Commit Graph

278 Commits (more_events)
 

Author SHA1 Message Date
Jose M. Guisado fc2b4b145f ogClient: add supported events to live mode
Live mode supports poweroff, reboot and boot events. This events serve
to send out-of-band requests to ogClient in order to run any of the
supported processes.

Live mode does not support any event datagram related to user session
notification.

XXX: Check if client is busy before processing the event.
2023-10-05 16:33:00 +02:00
Jose M. Guisado 1e92aa4262 ogClient: open event socket in live mode
Listen for event datagrams at UDP port 55885 in live mode too. The same
as when running Linux or Windows mode.
2023-10-05 16:32:40 +02:00
Jose M. Guisado 457a912749 live: drop IniciarSesion script when uefi booting
Replace IniciarSesion script in favor of native Python code when booting
a UEFI system. This applies when running the "session" command.

WIP: Only UEFI boots Windows systems. Raise NotImplementedError
exception trying to boot a Linux system using UEFI.
2023-09-13 15:18:11 +02:00
Jose M. Guisado a72ad3e637 utils: add boot.py
Add utility module related to the process of booting a system from a
client's partition.

The main utility function to boot a clients system is boot_os_at(), from
which firmware (UEFI or BIOS) and os-family specific private functions are invoked.

This initial commit adds UEFI windows boot function.
2023-09-13 15:18:11 +02:00
Jose M. Guisado 65f1cbc7eb utils: add uefi.py
Add UEFI related utilities inside a new utility module: uefi.py

	_check_efibootmgr_json
	======================
Check if the system efibootmgr executable supports JSON output. This is
a private function used only by other functions from uefi.py.

	is_uefi_supported
	=================
Check if the system supports UEFI firmware.

	run_efibootmgr_json
	===================
Runs efibootmgr with json output support. Return the JSON output as a
Python dict.

	efibootmgr_create_bootentry
	===========================
Create nvram boot entry. This bootentry is usually later set to boot
next just once via "BootNext" nvram variable.

	efibootmgr_delete_bootentry
	===========================
Delete a nvram boot entry. Used to avoid duplicates when booting the
same disk and partition from a given client.

	efibootmgr_bootnext
	===================
Set nvram "BootNext" variable to a given boot entry so after client
reboot, PXE is not executed and the given boot entry takes precedence.

Add dependency with efibootmgr version >= 18, and efibootmgr JSON output
which is currently out of tree from util-linux repo.
2023-09-13 15:18:03 +02:00
Jose M. Guisado a49988a222 probe: add basic os family detection
Add a basic OS family enumeration: OSFamily.

Add utility function that probes for an installed Linux or Windows
system, returns the corresponding enum value, OSFamily.UNKNOWN
otherwise.
2023-09-13 11:19:12 +02:00
Jose M. Guisado 8296ba9a51 disk: add get_efi_partition function
Add utility function inside disk.py to find, if any, the first ESP
partition of a given disk.

The disk is provided as an integer (starting at 1 following OpenGnsys
scripts usual values), meaning the (n-1)th disk from the disk array
returned from get_disks(). In the future a better mechanism should be
put in place to fetch probed disks from a running client.

This change is part of the upcoming drop of "IniciarSesion" script in
favor of a Python native approach. Specifically regarding UEFI systems.
2023-09-13 11:16:24 +02:00
Jose M. Guisado 49038f125a src: improve logging messages
Some users have mistakenly reported tiptorrent problems when the process
takes a long time. Specifically by rebooting or powering off the client
in the middle of the md5sum computation stage, just after the tiptorrent
transfer.

Same problem occurs when image creation command takes a long period of
time.

In order to help the user understand the different stages of commands
such as image creation or image restore using tiptorrent, the following
changes have been made to the current logging solution:

- Add log messages to warn users not to reboot or shut down the client
  during a tiptorrent transfer, and also during the md5sum computation
  stage.

- Add a log message telling the user that the image creation processes
  have started.

