diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..7d03613 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,26 @@ +root = true + +[*] +indent_style = space +indent_size = 4 +insert_final_newline = true +trim_trailing_whitespace = true + +[*.rs] +charset = utf-8 +max_line_length = 120 + +[*.toml] +indent_style = space +indent_size = 2 + +[*.yml] +indent_style = space +indent_size = 2 + +[*.md] +trim_trailing_whitespace = false + +[*.sh] +indent_style = space +indent_size = 4 diff --git a/.github/labeler.yml b/.github/labeler.yml index d306538..b0d63c9 100644 --- a/.github/labeler.yml +++ b/.github/labeler.yml @@ -1,12 +1,22 @@ -rust: -- **/**/*.rs - dependencies: - Cargo.toml -- **/Cargo.toml -- **/Cargo.lock +- isototest/Cargo.toml +- isototest/Cargo.lock +- isotoenv/Cargo.toml +- isotoenv/Cargo.lock +- isotomachine/Cargo.toml +- isotomachine/Cargo.lock - Cargo.lock +isototest: +- isototest/* + +isotomachine: +- isotomachine/* + +isotoenv: +- isotoenv/* + documentation: - docs/** - README.md diff --git a/.gitignore b/.gitignore index ae12eb9..106ff17 100644 --- a/.gitignore +++ b/.gitignore @@ -13,10 +13,13 @@ Cargo.lock # MSVC Windows builds of rustc generate these, which store debugging information *.pdb - # Added by cargo - /target # Local test binary vnc-test/ + +# Editor Configs +.idea/ +.vscode/ +.lvim-config.lua diff --git a/docs/CONTRIBUTING.md b/docs/CONTRIBUTING.md index 98d5aff..6566a3a 100644 --- a/docs/CONTRIBUTING.md +++ b/docs/CONTRIBUTING.md @@ -42,14 +42,3 @@ Code without tests might be rejected or take longer to process. If you discover a security vulnerability in our code, please inform us privately immediately according to our [Security Policy](./SECURITY.md). If you wish to fix a vulnerability, please also inform us and stand by for our green light. We would still like to investigate the vulnerability for ourselves to get an overview over the severity and scope of the problem. *Please refrain from publishing a fix until we came back to you or have published a security advisory*. - -## Disclaimer - -By contributing to this project you agree to surrender your contribution to the Nazara Project. - -Your contribution to this project will be subject to the same licensing terms as the rest of the project. - -This is a standard practice in open-source projects to ensure that all contributions are compatible with the project's overall license and to maintain consistency in the project's legal framework. - -It's important for contributors to be aware of this agreement to ensure that their contributions are properly integrated into the project without any legal conflicts. -#### Thank you for your contribution! diff --git a/docs/SECURITY.md b/docs/SECURITY.md index 2891627..b35d08a 100644 --- a/docs/SECURITY.md +++ b/docs/SECURITY.md @@ -3,7 +3,7 @@ ## Reporting a Vulnerability If you discover a security vulnerability in this project, please report it by emailing the -[project owner](mailto:christopher-hock@protonmail.com). Please provide detailed information about the vulnerability, +[project owner](mailto:christopher-hock@suse.com). Please provide detailed information about the vulnerability, including steps to reproduce, possible ways of exploitation and any relevant details about your environment. We appreciate responsible disclosure. @@ -22,8 +22,3 @@ dependencies which you may be planning to introduce to the project beforehand to This security policy is subject to change. It is the responsibility of all project contributors and users to stay updated on any modifications. By participating in this project, you agree to abide by this security policy. - -Nazara is designed to run only within your local network. The user is responsible for their network setup -themselves. - -We are not liable for any damages that are caused by insufficient network security. diff --git a/isotoenv/.gitignore b/isotoenv/.gitignore new file mode 100644 index 0000000..3c0d3d2 --- /dev/null +++ b/isotoenv/.gitignore @@ -0,0 +1,21 @@ +# Generated by Cargo +# will have compiled files and executables +debug/ +target/ + +# Remove Cargo.lock from gitignore if creating an executable, leave it for libraries +# More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html +Cargo.lock + +# These are backup files generated by rustfmt +**/*.rs.bk + +# MSVC Windows builds of rustc generate these, which store debugging information +*.pdb + +# Added by cargo +/target + +# Editor Configs +.idea/ +.vscode/ diff --git a/isotoenv/Cargo.toml b/isotoenv/Cargo.toml new file mode 100644 index 0000000..c8b454e --- /dev/null +++ b/isotoenv/Cargo.toml @@ -0,0 +1,18 @@ +[package] +name = "isotoenv" +version = "0.1.0" +edition = "2021" +description = "A library for creating an openQA test environment on a designated target" +readme = "README.md" +repository = "https://github.com/os-autoinst/isotest-ng/tree/main/isotoenv" +license = "GPL-2.0" + +[dependencies] +log = "0.4.22" +env_logger = { version = "0.11.5", optional = true } + +[dev-dependencies] + +[features] +# Feature to enable default logging configuration +default-logging = ["env_logger"] diff --git a/isotoenv/LICENSE b/isotoenv/LICENSE new file mode 100644 index 0000000..d159169 --- /dev/null +++ b/isotoenv/LICENSE @@ -0,0 +1,339 @@ + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Lesser General Public License instead.) You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along + with this program; if not, write to the Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author + Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + , 1 April 1989 + Ty Coon, President of Vice + +This General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may +consider it more useful to permit linking proprietary applications with the +library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. diff --git a/isotoenv/README.md b/isotoenv/README.md new file mode 100644 index 0000000..cfd345e --- /dev/null +++ b/isotoenv/README.md @@ -0,0 +1,3 @@ +# isotoenv + +Set up a [openQA](https://open.qa) test environment on a remote worker. diff --git a/isotoenv/src/errors/mod.rs b/isotoenv/src/errors/mod.rs new file mode 100644 index 0000000..ad22c76 --- /dev/null +++ b/isotoenv/src/errors/mod.rs @@ -0,0 +1,3 @@ +//! This module defines custom error types to be returned by `isototest`. +//! These types are thematically split into submodules. +pub mod util_errors; diff --git a/isotoenv/src/errors/util_errors.rs b/isotoenv/src/errors/util_errors.rs new file mode 100644 index 0000000..40ba78e --- /dev/null +++ b/isotoenv/src/errors/util_errors.rs @@ -0,0 +1,28 @@ +//! This module defines and implements error type which refer to the supporting util of this library. +//! This means functionality like logging and similar supporting functionality, which do not necessarily +//! impact the core functionality of this library itself. +use std::fmt; + +#[derive(Debug)] +#[cfg(feature = "default-logging")] +pub enum LoggingError { + LoggingInitError(String), + InvalidLogLevelError(String), +} + +#[cfg(feature = "default-logging")] +impl fmt::Display for LoggingError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + LoggingError::LoggingInitError(msg) => { + write!(f, "[error] Logging initialization failed: '{}'", msg) + } + LoggingError::InvalidLogLevelError(msg) => { + write!(f, "[error] Invalid log level: '{}'", msg) + } + } + } +} + +#[cfg(feature = "default-logging")] +impl std::error::Error for LoggingError {} diff --git a/isotoenv/src/lib.rs b/isotoenv/src/lib.rs new file mode 100644 index 0000000..d2f399f --- /dev/null +++ b/isotoenv/src/lib.rs @@ -0,0 +1,23 @@ +//! Prepare a test environment for [openQA](https://open.qa). +//! +//! This crate is responsible for preparing an `openQA` worker machine or VM for executing the test suite. +//! +//! ## Optional Features +//! +//! * `default-logging` - Provides you with a sensible logger configuration using the `env_logger` crate. + +// Organize library structure +pub mod errors; +pub mod logging; + +// Provide code on the root level of the library +#[cfg(feature = "default-logging")] +use crate::errors::util_errors::LoggingError; +#[cfg(feature = "default-logging")] +use crate::logging::init_default_logging; + +#[cfg(feature = "default-logging")] +pub fn init_logging(level: Option<&str>) -> Result<(), LoggingError> { + init_default_logging(level)?; + Ok(()) +} diff --git a/isotoenv/src/logging.rs b/isotoenv/src/logging.rs new file mode 100644 index 0000000..3cf5304 --- /dev/null +++ b/isotoenv/src/logging.rs @@ -0,0 +1,56 @@ +//! This module provides a sensible default configuration of a logging system. + +#[cfg(feature = "default-logging")] +use crate::errors::util_errors::LoggingError; +#[cfg(feature = "default-logging")] +use env_logger::Builder; +#[cfg(feature = "default-logging")] +use std::io::Write; + +pub const LOG_TARGET: &str = "[isototest]"; + +#[cfg(feature = "default-logging")] +/// Initialize default logging configuration with given log level. +/// +/// Log Level can be: +/// * "info" - Default log level also adapted if level is `none`. Logs events relevant for general usage. +/// * "debug" - Debug level for extended logging. Should only be used for development purposes. +/// * "trace" - Extensive log evel logging every event. Should only be used for development purposes. +/// +pub(crate) fn init_default_logging(level: Option<&str>) -> Result<(), LoggingError> { + match level { + Some("info") | None => { + log_builder(log::LevelFilter::Info); + Ok(()) + } + Some("debug") => { + log_builder(log::LevelFilter::Debug); + Ok(()) + } + Some("trace") => { + log_builder(log::LevelFilter::Trace); + Ok(()) + } + Some(invalid) => Err(LoggingError::InvalidLogLevelError(format!( + "Invalid log level '{}'!", + invalid + ))), + } +} + +#[cfg(feature = "default-logging")] +fn log_builder(level: log::LevelFilter) { + Builder::new() + .filter_level(level) + .format(|buf, record| { + writeln!( + buf, + "{} [{}] {}: {}", + buf.timestamp(), + record.level(), + record.target(), + record.args() + ) + }) + .init(); +} diff --git a/isotomachine/Cargo.toml b/isotomachine/Cargo.toml index 281dafe..b38dbec 100644 --- a/isotomachine/Cargo.toml +++ b/isotomachine/Cargo.toml @@ -8,4 +8,8 @@ repository = "https://github.com/ByteOtter/isotest-ng/tree/main/isotomachine" license = "GPL-2.0" [dependencies] -vnc-rs = "0.5.1" +env_logger = { version = "0.11.5", optional = true } +log = "0.4.22" + +[features] +default-logging = ["env_logger"] diff --git a/isotomachine/src/errors/mod.rs b/isotomachine/src/errors/mod.rs new file mode 100644 index 0000000..ad22c76 --- /dev/null +++ b/isotomachine/src/errors/mod.rs @@ -0,0 +1,3 @@ +//! This module defines custom error types to be returned by `isototest`. +//! These types are thematically split into submodules. +pub mod util_errors; diff --git a/isotomachine/src/errors/util_errors.rs b/isotomachine/src/errors/util_errors.rs new file mode 100644 index 0000000..40ba78e --- /dev/null +++ b/isotomachine/src/errors/util_errors.rs @@ -0,0 +1,28 @@ +//! This module defines and implements error type which refer to the supporting util of this library. +//! This means functionality like logging and similar supporting functionality, which do not necessarily +//! impact the core functionality of this library itself. +use std::fmt; + +#[derive(Debug)] +#[cfg(feature = "default-logging")] +pub enum LoggingError { + LoggingInitError(String), + InvalidLogLevelError(String), +} + +#[cfg(feature = "default-logging")] +impl fmt::Display for LoggingError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + LoggingError::LoggingInitError(msg) => { + write!(f, "[error] Logging initialization failed: '{}'", msg) + } + LoggingError::InvalidLogLevelError(msg) => { + write!(f, "[error] Invalid log level: '{}'", msg) + } + } + } +} + +#[cfg(feature = "default-logging")] +impl std::error::Error for LoggingError {} diff --git a/isotomachine/src/lib.rs b/isotomachine/src/lib.rs index 7d12d9a..b7b7175 100644 --- a/isotomachine/src/lib.rs +++ b/isotomachine/src/lib.rs @@ -1,14 +1,23 @@ -pub fn add(left: usize, right: usize) -> usize { - left + right -} +//! Prepare a [openQA](https://open.qa) test worker. +//! +//! This crate is responsible for setting up a `openQA` worker machine or VM. +//! +//! ## Optional Features +//! +//! * `default-logging` - Provides you with a sensible logger configuration using the `env_logger` crate. + +// Organize library structure +pub mod errors; +pub mod logging; -#[cfg(test)] -mod tests { - use super::*; +// Provide code on the root level of the library +#[cfg(feature = "default-logging")] +use crate::errors::util_errors::LoggingError; +#[cfg(feature = "default-logging")] +use crate::logging::init_default_logging; - #[test] - fn it_works() { - let result = add(2, 2); - assert_eq!(result, 4); - } +#[cfg(feature = "default-logging")] +pub fn init_logging(level: Option<&str>) -> Result<(), LoggingError> { + init_default_logging(level)?; + Ok(()) } diff --git a/isotomachine/src/logging.rs b/isotomachine/src/logging.rs new file mode 100644 index 0000000..3cf5304 --- /dev/null +++ b/isotomachine/src/logging.rs @@ -0,0 +1,56 @@ +//! This module provides a sensible default configuration of a logging system. + +#[cfg(feature = "default-logging")] +use crate::errors::util_errors::LoggingError; +#[cfg(feature = "default-logging")] +use env_logger::Builder; +#[cfg(feature = "default-logging")] +use std::io::Write; + +pub const LOG_TARGET: &str = "[isototest]"; + +#[cfg(feature = "default-logging")] +/// Initialize default logging configuration with given log level. +/// +/// Log Level can be: +/// * "info" - Default log level also adapted if level is `none`. Logs events relevant for general usage. +/// * "debug" - Debug level for extended logging. Should only be used for development purposes. +/// * "trace" - Extensive log evel logging every event. Should only be used for development purposes. +/// +pub(crate) fn init_default_logging(level: Option<&str>) -> Result<(), LoggingError> { + match level { + Some("info") | None => { + log_builder(log::LevelFilter::Info); + Ok(()) + } + Some("debug") => { + log_builder(log::LevelFilter::Debug); + Ok(()) + } + Some("trace") => { + log_builder(log::LevelFilter::Trace); + Ok(()) + } + Some(invalid) => Err(LoggingError::InvalidLogLevelError(format!( + "Invalid log level '{}'!", + invalid + ))), + } +} + +#[cfg(feature = "default-logging")] +fn log_builder(level: log::LevelFilter) { + Builder::new() + .filter_level(level) + .format(|buf, record| { + writeln!( + buf, + "{} [{}] {}: {}", + buf.timestamp(), + record.level(), + record.target(), + record.args() + ) + }) + .init(); +} diff --git a/isototest/Cargo.toml b/isototest/Cargo.toml index 3b8918b..b9d21d7 100644 --- a/isototest/Cargo.toml +++ b/isototest/Cargo.toml @@ -4,12 +4,20 @@ version = "0.1.0" edition = "2021" description = "A library for executing openQA test on workers" readme = "README.md" -repository = "https://github.com/ByteOtter/isotest-ng/tree/main/isototest" +repository = "https://github.com/os-autoinst/isotest-ng/tree/main/isototest" license = "GPL-2.0" [dependencies] +image = "0.25.2" +log = "0.4.22" tokio = "1.38.1" vnc-rs = "0.5.1" +env_logger = { version= "0.11.5", optional=true } +chrono = "0.4.38" [dev-dependencies] mockito = "1.4.0" + +[features] +# Feature to enable default logging configuration +default-logging = ["env_logger"] diff --git a/isototest/src/action.rs b/isototest/src/action/keyboard.rs similarity index 88% rename from isototest/src/action.rs rename to isototest/src/action/keyboard.rs index a3d8156..b5aa00a 100644 --- a/isototest/src/action.rs +++ b/isototest/src/action/keyboard.rs @@ -1,13 +1,20 @@ // SPDX-FileCopyrightText: Christopher Hock // SPDX-LicenseIdentifier: GPL-2.0-or-later -//! Action +//! # Keyboard Module //! -//! This module handles interactions between the VncClient and VncServer. +//! This module handles text-based interactions between the VncClient and VncServer. +//! +//! It uses [`X11Event::KeyEvent`](https://docs.rs/vnc-rs/0.5.1/vnc/event/struct.ClientKeyEvent.html) to send +//! individual key press or release events to the VNC server. +//! +//! To view what characters and control sequences are currently supported, see [`crate::types`]. extern crate proc_macro; use std::{thread::sleep, time::Duration}; +use log::info; use vnc::{client::VncClient, ClientKeyEvent, VncError, X11Event}; +use crate::logging::LOG_TARGET; use crate::types::{KeyCode, KeyEventType}; /// Sleep. @@ -25,7 +32,7 @@ macro_rules! wait_for_frame { }; } -/// Write given text to console +/// Send given text to VNC server. /// /// Uses `X11Event`s to send keypresses to the server. According to the [RFC](https://www.rfc-editor.org/rfc/rfc6143.html#section-7.5.4) /// it does not matter whether the X-Window System is running or not. @@ -34,6 +41,8 @@ macro_rules! wait_for_frame { /// /// * client: `&VncClient` - The client to be used for connections /// * text: `String` - The text to write. +/// * framerate: `Option` - The framerate of the remote machine. Used to time intervals in +/// which key signals are sent. If `None`, signal intervals are calculated according to a default. (30FPS) /// /// # Returns /// @@ -45,6 +54,7 @@ pub async fn write_to_console( framerate: Option, ) -> Result<(), VncError> { // Translate each character to a keycode + info!(target: LOG_TARGET, "Sending text '{}' with intervall of {}FPS....", text, framerate.unwrap_or(30 as f64)); let mut keycode: u32; for ch in text.chars() { @@ -65,18 +75,13 @@ pub async fn write_to_console( press_button(client, modifier, KeyEventType::Release, framerate).await?; } } + info!(target: LOG_TARGET, "Text '{}' sent.", text); Ok(()) } -#[allow(unused)] -/// Receive a screenshot of the remote machine. -pub async fn read_screen(client: &VncClient) -> Result<(), VncError> { - todo!("Not implemented yet!") -} - /// Encapsulate the `client.input()` function calls to avoid repitition. /// -/// Press and release a button or release it manually, if it is pressed. +/// Will put the given key into a state according to the [crate::types::KeyEventType] parameter. /// /// # Parameters /// @@ -192,7 +197,10 @@ fn framerate_to_nanos(rate: Option) -> Result { } } -/// Assign a given character its corresponding `VirtualKeyCode`. +/// Assign a given character its corresponding [`crate::types::KeyCode`]. +/// +/// Will return the u32 representation of the actualkeycode as this is required by +/// [`vnc-rs`](https://docs.rs/vnc-rs/0.5.1/vnc/event/struct.ClientKeyEvent.html) /// /// # Parameters /// diff --git a/isototest/src/action/mod.rs b/isototest/src/action/mod.rs new file mode 100644 index 0000000..e856867 --- /dev/null +++ b/isototest/src/action/mod.rs @@ -0,0 +1,3 @@ +//! This module is used to interact with the VNC server in any capacity. +pub mod keyboard; +pub mod view; diff --git a/isototest/src/action/view.rs b/isototest/src/action/view.rs new file mode 100644 index 0000000..55e0c51 --- /dev/null +++ b/isototest/src/action/view.rs @@ -0,0 +1,245 @@ +//! # View module +//! +//! This module handles everything related to requesting visual data from the VNC server. +use chrono::Utc; +use image::{DynamicImage, GenericImage, GenericImageView, ImageFormat, Rgba}; +use image::{ImageBuffer, RgbaImage}; +use std::path::PathBuf; +use std::{ + env, + path::Path, + time::{Duration, Instant}, +}; +use vnc::{Rect, VncClient, VncError, VncEvent, X11Event}; + +use log::{error, info, warn}; + +use crate::logging::LOG_TARGET; + +/// Receive a screenshot of the remote machine. +/// +/// # Parameters +/// +/// * client: `&VncClient` - The client instance used for connection. +/// * file_path: `Option<&Path>` - A file path you want to save your screenshot under as a `&Path`. +/// (If `None` -> `CWD` is set as output dir.) +/// * resolution: `Option` - The resolution of the VNC session. +/// * timeout: `Duration` - The `Duration` this function should wait for a `VncEvent` before it +/// continues. +/// +/// **NOTE**: The `resolution` must be passed to all calls of `read_screen` except the first one. +/// If it is not passed, the function will attempt to detect the resolution from the VNC server. +/// This only works for the first time though. The client cannot retrieve the resolution a second +/// time by itself as long as it has not changed. We recommend to save the `Ok()` return value of +/// the function so you have a global resolution state to return to when calling. +/// +/// # Returns +/// +/// * `Ok((u32, u32))` - The resolution of the VNC machine we connect to. +/// * `Err(VncError)` - Variation of `VncError` if something goes wrong. +pub async fn read_screen( + client: &VncClient, + file_path: Option<&Path>, + resolution: Option<(u32, u32)>, + timeout: Duration, +) -> Result<(u32, u32), VncError> { + info!(target: LOG_TARGET, "Requesting screenshot..."); + // Request screen update. + client.input(X11Event::Refresh).await?; + + let mut img_parts: Vec<(Rect, Vec)> = Vec::new(); + let mut width: Option; + let mut height: Option; + + // Try to detect screen resolution of the remote machine if it has not been passed. + // **This will cause issues, if you try to use this functionality a second time.** + match resolution { + Some((x, y)) => { + info!(target: LOG_TARGET, "Resolution provided; proceeding..."); + width = Some(x); + height = Some(y); + } + None => match client.recv_event().await? { + VncEvent::SetResolution(screen) => { + info!(target: LOG_TARGET, "Resolution received. Screen resolution: {}x{}", screen.width, screen.height); + width = Some(screen.width as u32); + height = Some(screen.height as u32); + + client.input(X11Event::Refresh).await?; + } + _ => { + error!(target: LOG_TARGET, "Failed to retrieve screen resolution. Aborting..."); + return Err(VncError::General( + "[error] No resolution found!".to_string(), + )); + } + }, + } + + let idle_timer: Instant = Instant::now(); + + loop { + // Poll new vnc events. + match client.poll_event().await? { + Some(x) => match x { + VncEvent::SetResolution(screen) => { + info!(target: LOG_TARGET, "Screen resolution: {}x{}", screen.width, screen.height); + width = Some(screen.width as u32); + height = Some(screen.height as u32); + + client.input(X11Event::Refresh).await?; + } + VncEvent::RawImage(rect, data) => { + img_parts.push((rect, data)); + } + VncEvent::Error(e) => { + error!(target: LOG_TARGET, "Error event received: {}", e); + return Err(VncError::General(e)); + } + x => { + warn!(target: LOG_TARGET, + "Function 'read_screen' got unexpected event '{:?}'.", + x + ); + break; + } + }, + None => { + if idle_timer.elapsed() >= timeout { + warn!(target: LOG_TARGET, "Timeout while waiting for VNC Event."); + break; + } + } + } + } + + let mut image: ImageBuffer, _> = ImageBuffer::new(width.unwrap(), height.unwrap()); + + // Reconstruct image from snippets sent by VNC server. + for (rect, data) in img_parts { + let mut view = image.sub_image( + rect.x as u32, + rect.y as u32, + rect.width as u32, + rect.height as u32, + ); + let image_buffer: ImageBuffer, _> = + ImageBuffer::from_raw(rect.width as u32, rect.height as u32, data.to_vec()) + .ok_or("Failed to create image buffer!") + .unwrap(); + + for x in 0..rect.width { + for y in 0..rect.height { + view.put_pixel( + x as u32, + y as u32, + image_buffer.get_pixel(x as u32, y as u32).to_owned(), + ); + } + } + } + + let mut prefix: PathBuf; + match file_path { + Some(x) => { + prefix = x.to_owned(); + } + None => { + let dir = env::current_dir()?; + prefix = dir.to_owned(); + } + } + + let last_modified_file: Option = std::fs::read_dir(&prefix) + .expect("Couldn't access local directory") + .flatten() // Remove failed + .filter(|f| f.metadata().unwrap().is_file()) // Filter out directories (only consider files) + .max_by_key(|x| x.metadata().unwrap().modified().unwrap()); // Get the most recently modified file + + prefix.push(format!("frame_{}.png", Utc::now())); + + match last_modified_file { + Some(x) => { + let prev_image: DynamicImage = image::open(x.path()).unwrap(); + // Layer the image data on top of the previous image. + let composed_image: DynamicImage = + compose_image(&prev_image, &DynamicImage::ImageRgba8(image)); + // image = prev_image.to_rgba8() + composed_image + .save_with_format(&prefix, ImageFormat::Png) + .unwrap(); + } + None => { + // Save image to file system in PNG format. + // NOTE: If the image color encoding is changed here, you must also change it in connection.rs! + DynamicImage::ImageRgba8(image) + .save_with_format(&prefix, ImageFormat::Png) + .unwrap(); + } + } + + info!(target: LOG_TARGET, "Screenshot saved to '{}'", prefix.to_str().unwrap()); + Ok((width.unwrap(), height.unwrap())) +} + +/// Compose new image data to the previous image and save copy. +/// +/// This is needed for subsequent calls of `read_screen` as the VNC server will only return the +/// last pixels changed since the previous request. +/// While this is handy for performance, it is no recommended for our use case as we need to have a +/// full picture of the screen to compare the current state of the test worker against expected +/// output. +/// +/// # Parameters +/// +/// * `base: &DynamicImage` - The image you want to lay the delta on top of. +/// * `overlay: &DynamicImage` - The new image data, which only includes this pixels that have +/// changed since the last screen request. +/// +/// # Returns +/// +/// * `DynamicImage` - New `DynamicImage` consisting of the already read parts of the screen +/// overlayed with the requested delta. +fn compose_image(prev_image: &DynamicImage, new: &DynamicImage) -> DynamicImage { + info!(target: LOG_TARGET, "Combining new pixel data with previous image."); + let (width, height): (u32, u32) = (prev_image.width(), prev_image.height()); + let mut new_image: RgbaImage = prev_image.to_rgba8(); + + for x in 0..width { + for y in 0..height { + let base_pixel: Rgba = prev_image.get_pixel(x, y); + let overlay_pixel: Rgba = new.get_pixel(x, y); + new_image.put_pixel(x, y, blend_pixels(base_pixel, overlay_pixel)); + } + } + DynamicImage::ImageRgba8(new_image) +} + +/// Blend two pixels together based on their alpha values (transparency). +/// +/// This function blends a pixel from the base image with a pixel from the overlay image. The +/// blending is done by considering the alpha (transparency) of the overlay pixel, which determines +/// how much of the overlay pixel should be visible over the base pixel. +/// +/// # Parameters +/// +/// * `base: Rgba` - The base pixel. +/// * `overlay: Rgba` - The pixel of the image you want to overlay. +/// +/// # Returns +/// +/// * `Rgba` - The pixel's new alpha value. +fn blend_pixels(base: Rgba, overlay: Rgba) -> Rgba { + let alpha_overlay: f32 = overlay[3] as f32 / 255.0; + + let func = |b, o| -> u8 { + (((b as f32 * (1.0 - alpha_overlay)) + (o as f32 * alpha_overlay)) * 255.0) as u8 + }; + + Rgba([ + func(base[0], overlay[0]), + func(base[1], overlay[1]), + func(base[2], overlay[2]), + 255 as u8, + ]) +} diff --git a/isototest/src/connection.rs b/isototest/src/connection.rs index 637c0fe..9de442a 100644 --- a/isototest/src/connection.rs +++ b/isototest/src/connection.rs @@ -1,12 +1,13 @@ // SPDX-FileCopyrightTest: Christopher Hock // SPDX-License-Identifier: GPL-2.0-or-later -//! # Connection Module -//! //! This module handles the VncClient and its connection to the VncServer. +use log::{debug, error, info}; use tokio::{self, net::TcpStream}; use vnc::{PixelFormat, VncClient, VncConnector, VncError}; +use crate::logging::LOG_TARGET; + /// Create a new VNC client. /// /// During the connection process the connection to the VNC server is @@ -31,35 +32,53 @@ pub async fn create_vnc_client( target_ip: String, mut psw: Option, ) -> Result { + info!(target: LOG_TARGET, "Creating VNC client for target IP: '{}'", target_ip); + if psw.is_none() { + debug!("No password provided; using empty password."); psw = Some(String::new()); } let tcp: TcpStream = match TcpStream::connect(target_ip).await { Ok(tcp) => tcp, Err(e) => { + error!(target: LOG_TARGET, "Failed to connect: {}", e); let err = VncError::IoError(e); return Err(err); } }; - let vnc: VncClient = VncConnector::new(tcp) + let vnc: VncClient = match VncConnector::new(tcp) .set_auth_method(async move { Ok(psw.unwrap()) }) .add_encoding(vnc::VncEncoding::Tight) .add_encoding(vnc::VncEncoding::Zrle) .add_encoding(vnc::VncEncoding::CopyRect) .add_encoding(vnc::VncEncoding::Raw) - .allow_shared(true) - .set_pixel_format(PixelFormat::bgra()) - .build()? - .try_start() - .await? - .finish()?; + .add_encoding(vnc::VncEncoding::Trle) + .add_encoding(vnc::VncEncoding::CursorPseudo) + .add_encoding(vnc::VncEncoding::DesktopSizePseudo) + .allow_shared(true) // Allow for multiple other VNC sessions to be connected at once. + // NOTE: If the color encoding is changed in the following line, you must also change it in + // view.rs to avoid the saved screenshots from having swapped colors. + .set_pixel_format(PixelFormat::rgba()) + .build() + { + Ok(vnc) => vnc, + Err(e) => { + error!(target: LOG_TARGET, "Failed to build VNC client: {}", e); + return Err(e); + } + } + .try_start() + .await? + .finish()?; + + info!("VNC Client successfully built and started."); Ok(vnc) } -/// Stop VNC engine, release all resources +/// Stop VNC engine, release all resources. /// /// # Parameters /// @@ -71,10 +90,17 @@ pub async fn create_vnc_client( /// * `Err(VncError)` - Escalates the `VncError` upwards, if the `.close()` function of `vnc-rs` /// returns an error. pub async fn kill_client(client: VncClient) -> Result<(), VncError> { + info!(target: LOG_TARGET, "Closing connection..."); match client.close().await { - Ok(_) => {} - Err(e) => return Err(e), + Ok(_) => { + info!(target: LOG_TARGET, "Connection closed."); + } + Err(e) => { + error!(target: LOG_TARGET, "Unable to close connection: {}", e); + return Err(e); + } }; drop(client); + info!(target: LOG_TARGET, "Client dropped."); Ok(()) } diff --git a/isototest/src/errors/mod.rs b/isototest/src/errors/mod.rs new file mode 100644 index 0000000..ad22c76 --- /dev/null +++ b/isototest/src/errors/mod.rs @@ -0,0 +1,3 @@ +//! This module defines custom error types to be returned by `isototest`. +//! These types are thematically split into submodules. +pub mod util_errors; diff --git a/isototest/src/errors/util_errors.rs b/isototest/src/errors/util_errors.rs new file mode 100644 index 0000000..1e5d977 --- /dev/null +++ b/isototest/src/errors/util_errors.rs @@ -0,0 +1,29 @@ +//! This module defines and implements error type which refer to the supporting util of this library. +//! This means functionality like logging and similar supporting functionality, which do not necessarily +//! impact the core functionality of this library itself. +#[cfg(feature = "default-logging")] // HACK: Until other error types implement fmt. +use std::fmt; + +#[derive(Debug)] +#[cfg(feature = "default-logging")] +pub enum LoggingError { + LoggingInitError(String), + InvalidLogLevelError(String), +} + +#[cfg(feature = "default-logging")] +impl fmt::Display for LoggingError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + LoggingError::LoggingInitError(msg) => { + write!(f, "[error] Logging initialization failed: '{}'", msg) + } + LoggingError::InvalidLogLevelError(msg) => { + write!(f, "[error] Invalid log level: '{}'", msg) + } + } + } +} + +#[cfg(feature = "default-logging")] +impl std::error::Error for LoggingError {} diff --git a/isototest/src/lib.rs b/isototest/src/lib.rs index 39cf48f..c3ed3c0 100644 --- a/isototest/src/lib.rs +++ b/isototest/src/lib.rs @@ -1,3 +1,76 @@ +//! Schedule and run tests for [openQA](https://open.qa). +//! +//! This crate's only responsibility is to schedule and run tests for the openQA project. +//! To this end it connects to the test environment on a remote worker machine (VM or bare metal) which has been prepared +//! by its two "sister-libraries" `isotoenv` and `ìsotomachine` via VNC and executes commands +//! specified by the openQA test to run. +//! +//! ## Example +//! +//! To use this crate, you need to create a `VncClient` instance, which will connect you to your +//! VNC server. This instance must be passed to any function which communicated with the VNC +//! server. +//! +//! ``` no_run +//! use isototest::connection::{create_vnc_client, kill_client}; +//! use isototest::action::keyboard::write_to_console; +//! use isototest::action::view::read_screen; +//! use tokio::{self}; +//! use std::process::exit; +//! +//! #[tokio::main] +//! async fn main() -> Result<(), Box> { +//! let addr = "127.0.0.1:5900"; +//! let psw = "password".to_string(); // Value irrelevant if the server does not use authentication. +//! let mut client = match create_vnc_client(addr.to_string(), Some(psw.clone())).await { +//! Ok(client) => { +//! println!("Client created. Handshake successful."); +//! client +//! }, +//! Err(e) => { +//! eprintln!("[Error] {:?}", e); +//! exit(1) +//! } +//! }; +//! +//! // Send a series of keypresses to the VNC server to type out the given text. +//! // Can be used to execute commands on the Terminal. +//! match write_to_console(&client, "Hello World!\n".to_string(), None).await { +//! Ok(_) => { +//! println!("Test text sent!"); +//! } +//! Err(e) => { +//! eprintln!("[error] {:?}", e); +//! exit(1); +//! } +//! } +//! +//! // Kill VNC connection and release resources. +//! kill_client(client).await?; +//! Ok(()) +//! } +//! ``` +//! +//! ## Optional Features +//! +//! * `default-logging` - Provides you with a sensible logger configuration using the `env_logger` +//! crate. + +// Organize library structure. pub mod action; pub mod connection; -mod types; +pub mod errors; +pub mod logging; +pub(crate) mod types; + +// Provide code on the root level of the library +#[cfg(feature = "default-logging")] +use crate::errors::util_errors::LoggingError; +#[cfg(feature = "default-logging")] +use crate::logging::init_default_logging; + +#[cfg(feature = "default-logging")] +pub fn init_logging(level: Option<&str>) -> Result<(), LoggingError> { + init_default_logging(level)?; + Ok(()) +} diff --git a/isototest/src/logging.rs b/isototest/src/logging.rs new file mode 100644 index 0000000..3cf5304 --- /dev/null +++ b/isototest/src/logging.rs @@ -0,0 +1,56 @@ +//! This module provides a sensible default configuration of a logging system. + +#[cfg(feature = "default-logging")] +use crate::errors::util_errors::LoggingError; +#[cfg(feature = "default-logging")] +use env_logger::Builder; +#[cfg(feature = "default-logging")] +use std::io::Write; + +pub const LOG_TARGET: &str = "[isototest]"; + +#[cfg(feature = "default-logging")] +/// Initialize default logging configuration with given log level. +/// +/// Log Level can be: +/// * "info" - Default log level also adapted if level is `none`. Logs events relevant for general usage. +/// * "debug" - Debug level for extended logging. Should only be used for development purposes. +/// * "trace" - Extensive log evel logging every event. Should only be used for development purposes. +/// +pub(crate) fn init_default_logging(level: Option<&str>) -> Result<(), LoggingError> { + match level { + Some("info") | None => { + log_builder(log::LevelFilter::Info); + Ok(()) + } + Some("debug") => { + log_builder(log::LevelFilter::Debug); + Ok(()) + } + Some("trace") => { + log_builder(log::LevelFilter::Trace); + Ok(()) + } + Some(invalid) => Err(LoggingError::InvalidLogLevelError(format!( + "Invalid log level '{}'!", + invalid + ))), + } +} + +#[cfg(feature = "default-logging")] +fn log_builder(level: log::LevelFilter) { + Builder::new() + .filter_level(level) + .format(|buf, record| { + writeln!( + buf, + "{} [{}] {}: {}", + buf.timestamp(), + record.level(), + record.target(), + record.args() + ) + }) + .init(); +} diff --git a/isototest/src/types.rs b/isototest/src/types.rs index 31a66a2..cab3bce 100644 --- a/isototest/src/types.rs +++ b/isototest/src/types.rs @@ -1,6 +1,8 @@ // SPDX-FileCopyrightText: Christopher Hock // SPDX-LicenseIdentifier: GPL-2.0-or-later +//! Common types for `isototest`. + /// Type of key press. /// /// # Members @@ -8,7 +10,7 @@ /// * `Press` - To signal a press and hold of the given key. /// * `Release` - To signal the release of a given key. /// * `Tap` - To signal a tap (press & release) of the given key. -pub enum KeyEventType { +pub(crate) enum KeyEventType { Press, Release, Tap, @@ -19,7 +21,7 @@ pub enum KeyEventType { /// /// Oriented on [this table](https://theasciicode.com.ar/ascii-printable-characters/exclamation-mark-ascii-code-33.html) /// Hex reprentations taken from [here](https://www.rfc-editor.org/rfc/rfc6143.html#section-7.5.4). -pub enum KeyCode { +pub(crate) enum KeyCode { NULL = 00, SOH = 01, STX = 02, diff --git a/vnc-test/src/main.rs b/vnc-test/src/main.rs index 62efa0e..1cb328a 100644 --- a/vnc-test/src/main.rs +++ b/vnc-test/src/main.rs @@ -1,9 +1,11 @@ use isototest::action::write_to_console; use isototest::connection::create_vnc_client; +use isototest::view::read_screen; use nix::sys::socket::{self, sockaddr_in, AddressFamily, SockType}; use std::process::exit; use std::process::{Command, Stdio}; use std::ptr::null_mut; +use std::time::Duration; use tokio::{ self, net::{TcpListener, TcpStream}, @@ -78,7 +80,7 @@ async fn main() -> Result<(), Box> { // let addr = vnc_server.srv.as_ref().unwrap().local_addr()?; let addr = ""; let psw = "password".to_string(); - let client = match create_vnc_client(addr.to_string(), Some(psw)).await { + let mut client = match create_vnc_client(addr.to_string(), Some(psw.clone())).await { Ok(client) => { println!("Client created. Handshake successful."); client @@ -89,7 +91,19 @@ async fn main() -> Result<(), Box> { } }; - match write_to_console(&client, include_str!("test.txt").to_string(), None).await { + let mut res; + match read_screen(&client, "screenshot.png", None, Duration::from_secs(1)).await { + Ok(x) => { + println!("Screenshot saved!"); + res = x; + }, + Err(e) => { + eprintln!("{}", e); + exit(1); + } + } + + match write_to_console(&client, include_str!("hello.txt").to_string(), None).await { Ok(_) => { println!("Test text sent!"); } @@ -99,5 +113,23 @@ async fn main() -> Result<(), Box> { } } + match read_screen(&client, "screenshot2.png", Some(res), Duration::from_secs(1)).await { + Ok(_) => { + println!("Screenshot saved!"); + }, + Err(e) => { + eprintln!("{}", e); + exit(1); + } + } + match read_screen(&client, "screenshot3.png", Some(res), Duration::from_secs(1)).await { + Ok(_) => { + println!("Screenshot saved!"); + }, + Err(e) => { + eprintln!("{}", e); + exit(1); + } + } Ok(()) }