- Use logging.exception inside "except:" blocks to print a traceback
  with the log messsage.
  (https://docs.python.org/3/library/logging.html#logging.exception)
2023-08-01 18:26:10 +02:00
Jose M. Guisado ee0d62db44 hw_inventory: use dict.get
The first stage of parsing the "lshw -json" command output is to load
the json string into a Python dictionary. lshw output is large and
varies from machine to machine, so it's not safe to assume that
different keys will be present in the dictionary.

Use dict.get() instead of dict[key] to avoid KeyError exceptions.
2023-07-21 11:55:25 +02:00
Jose M. Guisado 035995fc8c live: add image backup option in image creation
Backup image file if image creation request included

	"backup": true

This only applies when the target image is already present in the
repository folder before running the partclone subprocess.

This parameter is ignored if the target image is not present in the
repository.
2023-07-06 17:52:52 +02:00
Jose M. Guisado 5c3cf47023 rest: add backup parameter
Support parsing of "backup" parameter inside incoming requests.

Prepare ogClient support for backup image creation in "image create"
operation.
2023-07-06 17:38:32 +02:00
Jose M. Guisado 0c03d82ca8 ogclient: add support for X-Sequence header
Enable parsing of "X-Sequence" HTTP headers from incoming requests.
Add "seq" field in restRequest class.

Enable adding "X-Sequence" to outgoing responses.
Add "seq" field inside restResponse class.

Store current client sequence number inside ogClient class.

Ideally, the restRequest object should be used to retrieve the
sequence number but not all processing functions inside ogRest.py
receive the request as parameter (eg: process_refresh).
In the other hand, all processing functions receive the ogClient object.
2023-06-14 14:50:55 +02:00
Jose M. Guisado 926a73cf33 fs: fix subprocess input inside _extend_resize2fs
The subprocess module expects bytes-like object for "input" parameter by
default. Passing a string object result in the following error:

(2023-06-13 14:44:43) ogClient: [ERROR] - Exception when running "image create" subprocess
(2023-06-13 14:44:43) ogClient: [ERROR] - Unexpected error
Traceback (most recent call last):
  File "/opt/opengnsys/ogClient/src/live/ogOperations.py", line 465, in image_create
    ogExtendFs(disk, partition)
  File "/opt/opengnsys/ogClient/src/utils/fs.py", line 124, in ogExtendFs
    _extend_ntfsresize(partdev)
  File "/opt/opengnsys/ogClient/src/utils/fs.py", line 250, in _extend_ntfsresize
    proc = subprocess.run(cmd, input='y')
  File "/usr/lib/python3.8/subprocess.py", line 495, in run
    stdout, stderr = process.communicate(input, timeout=timeout)
  File "/usr/lib/python3.8/subprocess.py", line 1013, in communicate
    self._stdin_write(input)
  File "/usr/lib/python3.8/subprocess.py", line 962, in _stdin_write
    self.stdin.write(input)
TypeError: a bytes-like object is required, not 'str'

Fixes: dd999bfe34 ("utils: rewrite ogReduceFs")
2023-06-13 17:34:20 +02:00
Jose M. Guisado 88668cb195 fs: fix bug when ntfsresize reports nothing to do
There is a corner case in which a target NTFS filesystem is already
shrunken. When this happens ntfsresize text output parsing breaks.

Check when ntfsresize reports nothing to do, warn the user about this
and stop the dry-run ntfsresize loop.
2023-06-13 17:34:04 +02:00
Jose M. Guisado 666d2fb50f fs: fix typo inside _extend_resize2fs
_extend_ntfsresize contains an incorrect variable name inside
subprocess.run referring the resize command value.

Simplify this variable name inside each specific _extend_* function:

	s/cmd_resize2fs/cmd
	s/cmd_ntfsresize/cmd
2023-06-13 09:06:13 +02:00
Jose M. Guisado fa51f2be8f src: remove unused legacy software inventory code
Remove unnecessary InventarioSoftware invocation inside image_create
operation. Software inventory is executed after image creation
(see ogRest.py).

Remove legacy 'path' parameter. This parameter was used to specify the
path of a text file in which legacy bash scripts wrote the software
inventory of the client (something like "Csft-{ip}...").

Fixes: 04bb35bd86 ("live: rewrite software inventory")
Fixes: 2e3d47b7b8 ("Avoid writting /software output to a file")
2023-05-17 12:44:50 +02:00
Jose M. Guisado 0c6dd12f4c sw_inventory: ignore invalid windows programs
Don't raise exception if any windows program is missing DisplayName
node in the windows registry.

This attribute/node should contain the program's name. This name is used
as the package's name in the software set (software inventory).

This patch should be considered a hotfix, python-hivex does not report
any helpful message about this error.

(2023-05-09 14:43:13) ogClient: [ERROR] - Unexpected error
Traceback (most recent call last):
[...]
RuntimeError: Success

Before this patch, image creation *might* fail because it cannot create
the software inventory associated with the image due to the previously
described error. The software inventory is part of the response payload
of the image creation command (see src/ogRest:image_create).

Fixes: 04bb35bd86 (live: rewrite software inventory)
2023-05-09 17:04:27 +02:00
Jose M. Guisado 66a464f7d0 live: rewrite reboot operation
Add optional 'operation' parameter to _poweroff_oglive function.
Reuse _poweroff_oglive code before the busybox subprocess when rebooting
an ogLive client.
2023-05-09 13:09:07 +02:00
Jose M. Guisado ef06618a8c live: rewrite poweroff operation
Replace legacy bash script /opt/opengnsys/client/scripts/poweroff with a
Python native solution.

Use subprocess module for any required external program when shutting
down a client. ethtool is used to ensure WoL setting is correct before
shutting down.

ogLive does not properly use a init system so busybox is used when
shutting down the system. In other live environments poweroff operation
just calls /sbin/poweroff.
2023-05-09 13:09:07 +02:00
Jose M. Guisado cf6f50e528 utils: add umount_all function
Add utility function to unmount any mountpoint present in the /mnt
folder.

This function is a simplified version of the legacy bash function
ogUnmountAll used in several operations.
2023-05-09 13:09:07 +02:00
Jose M. Guisado 803ba74510 utils: rewrite ogExtendFs
Drop subprocess call to bash function ogExtendFs. Use a native python
solution with subprocess calls to the required underlying tools.

Use get_filesystem_type to get the present filesystem from a partition
and call the corresponding filesystem grow function.

Filesystem specific functions are declared "_extend_{filesystem}" and
should not be imported elsewhere.

Each filesystem specific function wraps a subprocess call to the
required underlying program:

- NTFS filesystems: "ntfsresize -f [partition]"
- ext4 filesystems: "resize2fs -f [partition]"

Set NTFS related subprocess stdin to 'y' because human input cannot be
unset with other ntfsresize parameters.
2023-05-09 13:09:02 +02:00
Jose M. Guisado dd999bfe34 utils: rewrite ogReduceFs
Drop subprocess call to bash function ogReduceFs. Use a native python
solution with subprocess calls to the required underlying tools.

Use get_filesystem_type to get the filesystem from a partition and call
the corresponding supported filesystem shrink function.

Filesystem specific functions are declared "_reduce_{filesystem}" and
should not be imported elsewhere.

In case of NTFS filesystems, the output of 'ntfsresize' is processed
directly. This is dirty, but we can expect no changes to the output
strings if we read the following comment in the nftsresize.c source
code:
https://github.com/tuxera/ntfs-3g/blob/edge/ntfsprogs/ntfsresize.c#L12

ntfsresize requires to do previous dry-run executions to confirm
that the resizing is possible.
If a dry-run fails but a 10% increase in size is still smaller than
original filesystem then retry the operation until dry-run reports
sucess or the size increase is bigger than original.

If resizing to a smaller ntfs filesystem is not possible then ogReduceFs
will do nothing.
2023-05-02 17:31:08 +02:00
Jose M. Guisado 22dce48d3e utils: add get_filesystem_type function
Retrieve filesystem type from a partition using get_filesystem_type.
Encapsulates a subprocess call to blkid.
2023-04-25 13:33:45 +02:00
Jose M. Guisado 2ddea6d514 src: add missing copyright notices 2023-04-18 17:26:40 +02:00
Jose M. Guisado ee80dc89ad live: rewrite hardware inventory command
Replace legacy shell script InventarioHardware for helper functions
from hw_inventory.py

Use get_hardware_inventory to obtain a HardwareInventory object with
the hardware information. Map the HardwareInventory object to a legacy
response string with the legacy_list_hardware_inventory function.

Remove "Chrd-*" file reading logic, it's no longer needed. Legacy shell
script InventarioHardware uses that file.

Expect a change in the structure of hardware inventory response payload
in the future. This patch does not address the HTTP response containing
the hardware inventory as a '\n' separated string of hardware elements.
2023-04-18 17:15:57 +02:00
Jose M. Guisado 49a86bddd9 utils: add hw_inventory.py
hw_inventory.py defines classes and helpers functions enabling
fetching of hardware inventory from a running client.

Uses a subprocess call to the command 'lshw -json' to obtain hardware
information.

Relevant public functions:

> get_hardware_inventory()
	Main function encapsulating subprocess and output processing
	logic.
	Returns a HardwareInventory object.

> legacy_list_hardware_inventory(inventory)
	Legacy string representation of parameter HardwareInventory object
2023-04-18 12:02:29 +02:00
Jose M. Guisado 4c0904d8da utils: rename inventory.py to sw_inventory.py
Rename software inventory file to sw_inventory to better distinguish
it from a future hardware inventory code.

In the future sw_inventory and hw_inventory might be merged together
once each file is tidied up.
2023-04-18 10:58:00 +02:00
Jose M. Guisado 04bb35bd86 live: rewrite software inventory
Replace legacy bash script in favor of Python code. Improves error
traceability and further development.

The software inventory operation mounts the target partition and it
fetches the list of installed software (package set). Once the
operation is complete, it unmounts the target partition.

For Windows, introduce hivex library python bindings for accessing
Windows registry hive files (https://libguestfs.org/hivex.3.html).

This operation is still processed by legacy code in the server side
(ogAdmServer.c in ogServer). Legacy backend process expects the software
inventory like the following example:

"software": "Windows 10 Enterprise Evaluation 2004 \nIntel(R) Network Connections 24.0.0.11 24.0.0.11 ..."

The os name is inserted first in this list followed by a '\n' separated
string of the software packages.

The legacy server code can be found in function actualizaSoftware at
ogServer/src/ogAdmServer.c

It is expected for software inventory payload to change in the future to
a simpler solution using just a json array of strings.
2023-03-27 15:48:03 +02:00
Jose M. Guisado 2172f00cde live: fix ogChangeRepo invocation
Add missing samba credentials parameter in ogChangeRepo invocation.

Credentials are loaded from ogClient config file.

Any production deployment should use its own samba user and password.
ogChangeRepo fails when using default samba credentials in a production
environment.

Fixes: a1edbe904b ("legacy: rewrite ogChangeRepo")
Fixes: 3703fd6063 ("live: support native unicast cache image restore")
2023-03-27 15:48:03 +02:00
Jose M. Guisado c0e14e0c95 live: fix unicast cache error log message
Removes undefined 'repo' variable from error logging message.

This caused the traceback to be polluted with an unhelpful message
about this variable being undefined.

Fixes: 3703fd606 ("live: support native unicast cache image restore")
2023-03-27 15:48:03 +02:00
Jose M. Guisado 0ebcd9f776 live: add linux swap parttype
Adds linux swap partition type, mapped to the 'LINUX-SWAP' string in web
interfaces like ogCP or webconsole.

Fixes: 29c53e54e9 ("live: add parttypes.py")
2023-03-23 09:49:46 +01:00
Jose M. Guisado 97e753cbfd ogRest: improve error logging when executing operations
Capture all possible Python exceptions in the try/except block of every
opengnsys operation.

Create an error handling function to deduplicate code in the except
block. The error handling function resets the ogRest state to IDLE and
sends the corresponding 500 Internal Server Error.

This *does not cover* every possible error. There are functions inside
ogThread which contain code that may raise errors that are not covered
by any try/except block.
2023-03-10 11:26:46 +01:00
Jose M. Guisado 5b5ef607ec ogRest: remove root logger constant
Remove unnecesary root logger constant: LOGGER

The root logger is used by default when executing:

	logging.debug()
	logging.info()
	logging.warning()
	...

There is no point in doing:

	LOGGER = logging.getLogger()  # Get root logger
	LOGGER.debug()  # Use root logger
2023-03-10 11:26:46 +01:00
Jose M. Guisado b58ccca48b legacy: improve readability of ogGetImageInfo helper functions
Change the name of the helper functions used when getting opengnsys
image information (legacy ogGetImageInfo bash script). As of now the
process consist of decompressing the image file with lzop and feeding
that output to partclone.info.

Prefer a more explicit function name rather than "process_image_*"

Add comment about skipping the first two lines of partclone.info output.
Usually, partclone.info starts printing out these two lines that are not
related to the partclone image information:

	Partclone v0.3.23 http://partclone.org
	Showing info of image (-)

As long as partclone.info output doesn't change we'll be fine, but we
should not depend on human readable output. This might change in the
future (i.e. adding json output format to partclone.info).
2023-03-10 11:26:42 +01:00
Jose M. Guisado c9a3a763dd legacy: rewrite ogGetImageInfo
Rewrites this legacy script behavior using native Python code, using
subprocess module when executing programs like partclone.info or lzop

ogGetImageInfo is a bash script that retrieves information regarding an
OpenGnsys partition image, specifically:

- clonator
- compressor
- filesystem
- datasize (size of the partition image)

This rewrite only supports partclone and lzop compressed images. This is
standard behavior, we have no reports of other programs or compression
algorithms in use.

Keep this legacy function with hungarian notation to emphasize this is
still a legacy component that may be replaced in the future.
2023-03-02 13:15:10 +01:00
Jose M. Guisado a1edbe904b legacy: rewrite ogChangeRepo
Drop ogChangeRepo Bash script in favor of a native Python
approach. Use only necessary subprocess calls instead of bringing
all the logic of this function into a Bash script black box.

ogChangeRepo unmounts the current OpenGnsys image samba folder
(/opt/opengnsys/images) and mounts (connects to) a new directory using
the new provided ip address. Keeping access mode from previous mount.
If anything goes wrong when mounting the new directory, it will fallback
to mounting the previous directory.

If no previous OpenGnsys image samba directory is detected, this
functions tries to mount the new directory anyway. In this case,
it will raise CalledProcessError if something goes wrong.
2023-03-02 09:33:33 +01:00
Jose M. Guisado 1858950af1 legacy: improve readability of cambiar_accesso
Expand function docstring and do not use CalledProcessError handling to
return True or False. Just checking for returncode value is simpler.
2023-03-02 09:09:39 +01:00
Jose M. Guisado 782f46a199 live: rewrite setup operation
Rewrites the setup operation using python-libfdisk module instead of an
external bash script. Consolidating the operation into Python's code,
limiting external subprocesses to well known programs and small
concrete tasks that are difficult to fully integrate into Python.

Use parttypes.py to fetch partition types from python-libfdisk module.
Use fs.py to create any specified supported filesystem.

OpenGnsys cache partitions are created labelling the partition as
"CACHE". Stops setting non-standard MBR hexcode (0xca) to the cache
partition in addition to the filesystem label.

Any partition specified as type EMPTY will be ignored.
2023-02-09 13:26:06 +01:00
Jose M. Guisado 7801d483d4 utils: add init_cache function
init_cache() creates the default directory in which OpenGnsys stores
images when using any cache enabled transfer method.

As of this commit this folder must exist for tiptorrent.py to
work properly.

Subprocess Popen object inside tiptorrent.py use
'cwd' optional parameter like:

	cwd='/opt/opengnsys/cache/opt/opengnsys/images/'

This folder convention might change in the future.
2023-02-08 17:11:44 +01:00
Jose M. Guisado eac942660f utils: add fs.py
Adds utility module which wraps several mkfs.* calls as a subprocess.

The main utility function is mkfs(fs, disk, partition, label), which
subsequently calls the corresponding mkfs_*(partition_device) function.

mkfs() supports specifying a drive label where supported.

Other modules using fs.py should call mkfs() only.
2023-02-08 17:11:44 +01:00
Jose M. Guisado 29c53e54e9 live: add parttypes.py
Adds parttypes.py module with utility functions to get partition types
(parttypes) from python-libfdisk.

Supports standard partition types, either DOS or GPT.
DOS labels use a hex code to define partition types, python-libfdisk
exposes get_parttype_from_code to look up for DOS partition types from a
given hexcode.
GPT label uses a string (UUID) for each supported partition type,
python-libfdisk exposes get_parttype_from_string to look up for GPT
partition types from a given string.
2023-02-08 17:11:44 +01:00
Jose M. Guisado c010c42008 live: clear ogbrowser log before image_create
Remove any previous unrelated log message shown in the "real time log"
html page before executing this command.
2022-12-05 16:37:35 +01:00
Jose M. Guisado 7f6a7b664b log: add file handler for ogLive "real time log"
Clients running in ogLive can show log messages via a lighttp server.
Particularly, a html page named "real time log" consists of <text-area>
tags with the contents of two particular text files
/tmp/session.log and /tmp/command.log

Adds a Python logging handler in order to write ogClient log messages
into /tmp/session.log. This way ogClient logs are show in the "real time
log" html page too.
2022-12-05 16:19:57 +01:00
Jose M. Guisado 70f1d0d71d live: clear ogbrowser logs before image_restore
Clears content of blue text areas in the real time log view before
executing a restore image operation.

Adds private function _ogbrowser_clear_logs, this function writes to a
couple of text files present in the ogLive environment.
The contents of this file are printed out to the blue text areas
in the "real time log" view.
2022-12-01 15:22:58 +01:00
Jose M. Guisado 699a6c242a live: improve error paths
Fix error paths in live operations which do not
reset the "browser" to the main page (one with the menu).

Add error logging messages when:

* _restartBrowser fails.
* ogChangeRepo fails.

Improve checksum fetch error handling. For example, when an invalid
repository IP is specified.
2022-11-17 15:55:42 +01:00
Javier Sánchez Parra 94f6793f96 log: declare samba handler only in live mode
ogClient in linux mode only write its logs to syslog and the console.

Also, raise exception if mode its not supported.
2022-11-02 16:37:46 +01:00
Javier Sánchez Parra f1fff0b0b6 log: import fcntl only on linux
Otherwise, ogClient do not work on Windows because fcntl module do not
exists on Windows.
2022-11-02 16:37:41 +01:00
Jose M. Guisado 3703fd6063 live: support native unicast cache image restore
UNICAST-CACHE consist of:

1. Checking if the target image is already present at the opengnsys
   cache partition. If so, check for integrity (local and remote
   checksum). If the image is not present in the cache partition,
   download the target image into it.
2. Restore the image from cache partition.

This commit add support for this operation natively from ogClient
Python's code.
2022-11-02 14:09:39 +01:00
Jose M. Guisado 55c76c9d70 tiptorrent: improve raised exceptions for tip_client_get
Raise exception when tiptorrent-client subprocess runs normally but
exits with non-zero code. (For example, if download file allocation
failed)
2022-09-29 13:24:43 +02:00
Jose M. Guisado f2515fcde9 live: don't use python open() when reading image
Specifies the image path in the lzop subprocess string.

It might be interesting to study efficient mechanisms to read large
binary files in python before using open() with default parameters for
buffered binary reading.
2022-09-23 12:12:35 +02:00