Compare commits
81 Commits
c3c613fdea
...
231fb113a9
|
@ -0,0 +1,10 @@
|
|||
__pycache__
|
||||
.venv
|
||||
venvog
|
||||
*.deb
|
||||
*.build
|
||||
*.dsc
|
||||
*.changes
|
||||
*.buildinfo
|
||||
*.tar.gz
|
||||
*-stamp
|
|
@ -1,60 +0,0 @@
|
|||
# GitLib
|
||||
|
||||
The `gitapi.py` is an API for OgGit, written in Python/Flask.
|
||||
|
||||
It is an HTTP server that receives commands and executes maintenance actions including the creation and deletion of repositories.
|
||||
|
||||
|
||||
# Installing Python dependencies
|
||||
|
||||
The conversion of the code to Python 3 currently requires the packages specified in `requirements.txt`.
|
||||
|
||||
To install Python dependencies, the `venv` module is used (https://docs.python.org/3/library/venv.html), which installs all dependencies in an environment independent of the system.
|
||||
|
||||
|
||||
# Usage
|
||||
|
||||
|
||||
# Ubuntu 24.04
|
||||
|
||||
sudo apt install -y python3-flask python3-paramiko opengnsys-flask-executor opengnsys-flask-restx
|
||||
|
||||
The `opengnsys-flask-executor` and `opengnsys-flask-restx` packages are available on the OpenGnsys package server.
|
||||
|
||||
Run with:
|
||||
|
||||
./gitapi.py
|
||||
|
||||
**Note:** Run as `opengnsys`, as it manages the images located in `/opt/opengnsys/images`.
|
||||
|
||||
|
||||
# Documentation
|
||||
|
||||
Python documentation can be generated using a utility like pdoc3 (there are multiple possible alternatives):
|
||||
|
||||
# Install pdoc3
|
||||
pip install --user pdoc3
|
||||
|
||||
# Generate documentation
|
||||
pdoc3 --force --html opengnsys_git_installer.py
|
||||
|
||||
# Operation
|
||||
|
||||
## Requirements
|
||||
|
||||
The gitapi is designed to run within an existing opengnsys environment. It should be installed in an ogrepository.
|
||||
|
||||
## API Examples
|
||||
|
||||
### Get list of branches
|
||||
|
||||
$ curl -L http://localhost:5000/repositories/linux/branches
|
||||
{
|
||||
"branches": [
|
||||
"master"
|
||||
]
|
||||
}
|
||||
|
||||
### Synchronize with remote repository
|
||||
|
||||
curl --header "Content-Type: application/json" --data '{"remote_repository":"foobar"}' -X POST -L http://localhost:5000/repositories/linux/sync
|
|
@ -1,69 +0,0 @@
|
|||
# Git API
|
||||
|
||||
La `gitapi.py` es una API para OgGit, escrita en Python/Flask.
|
||||
|
||||
Es un servidor HTTP que recibe comandos y ejecuta acciones de mantenimiento incluyendo la creación y eliminación de repositorios.
|
||||
|
||||
|
||||
# Instalación de dependencias para python
|
||||
|
||||
La conversion del código a Python 3 requiere actualmente los paquetes especificados en `requirements.txt`
|
||||
|
||||
Para instalar dependencias de python se usa el modulo venv (https://docs.python.org/3/library/venv.html) que instala todas las dependencias en un entorno independiente del sistema.
|
||||
|
||||
|
||||
# Uso
|
||||
|
||||
|
||||
## Distribuciones antiguas (18.04)
|
||||
|
||||
sudo apt install -y python3.8 python3.8-venv python3-venv libarchive-dev
|
||||
python3.8 -m venv venvog
|
||||
. venvog/bin/activate
|
||||
python3.8 -m pip install --upgrade pip
|
||||
pip3 install -r requirements.txt
|
||||
|
||||
Ejecutar con:
|
||||
|
||||
./gitapi.py
|
||||
|
||||
|
||||
## Uso
|
||||
|
||||
**Nota:** Ejecutar como `opengnsys`, ya que gestiona las imágenes que se encuentran en `/opt/opengnsys/images`.
|
||||
|
||||
$ . venvog/bin/activate
|
||||
$ ./gitapi.py
|
||||
|
||||
|
||||
# Documentación
|
||||
|
||||
Se puede generar documentación de Python con una utilidad como pdoc3 (hay multiples alternativas posibles):
|
||||
|
||||
# Instalar pdoc3
|
||||
pip install --user pdoc3
|
||||
|
||||
# Generar documentación
|
||||
pdoc3 --force --html opengnsys_git_installer.py
|
||||
|
||||
# Funcionamiento
|
||||
|
||||
## Requisitos
|
||||
|
||||
La gitapi esta diseñada para funcionar dentro de un entorno opengnsys existente. Se debe instalar en un ogrepository.
|
||||
|
||||
## Ejemplo de API
|
||||
|
||||
### Obtener lista de ramas
|
||||
|
||||
$ curl -L http://localhost:5000/repositories/linux/branches
|
||||
{
|
||||
"branches": [
|
||||
"master"
|
||||
]
|
||||
}
|
||||
|
||||
### Sincronizar con repositorio remoto
|
||||
|
||||
curl --header "Content-Type: application/json" --data '{"remote_repository":"foobar"}' -X POST -L http://localhost:5000/repositories/linux/sync
|
||||
|
492
api/gitapi.py
492
api/gitapi.py
|
@ -1,492 +0,0 @@
|
|||
#!/usr/bin/env python3
|
||||
"""
|
||||
This module provides a Flask-based API for managing Git repositories in the OpenGnsys system.
|
||||
It includes endpoints for creating, deleting, synchronizing, backing up, and performing garbage
|
||||
collection on Git repositories. The API also provides endpoints for retrieving repository
|
||||
information such as the list of repositories and branches, as well as checking the status of
|
||||
asynchronous tasks.
|
||||
|
||||
Classes:
|
||||
None
|
||||
|
||||
Functions:
|
||||
do_repo_backup(repo, params)
|
||||
|
||||
do_repo_sync(repo, params)
|
||||
|
||||
do_repo_gc(repo)
|
||||
|
||||
home()
|
||||
|
||||
get_repositories()
|
||||
|
||||
create_repo(repo)
|
||||
|
||||
sync_repo(repo)
|
||||
|
||||
backup_repository(repo)
|
||||
|
||||
gc_repo(repo)
|
||||
|
||||
tasks_status(task_id)
|
||||
|
||||
delete_repo(repo)
|
||||
|
||||
get_repository_branches(repo)
|
||||
|
||||
health_check()
|
||||
|
||||
Constants:
|
||||
REPOSITORIES_BASE_PATH (str): The base path where Git repositories are stored.
|
||||
|
||||
Global Variables:
|
||||
app (Flask): The Flask application instance.
|
||||
executor (Executor): The Flask-Executor instance for managing asynchronous tasks.
|
||||
tasks (dict): A dictionary to store the status of asynchronous tasks.
|
||||
"""
|
||||
|
||||
# pylint: disable=locally-disabled, line-too-long
|
||||
|
||||
import os.path
|
||||
import os
|
||||
import shutil
|
||||
import uuid
|
||||
import git
|
||||
import time
|
||||
from opengnsys_git_installer import OpengnsysGitInstaller
|
||||
from flask import Flask, request, jsonify # stream_with_context, Response,
|
||||
from flask_executor import Executor
|
||||
from flask_restx import Api, Resource, fields
|
||||
#from flasgger import Swagger
|
||||
import paramiko
|
||||
|
||||
REPOSITORIES_BASE_PATH = "/opt/opengnsys/images"
|
||||
|
||||
start_time = time.time()
|
||||
tasks = {}
|
||||
|
||||
|
||||
# Create an instance of the Flask class
|
||||
app = Flask(__name__)
|
||||
api = Api(app,
|
||||
version='0.50',
|
||||
title = "OpenGnsys Git API",
|
||||
description = "API for managing disk images stored in Git",
|
||||
doc = "/swagger/")
|
||||
|
||||
git_ns = api.namespace(name = "oggit", description = "Git operations", path = "/oggit/v1")
|
||||
|
||||
executor = Executor(app)
|
||||
|
||||
|
||||
|
||||
|
||||
def do_repo_backup(repo, params):
|
||||
"""
|
||||
Creates a backup of the specified Git repository and uploads it to a remote server via SFTP.
|
||||
|
||||
Args:
|
||||
repo (str): The name of the repository to back up.
|
||||
params (dict): A dictionary containing the following keys:
|
||||
- ssh_server (str): The SSH server address.
|
||||
- ssh_port (int): The SSH server port.
|
||||
- ssh_user (str): The SSH username.
|
||||
- filename (str): The remote filename where the backup will be stored.
|
||||
|
||||
Returns:
|
||||
bool: True if the backup was successful.
|
||||
"""
|
||||
|
||||
gitrepo = git.Repo(f"{REPOSITORIES_BASE_PATH}/{repo}.git")
|
||||
|
||||
ssh = paramiko.SSHClient()
|
||||
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||
|
||||
ssh.connect(params["ssh_server"], params["ssh_port"], params["ssh_user"])
|
||||
sftp = ssh.open_sftp()
|
||||
|
||||
|
||||
with sftp.file(params["filename"], mode='wb+') as remote_file:
|
||||
gitrepo.archive(remote_file, format="tar.gz")
|
||||
|
||||
|
||||
return True
|
||||
|
||||
def do_repo_sync(repo, params):
|
||||
"""
|
||||
Synchronizes a local Git repository with a remote repository.
|
||||
|
||||
Args:
|
||||
repo (str): The name of the local repository to synchronize.
|
||||
params (dict): A dictionary containing the remote repository URL with the key "remote_repository".
|
||||
|
||||
Returns:
|
||||
list: A list of dictionaries, each containing:
|
||||
- "local_ref" (str): The name of the local reference.
|
||||
- "remote_ref" (str): The name of the remote reference.
|
||||
- "summary" (str): A summary of the push operation for the reference.
|
||||
"""
|
||||
gitrepo = git.Repo(f"{REPOSITORIES_BASE_PATH}/{repo}.git")
|
||||
|
||||
# Recreate the remote every time, it might change
|
||||
if "backup" in gitrepo.remotes:
|
||||
gitrepo.delete_remote("backup")
|
||||
|
||||
backup_repo = gitrepo.create_remote("backup", params["remote_repository"])
|
||||
pushed_references = backup_repo.push("*:*")
|
||||
results = []
|
||||
|
||||
# This gets returned to the API
|
||||
for ref in pushed_references:
|
||||
results = results + [ {"local_ref" : ref.local_ref.name, "remote_ref" : ref.remote_ref.name, "summary" : ref.summary }]
|
||||
|
||||
return results
|
||||
|
||||
def do_repo_gc(repo):
|
||||
"""
|
||||
Perform garbage collection on the specified Git repository.
|
||||
|
||||
Args:
|
||||
repo (str): The name of the repository to perform garbage collection on.
|
||||
|
||||
Returns:
|
||||
bool: True if the garbage collection command was executed successfully.
|
||||
"""
|
||||
gitrepo = git.Repo(f"{REPOSITORIES_BASE_PATH}/{repo}.git")
|
||||
|
||||
gitrepo.git.gc()
|
||||
return True
|
||||
|
||||
|
||||
# Define a route for the root URL
|
||||
@api.route('/')
|
||||
class GitLib(Resource):
|
||||
|
||||
@api.doc('home')
|
||||
def get(self):
|
||||
"""
|
||||
Home route that returns a JSON response with a welcome message for the OpenGnsys Git API.
|
||||
|
||||
Returns:
|
||||
Response: A Flask JSON response containing a welcome message.
|
||||
"""
|
||||
return {
|
||||
"message": "OpenGnsys Git API"
|
||||
}
|
||||
|
||||
@git_ns.route('/oggit/v1/repositories')
|
||||
class GitRepositories(Resource):
|
||||
def get(self):
|
||||
"""
|
||||
Retrieve a list of Git repositories.
|
||||
|
||||
This endpoint scans the OpenGnsys image path for directories that
|
||||
appear to be Git repositories (i.e., they contain a "HEAD" file).
|
||||
It returns a JSON response containing the names of these repositories.
|
||||
|
||||
Returns:
|
||||
Response: A JSON response with a list of repository names or an
|
||||
error message if the repository storage is not found.
|
||||
- 200 OK: When the repositories are successfully retrieved.
|
||||
- 500 Internal Server Error: When the repository storage is not found.
|
||||
|
||||
Example JSON response:
|
||||
{
|
||||
"repositories": ["repo1", "repo2"]
|
||||
}
|
||||
"""
|
||||
|
||||
if not os.path.isdir(REPOSITORIES_BASE_PATH):
|
||||
return jsonify({"error": "Repository storage not found, git functionality may not be installed."}), 500
|
||||
|
||||
repos = []
|
||||
for entry in os.scandir(REPOSITORIES_BASE_PATH):
|
||||
if entry.is_dir(follow_symlinks=False) and os.path.isfile(os.path.join(entry.path, "HEAD")):
|
||||
name = entry.name
|
||||
if name.endswith(".git"):
|
||||
name = name[:-4]
|
||||
|
||||
repos = repos + [name]
|
||||
|
||||
return jsonify({
|
||||
"repositories": repos
|
||||
})
|
||||
|
||||
def post(self):
|
||||
"""
|
||||
Create a new Git repository.
|
||||
|
||||
This endpoint creates a new Git repository with the specified name.
|
||||
If the repository already exists, it returns a status message indicating so.
|
||||
|
||||
Args:
|
||||
repo (str): The name of the repository to be created.
|
||||
|
||||
Returns:
|
||||
Response: A JSON response with a status message and HTTP status code.
|
||||
- 200: If the repository already exists.
|
||||
- 201: If the repository is successfully created.
|
||||
"""
|
||||
data = request.json
|
||||
|
||||
if data is None:
|
||||
return jsonify({"error" : "Parameters missing"}), 400
|
||||
|
||||
repo = data["name"]
|
||||
|
||||
repo_path = os.path.join(REPOSITORIES_BASE_PATH, repo + ".git")
|
||||
if os.path.isdir(repo_path):
|
||||
return jsonify({"status": "Repository already exists"}), 200
|
||||
|
||||
|
||||
installer = OpengnsysGitInstaller()
|
||||
installer.add_forgejo_repo(repo)
|
||||
|
||||
#installer.init_git_repo(repo + ".git")
|
||||
|
||||
|
||||
return jsonify({"status": "Repository created"}), 201
|
||||
|
||||
|
||||
@git_ns.route('/oggit/v1/repositories/<repo>/sync')
|
||||
class GitRepoSync(Resource):
|
||||
def post(self, repo):
|
||||
"""
|
||||
Synchronize a repository with a remote repository.
|
||||
|
||||
This endpoint triggers the synchronization process for a specified repository.
|
||||
It expects a JSON payload with the remote repository details.
|
||||
|
||||
Args:
|
||||
repo (str): The name of the repository to be synchronized.
|
||||
|
||||
Returns:
|
||||
Response: A JSON response indicating the status of the synchronization process.
|
||||
- 200: If the synchronization process has started successfully.
|
||||
- 400: If the request payload is missing or invalid.
|
||||
- 404: If the specified repository is not found.
|
||||
"""
|
||||
repo_path = os.path.join(REPOSITORIES_BASE_PATH, repo + ".git")
|
||||
if not os.path.isdir(repo_path):
|
||||
return jsonify({"error": "Repository not found"}), 404
|
||||
|
||||
|
||||
data = request.json
|
||||
|
||||
if data is None:
|
||||
return jsonify({"error" : "Parameters missing"}), 400
|
||||
|
||||
future = executor.submit(do_repo_sync, repo, data)
|
||||
task_id = str(uuid.uuid4())
|
||||
tasks[task_id] = future
|
||||
return jsonify({"status": "started", "task_id" : task_id}), 200
|
||||
|
||||
|
||||
|
||||
@git_ns.route('/oggit/v1/repositories/<repo>/backup')
|
||||
class GitRepoBackup(Resource):
|
||||
def backup_repository(self, repo):
|
||||
"""
|
||||
Backup a specified repository.
|
||||
|
||||
Endpoint: POST /repositories/<repo>/backup
|
||||
|
||||
Args:
|
||||
repo (str): The name of the repository to back up.
|
||||
|
||||
Request Body (JSON):
|
||||
ssh_port (int, optional): The SSH port to use for the backup. Defaults to 22.
|
||||
|
||||
Returns:
|
||||
Response: A JSON response indicating the status of the backup operation.
|
||||
- If the repository is not found, returns a 404 error with a message.
|
||||
- If the request body is missing, returns a 400 error with a message.
|
||||
- If the backup process starts successfully, returns a 200 status with the task ID.
|
||||
|
||||
Notes:
|
||||
- The repository path is constructed by appending ".git" to the repository name.
|
||||
- The backup operation is performed asynchronously using a thread pool executor.
|
||||
- The task ID of the backup operation is generated using UUID and stored in a global tasks dictionary.
|
||||
"""
|
||||
repo_path = os.path.join(REPOSITORIES_BASE_PATH, repo + ".git")
|
||||
if not os.path.isdir(repo_path):
|
||||
return jsonify({"error": "Repository not found"}), 404
|
||||
|
||||
|
||||
data = request.json
|
||||
if data is None:
|
||||
return jsonify({"error" : "Parameters missing"}), 400
|
||||
|
||||
|
||||
if not "ssh_port" in data:
|
||||
data["ssh_port"] = 22
|
||||
|
||||
|
||||
future = executor.submit(do_repo_backup, repo, data)
|
||||
task_id = str(uuid.uuid4())
|
||||
tasks[task_id] = future
|
||||
|
||||
return jsonify({"status": "started", "task_id" : task_id}), 200
|
||||
|
||||
@git_ns.route('/oggit/v1/repositories/<repo>/compact', methods=['POST'])
|
||||
class GitRepoCompact(Resource):
|
||||
def post(self, repo):
|
||||
"""
|
||||
Initiates a garbage collection (GC) process for a specified Git repository.
|
||||
|
||||
This endpoint triggers an asynchronous GC task for the given repository.
|
||||
The task is submitted to an executor, and a unique task ID is generated
|
||||
and returned to the client.
|
||||
|
||||
Args:
|
||||
repo (str): The name of the repository to perform GC on.
|
||||
|
||||
Returns:
|
||||
Response: A JSON response containing the status of the request and
|
||||
a unique task ID if the repository is found, or an error
|
||||
message if the repository is not found.
|
||||
"""
|
||||
repo_path = os.path.join(REPOSITORIES_BASE_PATH, repo + ".git")
|
||||
if not os.path.isdir(repo_path):
|
||||
return jsonify({"error": "Repository not found"}), 404
|
||||
|
||||
future = executor.submit(do_repo_gc, repo)
|
||||
task_id = str(uuid.uuid4())
|
||||
tasks[task_id] = future
|
||||
|
||||
return jsonify({"status": "started", "task_id" : task_id}), 200
|
||||
|
||||
|
||||
@git_ns.route('/oggit/v1/tasks/<task_id>/status')
|
||||
class GitTaskStatus(Resource):
|
||||
def get(self, task_id):
|
||||
"""
|
||||
Endpoint to check the status of a specific task.
|
||||
|
||||
Args:
|
||||
task_id (str): The unique identifier of the task.
|
||||
|
||||
Returns:
|
||||
Response: A JSON response containing the status of the task.
|
||||
- If the task is not found, returns a 404 error with an error message.
|
||||
- If the task is completed, returns a 200 status with the result.
|
||||
- If the task is still in progress, returns a 202 status indicating the task is in progress.
|
||||
"""
|
||||
if not task_id in tasks:
|
||||
return jsonify({"error": "Task not found"}), 404
|
||||
|
||||
future = tasks[task_id]
|
||||
|
||||
if future.done():
|
||||
result = future.result()
|
||||
return jsonify({"status" : "completed", "result" : result}), 200
|
||||
else:
|
||||
return jsonify({"status" : "in progress"}), 202
|
||||
|
||||
|
||||
|
||||
@git_ns.route('/oggit/v1/repositories/<repo>', methods=['DELETE'])
|
||||
class GitRepo(Resource):
|
||||
def delete(self, repo):
|
||||
"""
|
||||
Deletes a Git repository.
|
||||
|
||||
This endpoint deletes a Git repository specified by the `repo` parameter.
|
||||
If the repository does not exist, it returns a 404 error with a message
|
||||
indicating that the repository was not found. If the repository is successfully
|
||||
deleted, it returns a 200 status with a message indicating that the repository
|
||||
was deleted.
|
||||
|
||||
Args:
|
||||
repo (str): The name of the repository to delete.
|
||||
|
||||
Returns:
|
||||
Response: A JSON response with a status message and the appropriate HTTP status code.
|
||||
"""
|
||||
repo_path = os.path.join(REPOSITORIES_BASE_PATH, repo + ".git")
|
||||
if not os.path.isdir(repo_path):
|
||||
return jsonify({"error": "Repository not found"}), 404
|
||||
|
||||
|
||||
shutil.rmtree(repo_path)
|
||||
return jsonify({"status": "Repository deleted"}), 200
|
||||
|
||||
|
||||
|
||||
|
||||
@git_ns.route('/oggit/v1/repositories/<repo>/branches')
|
||||
class GitRepoBranches(Resource):
|
||||
def get(self, repo):
|
||||
"""
|
||||
Retrieve the list of branches for a given repository.
|
||||
|
||||
Args:
|
||||
repo (str): The name of the repository.
|
||||
|
||||
Returns:
|
||||
Response: A JSON response containing a list of branch names or an error message if the repository is not found.
|
||||
- 200: A JSON object with a "branches" key containing a list of branch names.
|
||||
- 404: A JSON object with an "error" key containing the message "Repository not found" if the repository does not exist.
|
||||
"""
|
||||
repo_path = os.path.join(REPOSITORIES_BASE_PATH, repo + ".git")
|
||||
if not os.path.isdir(repo_path):
|
||||
return jsonify({"error": "Repository not found"}), 404
|
||||
|
||||
git_repo = git.Repo(repo_path)
|
||||
|
||||
branches = []
|
||||
for branch in git_repo.branches:
|
||||
branches = branches + [branch.name]
|
||||
|
||||
|
||||
return jsonify({
|
||||
"branches": branches
|
||||
})
|
||||
|
||||
|
||||
|
||||
|
||||
@git_ns.route('/health')
|
||||
class GitHealth(Resource):
|
||||
def get(self):
|
||||
"""
|
||||
Health check endpoint.
|
||||
|
||||
This endpoint returns a JSON response indicating the health status of the application.
|
||||
|
||||
Returns:
|
||||
Response: A JSON response with a status key set to "OK". Currently it always returns
|
||||
a successful value, but this endpoint can still be used to check that the API is
|
||||
active and functional.
|
||||
|
||||
"""
|
||||
return {
|
||||
"status": "OK"
|
||||
}
|
||||
|
||||
@git_ns.route('/status')
|
||||
class GitStatus(Resource):
|
||||
def get(self):
|
||||
"""
|
||||
Status check endpoint.
|
||||
|
||||
This endpoint returns a JSON response indicating the status of the application.
|
||||
|
||||
Returns:
|
||||
Response: A JSON response with status information
|
||||
|
||||
"""
|
||||
return {
|
||||
"uptime" : time.time() - start_time,
|
||||
"active_tasks" : len(tasks)
|
||||
}
|
||||
|
||||
|
||||
api.add_namespace(git_ns)
|
||||
|
||||
|
||||
|
||||
# Run the Flask app
|
||||
if __name__ == '__main__':
|
||||
print(f"Map: {app.url_map}")
|
||||
app.run(debug=True, host='0.0.0.0')
|
|
@ -1 +0,0 @@
|
|||
../installer/opengnsys_git_installer.py
|
|
@ -1,34 +0,0 @@
|
|||
aniso8601==9.0.1
|
||||
attrs==24.2.0
|
||||
bcrypt==4.2.0
|
||||
blinker==1.8.2
|
||||
cffi==1.17.1
|
||||
click==8.1.7
|
||||
cryptography==43.0.1
|
||||
dataclasses==0.6
|
||||
flasgger==0.9.7.1
|
||||
Flask==3.0.3
|
||||
Flask-Executor==1.0.0
|
||||
flask-restx==1.3.0
|
||||
gitdb==4.0.11
|
||||
GitPython==3.1.43
|
||||
importlib_resources==6.4.5
|
||||
itsdangerous==2.2.0
|
||||
Jinja2==3.1.4
|
||||
jsonschema==4.23.0
|
||||
jsonschema-specifications==2024.10.1
|
||||
libarchive-c==5.1
|
||||
MarkupSafe==3.0.1
|
||||
mistune==3.0.2
|
||||
packaging==24.1
|
||||
paramiko==3.5.0
|
||||
pycparser==2.22
|
||||
PyNaCl==1.5.0
|
||||
pytz==2024.2
|
||||
PyYAML==6.0.2
|
||||
referencing==0.35.1
|
||||
rpds-py==0.20.0
|
||||
six==1.16.0
|
||||
smmap==5.0.1
|
||||
termcolor==2.5.0
|
||||
Werkzeug==3.0.4
|
|
@ -1,27 +0,0 @@
|
|||
bcrypt==4.0.1
|
||||
cffi==1.15.1
|
||||
click==8.0.4
|
||||
colorterm==0.3
|
||||
contextvars==2.4
|
||||
cryptography==40.0.2
|
||||
dataclasses==0.8
|
||||
Flask==2.0.3
|
||||
Flask-Executor==1.0.0
|
||||
gitdb==4.0.9
|
||||
GitPython==3.1.20
|
||||
immutables==0.19
|
||||
importlib-metadata==4.8.3
|
||||
itsdangerous==2.0.1
|
||||
Jinja2==3.0.3
|
||||
libarchive==0.4.7
|
||||
MarkupSafe==2.0.1
|
||||
nose==1.3.7
|
||||
paramiko==3.5.0
|
||||
pkg_resources==0.0.0
|
||||
pycparser==2.21
|
||||
PyNaCl==1.5.0
|
||||
smmap==5.0.0
|
||||
termcolor==1.1.0
|
||||
typing_extensions==4.1.1
|
||||
Werkzeug==2.0.3
|
||||
zipp==3.6.0
|
|
@ -1,122 +0,0 @@
|
|||
# GitLib
|
||||
|
||||
The `gitlib.py` is a Python library also usable as a command-line program for testing purposes.
|
||||
|
||||
It contains functions for managing git, and the command-line interface allows executing them without needing to write a program that uses the library.
|
||||
|
||||
## Requirements
|
||||
|
||||
Gitlib is designed to work within an existing OpenGnsys environment. It invokes some OpenGnsys commands internally and reads the parameters passed to the kernel in oglive.
|
||||
|
||||
Therefore, it will not work correctly outside of an oglive environment.
|
||||
|
||||
## Installing Python dependencies
|
||||
|
||||
The code conversion to Python 3 currently requires the packages specified in `requirements.txt`.
|
||||
|
||||
The `venv` module (https://docs.python.org/3/library/venv.html) is used to install Python dependencies, creating an environment isolated from the system.
|
||||
|
||||
**Note:** Ubuntu 24.04 includes most of the required dependencies as packages, but there is no `blkid` package, so it must be installed using pip within a virtual environment.
|
||||
|
||||
Run the following commands:
|
||||
|
||||
```bash
|
||||
sudo apt install -y python3 libarchive-dev libblkid-dev pkg-config libacl1-dev
|
||||
python3 -m venv venvog
|
||||
. venvog/bin/activate
|
||||
python3 -m pip install --upgrade pip
|
||||
pip3 install -r requirements.txt
|
||||
```
|
||||
|
||||
# Usage
|
||||
|
||||
Run with:
|
||||
|
||||
```bash
|
||||
# . venvog/bin/activate
|
||||
# ./gitlib.py
|
||||
```
|
||||
|
||||
In command-line mode, help can be displayed with:
|
||||
|
||||
```bash
|
||||
./gitlib.py --help
|
||||
```
|
||||
|
||||
**Note:** Execute as the `root` user, as `sudo` clears the environment variable changes made by venv. This will likely result in a Python module not found error or program failure due to outdated dependencies.
|
||||
|
||||
**Note:** Commands starting with `--test` exist for internal testing. They are temporary and meant to test specific parts of the code. These may require specific conditions to work and will be removed upon completion of development.
|
||||
|
||||
## Initialize a repository:
|
||||
|
||||
```bash
|
||||
./gitlib.py --init-repo-from /dev/sda2 --repo linux
|
||||
```
|
||||
|
||||
This initializes the 'linux' repository with the content of /mnt/sda2.
|
||||
|
||||
`--repo` specifies the name of one of the repositories configured during the git installation (see git installer).
|
||||
|
||||
The repository is uploaded to the ogrepository, obtained from the boot parameter passed to the kernel.
|
||||
|
||||
## Clone a repository:
|
||||
|
||||
```bash
|
||||
./gitlib.py --clone-repo-to /dev/sda2 --boot-device /dev/sda --repo linux
|
||||
```
|
||||
|
||||
This clones a repository from the ogrepository. The target is a physical device that will be formatted with the necessary file system.
|
||||
|
||||
`--boot-device` specifies the boot device where the bootloader (GRUB or similar) will be installed.
|
||||
|
||||
`--repo` is the repository name contained in ogrepository.
|
||||
|
||||
# Special Considerations for Windows
|
||||
|
||||
## Cloning
|
||||
|
||||
* Windows must be completely shut down, not hibernated. See: https://learn.microsoft.com/en-us/troubleshoot/windows-client/setup-upgrade-and-drivers/disable-and-re-enable-hibernation
|
||||
* Windows must be cleanly shut down using "Shut Down". Gitlib may fail to mount a disk from an improperly shut down system. If so, boot Windows again and shut it down properly.
|
||||
* Disk encryption (BitLocker) cannot be used.
|
||||
|
||||
## Restoration
|
||||
|
||||
Windows uses a structure called BCD (https://learn.microsoft.com/en-us/windows-hardware/manufacture/desktop/bcd-system-store-settings-for-uefi?view=windows-11) to store boot configuration.
|
||||
|
||||
This structure can vary depending on the machine where it is deployed. For this reason, gitlib supports storing multiple versions of the BCD internally and selecting the one corresponding to a specific machine.
|
||||
|
||||
# Documentation
|
||||
|
||||
Python documentation can be generated using utilities such as `pdoc3` (other alternatives are also possible):
|
||||
|
||||
```bash
|
||||
# Install pdoc3
|
||||
pip install --user pdoc3
|
||||
|
||||
# Generate documentation
|
||||
pdoc3 --force --html opengnsys_git_installer.py
|
||||
```
|
||||
|
||||
# Functionality
|
||||
|
||||
## Metadata
|
||||
|
||||
Git cannot store data about extended attributes, sockets, or other special file types. Gitlib stores these in `.opengnsys-metadata` at the root of the repository.
|
||||
|
||||
The data is saved in `jsonl` files, a structure with one JSON object per line. This facilitates partial applications by applying only the necessary lines.
|
||||
|
||||
The following files are included:
|
||||
|
||||
* `acls.jsonl`: ACLs
|
||||
* `empty_directories.jsonl`: Empty directories, as Git cannot store them
|
||||
* `filesystems.json`: Information about file systems: types, sizes, UUIDs
|
||||
* `gitignores.jsonl`: List of .gitignore files (renamed to avoid interfering with Git)
|
||||
* `metadata.json`: General metadata about the repository
|
||||
* `special_files.jsonl`: Special files like sockets
|
||||
* `xattrs.jsonl`: Extended attributes
|
||||
* `renamed.jsonl`: Files renamed to avoid interfering with Git
|
||||
* `unix_permissions.jsonl`: UNIX permissions (not precisely stored by Git)
|
||||
* `ntfs_secaudit.txt`: NTFS security data
|
||||
* `efi_data`: Copy of the EFI (ESP) partition
|
||||
* `efi_data.(id)`: EFI partition copy corresponding to a specific machine
|
||||
* `efi_data.(name)`: EFI partition copy corresponding to a name specified by the administrator.
|
149
gitlib/README.md
149
gitlib/README.md
|
@ -1,149 +0,0 @@
|
|||
# GitLib
|
||||
|
||||
La `gitlib.py` es una librería de Python también usable como programa de línea
|
||||
de comandos para pruebas.
|
||||
|
||||
Contiene las funciones de gestión de git, y la parte de línea de comandos permite ejecutarlas sin necesitar escribir un programa que use la librería.
|
||||
|
||||
|
||||
## Requisitos
|
||||
|
||||
La gitlib esta diseñada para funcionar dentro de un entorno opengnsys existente. Invoca algunos de los comandos de opengnsys internamente, y lee los parámetros pasados al kernel en el oglive.
|
||||
|
||||
Por lo tanto, no va a funcionar correctamente fuera de un entorno oglive.
|
||||
|
||||
## Instalación de dependencias para python
|
||||
|
||||
La conversion del código a Python 3 requiere actualmente los paquetes especificados en `requirements.txt`
|
||||
|
||||
Para instalar dependencias de python se usa el modulo venv (https://docs.python.org/3/library/venv.html) que instala todas las dependencias en un entorno independiente del sistema.
|
||||
|
||||
**Nota:** Ubuntu 24.04 tiene la mayoría de las dependencias necesarias como paquetes, pero no hay paquete de `blkid`, por lo cual es necesario usar pip y un virtualenv.
|
||||
|
||||
Ejecutar:
|
||||
|
||||
sudo apt install -y python3 libarchive-dev libblkid-dev pkg-config libacl1-dev
|
||||
python3 -m venv venvog
|
||||
. venvog/bin/activate
|
||||
python3 -m pip install --upgrade pip
|
||||
pip3 install -r requirements.txt
|
||||
|
||||
|
||||
# Uso
|
||||
|
||||
Ejecutar con:
|
||||
|
||||
# . venvog/bin/activate
|
||||
# ./gitlib.py
|
||||
|
||||
En modo de linea de comando, hay ayuda que se puede ver con:
|
||||
|
||||
./gitlib.py --help
|
||||
|
||||
|
||||
**Nota:** Ejecutar como usuario `root`, ya que `sudo` borra los cambios a las variables de entorno realizadas por venv. El resultado probable es un error de falta de módulos de Python, o un fallo del programa por usar dependencias demasiado antiguas.
|
||||
|
||||
**Nota:** Los comandos que comienzan por `--test` existen para hacer pruebas internas, y existen temporalmente para probar partes especificas del código. Es posible que necesiten condiciones especificas para funcionar, y van a eliminarse al completarse el desarrollo.
|
||||
|
||||
|
||||
## Inicializar un repositorio:
|
||||
|
||||
./gitlib.py --init-repo-from /dev/sda2 --repo linux
|
||||
|
||||
|
||||
Esto inicializa el repositorio 'linux' con el contenido /mnt/sda2.
|
||||
|
||||
`--repo` especifica el nombre de uno de los repositorios fijados durante la instalación de git (ver git installer).
|
||||
|
||||
El repositorio de sube al ogrepository, que se obtiene del parámetro de arranque pasado al kernel.
|
||||
|
||||
## Clonar un repositorio:
|
||||
|
||||
./gitlib.py --clone-repo-to /dev/sda2 --boot-device /dev/sda --repo linux
|
||||
|
||||
Esto clona un repositorio del ogrepository. El destino es un dispositivo físico que se va a formatear con el sistema de archivos necesario.
|
||||
|
||||
`--boot-device` especifica el dispositivo de arranque donde se va a instalar el bootloader (GRUB o similar)
|
||||
|
||||
`--repo` es el nombre de repositorio contenido en ogrepository.
|
||||
|
||||
# Consideraciones especiales para Windows
|
||||
|
||||
## Clonación
|
||||
|
||||
* Windows debe haber sido apagado completamente, sin hibernar. Ver https://learn.microsoft.com/en-us/troubleshoot/windows-client/setup-upgrade-and-drivers/disable-and-re-enable-hibernation
|
||||
* Windows debe haber sido apagado limpiamente, usando "Apagar sistema". Es posible que gitlib no pueda montar un disco de un sistema apagado incorrectamente. En ese caso hay que volver a iniciar Windows, y apagarlo.
|
||||
* No se puede usar cifrado de disco (Bitlocker)
|
||||
|
||||
## Restauración
|
||||
|
||||
Windows usa una estructura llamada BCD (https://learn.microsoft.com/en-us/windows-hardware/manufacture/desktop/bcd-system-store-settings-for-uefi?view=windows-11) para almacenar la configuración de arranque.
|
||||
|
||||
La estructura puede variar dependiendo en que maquina se despliegue, por esto gitlib soporta almacenar internamente multiples versiones del BCD, y elegir el correspondiente a una maquina especifica.
|
||||
|
||||
## Identificadores de disco
|
||||
|
||||
El arranque de Windows dependiendo de como esté configurado por Windows puede referirse
|
||||
a UUIDs de particiones y discos cuando se usa particionado GPT.
|
||||
|
||||
El código actual conserva los UUIDs y los restaura al clonar.
|
||||
|
||||
## BCDs específicos
|
||||
|
||||
Los datos de arranque de Windows se guardan en `.opengsnys-metadata/efi_data`. Es posible incluir versiones adicionales en caso necesario. Se hace creando un directorio adicional con el nombre `efi_data.(id)`, donde id es un número de serie obtenido con el comando `/usr/sbin/dmidecode -s system-uuid`.
|
||||
|
||||
Por ejemplo:
|
||||
|
||||
```
|
||||
# Obtener ID único del equipo
|
||||
|
||||
dmidecode -s system-uuid
|
||||
a64cc65b-12a6-42ef-8182-5ae4832e9f19
|
||||
|
||||
# Copiar la partición EFI al directorio correspondiente a esa máquina particular
|
||||
mkdir /mnt/sda3/.opengnsys-metadata/efi_data.a64cc65b-12a6-42ef-8182-5ae4832e9f19
|
||||
cp -Rdpv /mnt/sda1/* /mnt/sda3/.opengnsys-metadata/efi_data.a64cc65b-12a6-42ef-8182-5ae4832e9f19
|
||||
|
||||
# commit
|
||||
```
|
||||
|
||||
Con esto, al desplegar el repo, para la máquina a64cc65b-12a6-42ef-8182-5ae4832e9f19 se va a usar su propia configuración de arranque, en vez de la general.
|
||||
|
||||
|
||||
|
||||
# Documentación
|
||||
|
||||
Se puede generar documentación de Python con una utilidad como pdoc3 (hay multiples alternativas posibles):
|
||||
|
||||
# Instalar pdoc3
|
||||
pip install --user pdoc3
|
||||
|
||||
# Generar documentación
|
||||
pdoc3 --force --html opengnsys_git_installer.py
|
||||
|
||||
# Funcionamiento
|
||||
|
||||
|
||||
|
||||
## Metadatos
|
||||
|
||||
Git no es capaz de almacenar datos de atributos extendidos, sockets y otros tipos de archivos especiales. El gitlib los almacena en .opengnsys-metadata en
|
||||
el raíz del repositorio.
|
||||
|
||||
Los datos se guardan en archivos de tipo `jsonl`, una estructura de JSON por linea. Esto es para facilitar aplicaciones parciales solo aplicando el efecto de las lineas necesarias.
|
||||
|
||||
Existen estos archivos:
|
||||
|
||||
* `acls.jsonl`: ACLs
|
||||
* `empty_directories.jsonl`: Directorios vacíos, ya que Git no es capaz de guardarlos
|
||||
* `filesystems.json`: Información sobre sistemas de archivos: tipos, tamaños, UUIDs
|
||||
* `gitignores.jsonl`: Lista de archivos .gitignore (los renombramos para que no interfieran con git)
|
||||
* `metadata.json`: Metadatos generales acerca del repositorio
|
||||
* `special_files.jsonl`: Archivos especiales como sockets
|
||||
* `xattrs.jsonl`: Atributos extendidos
|
||||
* `renamed.jsonl`: Archivos renombrados para no interferir con Git
|
||||
* `unix_permissions.jsonl`: Permisos UNIX (Git no los almacena exactamente)
|
||||
* `ntfs_secaudit.txt`: Datos de seguridad de NTFS
|
||||
* `efi_data`: Copia de la partición EFI (ESP)
|
||||
* `efi_data.(id)`: Copia de la partición EFI correspondiente a un equipo especifico.
|
||||
* `efi_data.(nombre)`: Copia de la partición EFI correspondiente a un nombre especificado por el administrador.
|
|
@ -1,25 +0,0 @@
|
|||
# Instalar de Admin
|
||||
|
||||
. venv/bin/activate
|
||||
./opengnsys_git_installer.py
|
||||
|
||||
# Inicializar el repo a partir de los datos de una maquina modelo:
|
||||
|
||||
Ejecutar en oglive corriendo en la maquina modelo
|
||||
|
||||
. venv/bin/activate
|
||||
./gitlib.py --init-repo-from /dev/sda2 --repo linux
|
||||
|
||||
|
||||
# Usar git para desplegar sobre una maquina nueva:
|
||||
|
||||
|
||||
Ejecutar en oglive corriendo en la maquina de destino.
|
||||
|
||||
Preparar el disco creando partición boot/EFI y partición de datos.
|
||||
|
||||
|
||||
. venv/bin/activate
|
||||
./gitlib.py --clone-repo-to /dev/sda2 --repo linux --boot-device /dev/sda
|
||||
|
||||
|
345
gitlib/bcd.py
345
gitlib/bcd.py
|
@ -1,345 +0,0 @@
|
|||
#!/usr/bin/env python3
|
||||
import hivex
|
||||
import argparse
|
||||
import struct
|
||||
|
||||
from hivex import Hivex
|
||||
from hivex.hive_types import *
|
||||
|
||||
|
||||
# Docs:
|
||||
#
|
||||
# https://www.geoffchappell.com/notes/windows/boot/bcd/objects.htm
|
||||
# https://learn.microsoft.com/en-us/previous-versions/windows/desktop/bcd/bcdbootmgrelementtypes
|
||||
|
||||
#print(f"Root: {root}")
|
||||
|
||||
|
||||
BCD_Enumerations = {
|
||||
"BcdLibraryDevice_ApplicationDevice" : 0x11000001,
|
||||
"BcdLibraryString_ApplicationPath" : 0x12000002,
|
||||
"BcdLibraryString_Description" : 0x12000004,
|
||||
"BcdLibraryString_PreferredLocale" : 0x12000005,
|
||||
"BcdLibraryObjectList_InheritedObjects" : 0x14000006,
|
||||
"BcdLibraryInteger_TruncatePhysicalMemory" : 0x15000007,
|
||||
"BcdLibraryObjectList_RecoverySequence" : 0x14000008,
|
||||
"BcdLibraryBoolean_AutoRecoveryEnabled" : 0x16000009,
|
||||
"BcdLibraryIntegerList_BadMemoryList" : 0x1700000a,
|
||||
"BcdLibraryBoolean_AllowBadMemoryAccess" : 0x1600000b,
|
||||
"BcdLibraryInteger_FirstMegabytePolicy" : 0x1500000c,
|
||||
"BcdLibraryInteger_RelocatePhysicalMemory" : 0x1500000D,
|
||||
"BcdLibraryInteger_AvoidLowPhysicalMemory" : 0x1500000E,
|
||||
"BcdLibraryBoolean_DebuggerEnabled" : 0x16000010,
|
||||
"BcdLibraryInteger_DebuggerType" : 0x15000011,
|
||||
"BcdLibraryInteger_SerialDebuggerPortAddress" : 0x15000012,
|
||||
"BcdLibraryInteger_SerialDebuggerPort" : 0x15000013,
|
||||
"BcdLibraryInteger_SerialDebuggerBaudRate" : 0x15000014,
|
||||
"BcdLibraryInteger_1394DebuggerChannel" : 0x15000015,
|
||||
"BcdLibraryString_UsbDebuggerTargetName" : 0x12000016,
|
||||
"BcdLibraryBoolean_DebuggerIgnoreUsermodeExceptions" : 0x16000017,
|
||||
"BcdLibraryInteger_DebuggerStartPolicy" : 0x15000018,
|
||||
"BcdLibraryString_DebuggerBusParameters" : 0x12000019,
|
||||
"BcdLibraryInteger_DebuggerNetHostIP" : 0x1500001A,
|
||||
"BcdLibraryInteger_DebuggerNetPort" : 0x1500001B,
|
||||
"BcdLibraryBoolean_DebuggerNetDhcp" : 0x1600001C,
|
||||
"BcdLibraryString_DebuggerNetKey" : 0x1200001D,
|
||||
"BcdLibraryBoolean_EmsEnabled" : 0x16000020,
|
||||
"BcdLibraryInteger_EmsPort" : 0x15000022,
|
||||
"BcdLibraryInteger_EmsBaudRate" : 0x15000023,
|
||||
"BcdLibraryString_LoadOptionsString" : 0x12000030,
|
||||
"BcdLibraryBoolean_DisplayAdvancedOptions" : 0x16000040,
|
||||
"BcdLibraryBoolean_DisplayOptionsEdit" : 0x16000041,
|
||||
"BcdLibraryDevice_BsdLogDevice" : 0x11000043,
|
||||
"BcdLibraryString_BsdLogPath" : 0x12000044,
|
||||
"BcdLibraryBoolean_GraphicsModeDisabled" : 0x16000046,
|
||||
"BcdLibraryInteger_ConfigAccessPolicy" : 0x15000047,
|
||||
"BcdLibraryBoolean_DisableIntegrityChecks" : 0x16000048,
|
||||
"BcdLibraryBoolean_AllowPrereleaseSignatures" : 0x16000049,
|
||||
"BcdLibraryString_FontPath" : 0x1200004A,
|
||||
"BcdLibraryInteger_SiPolicy" : 0x1500004B,
|
||||
"BcdLibraryInteger_FveBandId" : 0x1500004C,
|
||||
"BcdLibraryBoolean_ConsoleExtendedInput" : 0x16000050,
|
||||
"BcdLibraryInteger_GraphicsResolution" : 0x15000052,
|
||||
"BcdLibraryBoolean_RestartOnFailure" : 0x16000053,
|
||||
"BcdLibraryBoolean_GraphicsForceHighestMode" : 0x16000054,
|
||||
"BcdLibraryBoolean_IsolatedExecutionContext" : 0x16000060,
|
||||
"BcdLibraryBoolean_BootUxDisable" : 0x1600006C,
|
||||
"BcdLibraryBoolean_BootShutdownDisabled" : 0x16000074,
|
||||
"BcdLibraryIntegerList_AllowedInMemorySettings" : 0x17000077,
|
||||
"BcdLibraryBoolean_ForceFipsCrypto" : 0x16000079,
|
||||
|
||||
|
||||
"BcdBootMgrObjectList_DisplayOrder" : 0x24000001,
|
||||
"BcdBootMgrObjectList_BootSequence" : 0x24000002,
|
||||
"BcdBootMgrObject_DefaultObject" : 0x23000003,
|
||||
"BcdBootMgrInteger_Timeout" : 0x25000004,
|
||||
"BcdBootMgrBoolean_AttemptResume" : 0x26000005,
|
||||
"BcdBootMgrObject_ResumeObject" : 0x23000006,
|
||||
"BcdBootMgrObjectList_ToolsDisplayOrder" : 0x24000010,
|
||||
"BcdBootMgrBoolean_DisplayBootMenu" : 0x26000020,
|
||||
"BcdBootMgrBoolean_NoErrorDisplay" : 0x26000021,
|
||||
"BcdBootMgrDevice_BcdDevice" : 0x21000022,
|
||||
"BcdBootMgrString_BcdFilePath" : 0x22000023,
|
||||
"BcdBootMgrBoolean_ProcessCustomActionsFirst" : 0x26000028,
|
||||
"BcdBootMgrIntegerList_CustomActionsList" : 0x27000030,
|
||||
"BcdBootMgrBoolean_PersistBootSequence" : 0x26000031,
|
||||
|
||||
"BcdDeviceInteger_RamdiskImageOffset" : 0x35000001,
|
||||
"BcdDeviceInteger_TftpClientPort" : 0x35000002,
|
||||
"BcdDeviceInteger_SdiDevice" : 0x31000003,
|
||||
"BcdDeviceInteger_SdiPath" : 0x32000004,
|
||||
"BcdDeviceInteger_RamdiskImageLength" : 0x35000005,
|
||||
"BcdDeviceBoolean_RamdiskExportAsCd" : 0x36000006,
|
||||
"BcdDeviceInteger_RamdiskTftpBlockSize" : 0x36000007,
|
||||
"BcdDeviceInteger_RamdiskTftpWindowSize" : 0x36000008,
|
||||
"BcdDeviceBoolean_RamdiskMulticastEnabled" : 0x36000009,
|
||||
"BcdDeviceBoolean_RamdiskMulticastTftpFallback" : 0x3600000A,
|
||||
"BcdDeviceBoolean_RamdiskTftpVarWindow" : 0x3600000B,
|
||||
|
||||
"BcdMemDiagInteger_PassCount" : 0x25000001,
|
||||
"BcdMemDiagInteger_FailureCount" : 0x25000003,
|
||||
|
||||
"Reserved1" : 0x21000001,
|
||||
"Reserved2" : 0x22000002,
|
||||
"BcdResumeBoolean_UseCustomSettings" : 0x26000003,
|
||||
"BcdResumeDevice_AssociatedOsDevice" : 0x21000005,
|
||||
"BcdResumeBoolean_DebugOptionEnabled" : 0x26000006,
|
||||
"BcdResumeInteger_BootMenuPolicy" : 0x25000008,
|
||||
|
||||
"BcdOSLoaderDevice_OSDevice" : 0x21000001,
|
||||
"BcdOSLoaderString_SystemRoot" : 0x22000002,
|
||||
"BcdOSLoaderObject_AssociatedResumeObject" : 0x23000003,
|
||||
"BcdOSLoaderBoolean_DetectKernelAndHal" : 0x26000010,
|
||||
"BcdOSLoaderString_KernelPath" : 0x22000011,
|
||||
"BcdOSLoaderString_HalPath" : 0x22000012,
|
||||
"BcdOSLoaderString_DbgTransportPath" : 0x22000013,
|
||||
"BcdOSLoaderInteger_NxPolicy" : 0x25000020,
|
||||
"BcdOSLoaderInteger_PAEPolicy" : 0x25000021,
|
||||
"BcdOSLoaderBoolean_WinPEMode" : 0x26000022,
|
||||
"BcdOSLoaderBoolean_DisableCrashAutoReboot" : 0x26000024,
|
||||
"BcdOSLoaderBoolean_UseLastGoodSettings" : 0x26000025,
|
||||
"BcdOSLoaderBoolean_AllowPrereleaseSignatures" : 0x26000027,
|
||||
"BcdOSLoaderBoolean_NoLowMemory" : 0x26000030,
|
||||
"BcdOSLoaderInteger_RemoveMemory" : 0x25000031,
|
||||
"BcdOSLoaderInteger_IncreaseUserVa" : 0x25000032,
|
||||
"BcdOSLoaderBoolean_UseVgaDriver" : 0x26000040,
|
||||
"BcdOSLoaderBoolean_DisableBootDisplay" : 0x26000041,
|
||||
"BcdOSLoaderBoolean_DisableVesaBios" : 0x26000042,
|
||||
"BcdOSLoaderBoolean_DisableVgaMode" : 0x26000043,
|
||||
"BcdOSLoaderInteger_ClusterModeAddressing" : 0x25000050,
|
||||
"BcdOSLoaderBoolean_UsePhysicalDestination" : 0x26000051,
|
||||
"BcdOSLoaderInteger_RestrictApicCluster" : 0x25000052,
|
||||
"BcdOSLoaderBoolean_UseLegacyApicMode" : 0x26000054,
|
||||
"BcdOSLoaderInteger_X2ApicPolicy" : 0x25000055,
|
||||
"BcdOSLoaderBoolean_UseBootProcessorOnly" : 0x26000060,
|
||||
"BcdOSLoaderInteger_NumberOfProcessors" : 0x25000061,
|
||||
"BcdOSLoaderBoolean_ForceMaximumProcessors" : 0x26000062,
|
||||
"BcdOSLoaderBoolean_ProcessorConfigurationFlags" : 0x25000063,
|
||||
"BcdOSLoaderBoolean_MaximizeGroupsCreated" : 0x26000064,
|
||||
"BcdOSLoaderBoolean_ForceGroupAwareness" : 0x26000065,
|
||||
"BcdOSLoaderInteger_GroupSize" : 0x25000066,
|
||||
"BcdOSLoaderInteger_UseFirmwarePciSettings" : 0x26000070,
|
||||
"BcdOSLoaderInteger_MsiPolicy" : 0x25000071,
|
||||
"BcdOSLoaderInteger_SafeBoot" : 0x25000080,
|
||||
"BcdOSLoaderBoolean_SafeBootAlternateShell" : 0x26000081,
|
||||
"BcdOSLoaderBoolean_BootLogInitialization" : 0x26000090,
|
||||
"BcdOSLoaderBoolean_VerboseObjectLoadMode" : 0x26000091,
|
||||
"BcdOSLoaderBoolean_KernelDebuggerEnabled" : 0x260000a0,
|
||||
"BcdOSLoaderBoolean_DebuggerHalBreakpoint" : 0x260000a1,
|
||||
"BcdOSLoaderBoolean_UsePlatformClock" : 0x260000A2,
|
||||
"BcdOSLoaderBoolean_ForceLegacyPlatform" : 0x260000A3,
|
||||
"BcdOSLoaderInteger_TscSyncPolicy" : 0x250000A6,
|
||||
"BcdOSLoaderBoolean_EmsEnabled" : 0x260000b0,
|
||||
"BcdOSLoaderInteger_DriverLoadFailurePolicy" : 0x250000c1,
|
||||
"BcdOSLoaderInteger_BootMenuPolicy" : 0x250000C2,
|
||||
"BcdOSLoaderBoolean_AdvancedOptionsOneTime" : 0x260000C3,
|
||||
"BcdOSLoaderInteger_BootStatusPolicy" : 0x250000E0,
|
||||
"BcdOSLoaderBoolean_DisableElamDrivers" : 0x260000E1,
|
||||
"BcdOSLoaderInteger_HypervisorLaunchType" : 0x250000F0,
|
||||
"BcdOSLoaderBoolean_HypervisorDebuggerEnabled" : 0x260000F2,
|
||||
"BcdOSLoaderInteger_HypervisorDebuggerType" : 0x250000F3,
|
||||
"BcdOSLoaderInteger_HypervisorDebuggerPortNumber" : 0x250000F4,
|
||||
"BcdOSLoaderInteger_HypervisorDebuggerBaudrate" : 0x250000F5,
|
||||
"BcdOSLoaderInteger_HypervisorDebugger1394Channel" : 0x250000F6,
|
||||
"BcdOSLoaderInteger_BootUxPolicy" : 0x250000F7,
|
||||
"BcdOSLoaderString_HypervisorDebuggerBusParams" : 0x220000F9,
|
||||
"BcdOSLoaderInteger_HypervisorNumProc" : 0x250000FA,
|
||||
"BcdOSLoaderInteger_HypervisorRootProcPerNode" : 0x250000FB,
|
||||
"BcdOSLoaderBoolean_HypervisorUseLargeVTlb" : 0x260000FC,
|
||||
"BcdOSLoaderInteger_HypervisorDebuggerNetHostIp" : 0x250000FD,
|
||||
"BcdOSLoaderInteger_HypervisorDebuggerNetHostPort" : 0x250000FE,
|
||||
"BcdOSLoaderInteger_TpmBootEntropyPolicy" : 0x25000100,
|
||||
"BcdOSLoaderString_HypervisorDebuggerNetKey" : 0x22000110,
|
||||
"BcdOSLoaderBoolean_HypervisorDebuggerNetDhcp" : 0x26000114,
|
||||
"BcdOSLoaderInteger_HypervisorIommuPolicy" : 0x25000115,
|
||||
"BcdOSLoaderInteger_XSaveDisable" : 0x2500012b
|
||||
}
|
||||
|
||||
|
||||
def format_value(bcd, bcd_value):
|
||||
|
||||
name = bcd.value_key(bcd_value)
|
||||
(type, length) = bcd.value_type(bcd_value)
|
||||
|
||||
typename = ""
|
||||
str_value = ""
|
||||
if type == REG_SZ:
|
||||
typename = "SZ"
|
||||
str_value = bcd.value_string(bcd_value)
|
||||
elif type == REG_DWORD:
|
||||
typename = "DWORD"
|
||||
dval = bcd.value_dword(bcd_value)
|
||||
|
||||
str_value = hex(dval) + " (" + str(bcd.value_dword(bcd_value)) + ")"
|
||||
elif type == REG_BINARY:
|
||||
typename = "BIN"
|
||||
(length, value) = bcd.value_value(bcd_value)
|
||||
str_value = value.hex()
|
||||
elif type == REG_DWORD_BIG_ENDIAN:
|
||||
typename = "DWORD_BE"
|
||||
elif type == REG_EXPAND_SZ:
|
||||
typename = "EXPAND SZ"
|
||||
elif type == REG_FULL_RESOURCE_DESCRIPTOR:
|
||||
typename = "RES DESC"
|
||||
elif type == REG_LINK:
|
||||
typename = "LINK"
|
||||
elif type == REG_MULTI_SZ:
|
||||
typename = "MULTISZ"
|
||||
(length, str_value) = bcd.value_value(bcd_value)
|
||||
str_value = str_value.decode('utf-16le')
|
||||
str_value = str_value.replace("\0", ";")
|
||||
#value = ";".join("\0".split(value))
|
||||
elif type == REG_NONE:
|
||||
typename = "NONE"
|
||||
elif type == REG_QWORD:
|
||||
typename = "QWORD"
|
||||
elif type == REG_RESOURCE_LIST:
|
||||
typename = "RES LIST"
|
||||
elif type == REG_RESOURCE_REQUIREMENTS_LIST:
|
||||
typename = "REQ LIST"
|
||||
else:
|
||||
typename = str(type)
|
||||
str_value = "???"
|
||||
|
||||
|
||||
return (typename, length, str_value)
|
||||
|
||||
def dump_all(root, depth = 0):
|
||||
|
||||
padding = "\t" * depth
|
||||
|
||||
children = bcd.node_children(root)
|
||||
|
||||
if len(children) > 0:
|
||||
|
||||
for child in children:
|
||||
name = bcd.node_name(child)
|
||||
print(f"{padding}{name}")
|
||||
|
||||
dump_all(child, depth + 1)
|
||||
# print(f"Child: {child}")
|
||||
|
||||
#print(f"Values: {num_vals}")
|
||||
return
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
values = bcd.node_values(root)
|
||||
#print(f"Value list: {values}")
|
||||
|
||||
for v in values:
|
||||
(type_name, length, str_value) = format_value(bcd, v)
|
||||
name = bcd.value_key(v)
|
||||
|
||||
print(f"{padding}{name: <16}: [{type_name: <10}]; ({length: < 4}) {str_value}")
|
||||
|
||||
|
||||
class WindowsBCD:
|
||||
def __init__(self, filename):
|
||||
self.filename = filename
|
||||
self.bcd = Hivex(filename)
|
||||
|
||||
def dump(self, root=None, depth = 0):
|
||||
padding = "\t" * depth
|
||||
|
||||
if root is None:
|
||||
root = self.bcd.root()
|
||||
|
||||
children = self.bcd.node_children(root)
|
||||
|
||||
if len(children) > 0:
|
||||
for child in children:
|
||||
name = self.bcd.node_name(child)
|
||||
print(f"{padding}{name}")
|
||||
|
||||
self.dump(child, depth + 1)
|
||||
return
|
||||
|
||||
values = self.bcd.node_values(root)
|
||||
|
||||
for v in values:
|
||||
(type_name, length, str_value) = format_value(self.bcd, v)
|
||||
name = self.bcd.value_key(v)
|
||||
|
||||
print(f"{padding}{name: <16}: [{type_name: <10}]; ({length: < 4}) {str_value}")
|
||||
|
||||
def list(self):
|
||||
root = self.bcd.root()
|
||||
objects = self.bcd.node_get_child(root, "Objects")
|
||||
|
||||
for child in self.bcd.node_children(objects):
|
||||
entry_id = self.bcd.node_name(child)
|
||||
|
||||
elements = self.bcd.node_get_child(child, "Elements")
|
||||
description_entry = self.bcd.node_get_child(elements, "12000004")
|
||||
|
||||
if description_entry:
|
||||
values = self.bcd.node_values(description_entry)
|
||||
if values:
|
||||
(type_name, length, str_value) = format_value(self.bcd, values[0])
|
||||
print(f"{entry_id}: {str_value}")
|
||||
else:
|
||||
print(f"{entry_id}: [no description value!?]")
|
||||
|
||||
|
||||
appdevice_entry = self.bcd.node_get_child(elements, "11000001")
|
||||
|
||||
if appdevice_entry:
|
||||
values = self.bcd.node_values(appdevice_entry)
|
||||
(length, data) = self.bcd.value_value(values[0])
|
||||
hex = data.hex()
|
||||
print(f"LEN: {length}, HEX: {hex}, RAW: {data}")
|
||||
if len(data) > 10:
|
||||
etype = struct.unpack_from('<I', data, offset = 16)
|
||||
print(f"Type: {etype}")
|
||||
|
||||
|
||||
|
||||
else:
|
||||
print(f"{entry_id}: [no description entry 12000004]")
|
||||
|
||||
|
||||
parser = argparse.ArgumentParser(
|
||||
prog="Windows BCD parser",
|
||||
description="Parses the BCD",
|
||||
)
|
||||
|
||||
parser.add_argument("--db", type=str, metavar='BCD file', help="Database to use")
|
||||
parser.add_argument("--dump", action='store_true', help="Dumps the specified database")
|
||||
parser.add_argument("--list", action='store_true', help="Lists boot entries in the specified database")
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
bcdobj = WindowsBCD(args.db)
|
||||
|
||||
if args.dump:
|
||||
# "/home/vadim/opengnsys/winboot/boot-copy/EFI/Microsoft/Boot/BCD"
|
||||
#bcd = Hivex(args.dump)
|
||||
|
||||
#root = bcd.root()
|
||||
#dump_all(root)
|
||||
bcdobj.dump()
|
||||
elif args.list:
|
||||
bcdobj.list()
|
115
gitlib/disk.py
115
gitlib/disk.py
|
@ -1,115 +0,0 @@
|
|||
|
||||
import logging
|
||||
import subprocess
|
||||
import re
|
||||
|
||||
# pylint: disable=locally-disabled, line-too-long, logging-fstring-interpolation, too-many-lines
|
||||
|
||||
|
||||
class DiskLibrary:
|
||||
def __init__(self):
|
||||
self.logger = logging.getLogger("OpengnsysDiskLibrary")
|
||||
self.logger.setLevel(logging.DEBUG)
|
||||
|
||||
def split_device_partition(self, device):
|
||||
"""
|
||||
Parses a device file like /dev/sda3 into the root device (/dev/sda) and partition number (3)
|
||||
|
||||
Args:
|
||||
device (str): Device in /dev
|
||||
|
||||
Returns:
|
||||
[base_device, partno]
|
||||
"""
|
||||
|
||||
r = re.compile("^(.*?)(\\d+)$")
|
||||
m = r.match(device)
|
||||
disk = m.group(1)
|
||||
partno = int(m.group(2))
|
||||
|
||||
self.logger.debug(f"{device} parsed into disk device {disk}, partition {partno}")
|
||||
return (disk, partno)
|
||||
|
||||
def get_disk_json_data(self, device):
|
||||
"""
|
||||
Returns the partition JSON data dump for the entire disk, even if a partition is passed.
|
||||
|
||||
This is specifically in the format used by sfdisk.
|
||||
|
||||
Args:
|
||||
device (str): Block device, eg, /dev/sda3
|
||||
|
||||
Returns:
|
||||
str: JSON dump produced by sfdisk
|
||||
"""
|
||||
(disk, partno) = self.split_device_partition(device)
|
||||
|
||||
result = subprocess.run(["/usr/sbin/sfdisk", "--json", disk], check=True, capture_output=True, encoding='utf-8')
|
||||
return result.stdout.strip()
|
||||
|
||||
def get_disk_uuid(self, device):
|
||||
"""
|
||||
Returns the UUID of the disk itself, if there's a GPT partition table.
|
||||
|
||||
Args:
|
||||
device (str): Block device, eg, /dev/sda3
|
||||
|
||||
Returns:
|
||||
str: UUID
|
||||
"""
|
||||
(disk, partno) = self.split_device_partition(device)
|
||||
|
||||
result = subprocess.run(["/usr/sbin/sfdisk", "--disk-id", disk], check=True, capture_output=True, encoding='utf-8')
|
||||
return result.stdout.strip()
|
||||
|
||||
def set_disk_uuid(self, device, uuid):
|
||||
|
||||
(disk, partno) = self.split_device_partition(device)
|
||||
|
||||
subprocess.run(["/usr/sbin/sfdisk", "--disk-id", disk, uuid], check=True, encoding='utf-8')
|
||||
|
||||
|
||||
def get_partition_uuid(self, device):
|
||||
"""
|
||||
Returns the UUID of the partition, if there's a GPT partition table.
|
||||
|
||||
Args:
|
||||
device (str): Block device, eg, /dev/sda3
|
||||
|
||||
Returns:
|
||||
str: UUID
|
||||
"""
|
||||
|
||||
(disk, partno) = self.split_device_partition(device)
|
||||
|
||||
result = subprocess.run(["/usr/sbin/sfdisk", "--part-uuid", disk, str(partno)], check=True, capture_output=True, encoding='utf-8')
|
||||
return result.stdout.strip()
|
||||
|
||||
def set_partition_uuid(self, device, uuid):
|
||||
(disk, partno) = self.split_device_partition(device)
|
||||
|
||||
subprocess.run(["/usr/sbin/sfdisk", "--part-uuid", disk, str(partno), uuid], check=True, encoding='utf-8')
|
||||
|
||||
def get_partition_type(self, device):
|
||||
"""
|
||||
Returns the type UUID of the partition, if there's a GPT partition table.
|
||||
|
||||
Args:
|
||||
device (str): Block device, eg, /dev/sda3
|
||||
|
||||
Returns:
|
||||
str: UUID
|
||||
"""
|
||||
|
||||
(disk, partno) = self.split_device_partition(device)
|
||||
|
||||
result = subprocess.run(["/usr/sbin/sfdisk", "--part-type", disk, str(partno)], check=True, capture_output=True, encoding='utf-8')
|
||||
return result.stdout.strip()
|
||||
|
||||
def set_partition_type(self, device, uuid):
|
||||
(disk, partno) = self.split_device_partition(device)
|
||||
|
||||
subprocess.run(["/usr/sbin/sfdisk", "--part-type", disk, str(partno), uuid], check=True, encoding='utf-8')
|
||||
|
||||
|
||||
|
|
@ -1,544 +0,0 @@
|
|||
|
||||
import logging
|
||||
import subprocess
|
||||
import os
|
||||
import json
|
||||
import blkid
|
||||
import time
|
||||
|
||||
from ntfs import *
|
||||
|
||||
|
||||
|
||||
# pylint: disable=locally-disabled, line-too-long, logging-fstring-interpolation, too-many-lines
|
||||
|
||||
|
||||
class FilesystemLibrary:
|
||||
def __init__(self, ntfs_implementation = NTFSImplementation.KERNEL):
|
||||
self.logger = logging.getLogger("OpengnsysFilesystemLibrary")
|
||||
self.logger.setLevel(logging.DEBUG)
|
||||
|
||||
self.mounts = {}
|
||||
self.base_mount_path = "/mnt"
|
||||
self.ntfs_implementation = ntfs_implementation
|
||||
|
||||
self.update_mounts()
|
||||
|
||||
def _rmmod(self, module):
|
||||
self.logger.debug("Trying to unload module {module}...")
|
||||
subprocess.run(["/usr/sbin/rmmod", module], check=False)
|
||||
|
||||
def _modprobe(self, module):
|
||||
self.logger.debug("Trying to load module {module}...")
|
||||
subprocess.run(["/usr/sbin/modprobe", module], check=True)
|
||||
|
||||
|
||||
# _parse_mounts
|
||||
def update_mounts(self):
|
||||
"""
|
||||
Update the current mount points by parsing the /proc/mounts file.
|
||||
|
||||
This method reads the /proc/mounts file to gather information about
|
||||
the currently mounted filesystems. It stores this information in a
|
||||
dictionary where the keys are the mount points and the values are
|
||||
dictionaries containing details about each filesystem.
|
||||
|
||||
The details stored for each filesystem include:
|
||||
- device: The device file associated with the filesystem.
|
||||
- mountpoint: The directory where the filesystem is mounted.
|
||||
- type: The type of the filesystem (e.g., ext4, vfat).
|
||||
- options: Mount options associated with the filesystem.
|
||||
- dump_freq: The dump frequency for the filesystem.
|
||||
- passno: The pass number for filesystem checks.
|
||||
|
||||
The method also adds an entry for each mount point with a trailing
|
||||
slash to ensure consistency in accessing the mount points.
|
||||
|
||||
Attributes:
|
||||
mounts (dict): A dictionary where keys are mount points and values
|
||||
are dictionaries containing filesystem details.
|
||||
"""
|
||||
filesystems = {}
|
||||
|
||||
self.logger.debug("Parsing /proc/mounts")
|
||||
|
||||
with open("/proc/mounts", 'r', encoding='utf-8') as mounts:
|
||||
for line in mounts:
|
||||
parts = line.split()
|
||||
data = {}
|
||||
data['device'] = parts[0]
|
||||
data['mountpoint'] = parts[1]
|
||||
data['type'] = parts[2]
|
||||
data['options'] = parts[3]
|
||||
data['dump_freq'] = parts[4]
|
||||
data['passno'] = parts[5]
|
||||
|
||||
filesystems[data["mountpoint"]] = data
|
||||
filesystems[data["mountpoint"] + "/"] = data
|
||||
|
||||
self.mounts = filesystems
|
||||
|
||||
def find_mountpoint(self, device):
|
||||
"""
|
||||
Find the mount point for a given device.
|
||||
|
||||
This method checks if the specified device is currently mounted and returns
|
||||
the corresponding mount point if it is found.
|
||||
|
||||
Args:
|
||||
device (str): The path to the device to check.
|
||||
|
||||
Returns:
|
||||
str or None: The mount point of the device if it is mounted, otherwise None.
|
||||
"""
|
||||
norm = os.path.normpath(device)
|
||||
|
||||
self.logger.debug(f"Checking if {device} is mounted")
|
||||
for mountpoint, mount in self.mounts.items():
|
||||
#self.logger.debug(f"Item: {mount}")
|
||||
#self.logger.debug(f"Checking: " + mount['device'])
|
||||
if mount['device'] == norm:
|
||||
return mountpoint
|
||||
|
||||
return None
|
||||
|
||||
def find_device(self, mountpoint):
|
||||
"""
|
||||
Find the device corresponding to a given mount point.
|
||||
|
||||
Args:
|
||||
mountpoint (str): The mount point to search for.
|
||||
|
||||
Returns:
|
||||
str or None: The device corresponding to the mount point if found,
|
||||
otherwise None.
|
||||
"""
|
||||
self.update_mounts()
|
||||
self.logger.debug("Finding device corresponding to mount point %s", mountpoint)
|
||||
if mountpoint in self.mounts:
|
||||
return self.mounts[mountpoint]['device']
|
||||
else:
|
||||
self.logger.warning("Failed to find mountpoint %s", mountpoint)
|
||||
return None
|
||||
|
||||
def is_mounted(self, device = None, mountpoint = None):
|
||||
def is_mounted(self, device=None, mountpoint=None):
|
||||
"""
|
||||
Check if a device or mountpoint is currently mounted.
|
||||
|
||||
Either checking by device or mountpoint is valid.
|
||||
|
||||
Args:
|
||||
device (str, optional): The device to check if it is mounted.
|
||||
Defaults to None.
|
||||
mountpoint (str, optional): The mountpoint to check if it is mounted.
|
||||
Defaults to None.
|
||||
|
||||
Returns:
|
||||
bool: True if the device is mounted or the mountpoint is in the list
|
||||
of mounts, False otherwise.
|
||||
"""
|
||||
self.update_mounts()
|
||||
if device:
|
||||
return not self.find_mountpoint(device) is None
|
||||
else:
|
||||
return mountpoint in self.mounts
|
||||
|
||||
def unmount(self, device = None, mountpoint = None):
|
||||
def unmount(self, device=None, mountpoint=None):
|
||||
"""
|
||||
Unmounts a filesystem.
|
||||
|
||||
This method unmounts a filesystem either by the device name or the mountpoint.
|
||||
If a device is provided, it finds the corresponding mountpoint and unmounts it.
|
||||
If a mountpoint is provided directly, it unmounts the filesystem at that mountpoint.
|
||||
|
||||
Args:
|
||||
device (str, optional): The device name to unmount. Defaults to None.
|
||||
mountpoint (str, optional): The mountpoint to unmount. Defaults to None.
|
||||
|
||||
Raises:
|
||||
subprocess.CalledProcessError: If the unmount command fails.
|
||||
|
||||
Logs:
|
||||
Debug information about the unmounting process.
|
||||
"""
|
||||
if device:
|
||||
self.logger.debug("Finding mountpoint of %s", device)
|
||||
mountpoint = self.find_mountpoint(device)
|
||||
|
||||
if not mountpoint is None:
|
||||
self.logger.debug(f"Unmounting {mountpoint}")
|
||||
|
||||
done = False
|
||||
start_time = time.time()
|
||||
timeout = 60
|
||||
|
||||
|
||||
while not done and (time.time() - start_time) < timeout:
|
||||
ret = subprocess.run(["/usr/bin/umount", mountpoint], check=False, capture_output=True, encoding='utf-8')
|
||||
if ret.returncode == 0:
|
||||
done=True
|
||||
else:
|
||||
if "target is busy" in ret.stderr:
|
||||
self.logger.debug("Filesystem busy, waiting. %.1f seconds left", timeout - (time.time() - start_time))
|
||||
time.sleep(0.1)
|
||||
else:
|
||||
raise subprocess.CalledProcessError(ret.returncode, ret.args, output=ret.stdout, stderr=ret.stderr)
|
||||
|
||||
# We've unmounted a new filesystem, update our filesystems list
|
||||
self.update_mounts()
|
||||
else:
|
||||
self.logger.debug(f"{device} is not mounted")
|
||||
|
||||
|
||||
def mount(self, device, mountpoint, filesystem = None):
|
||||
"""
|
||||
Mounts a device to a specified mountpoint.
|
||||
|
||||
Parameters:
|
||||
device (str): The device to be mounted (e.g., '/dev/sda1').
|
||||
mountpoint (str): The directory where the device will be mounted.
|
||||
filesystem (str, optional): The type of filesystem to be used (e.g., 'ext4', 'ntfs'). Defaults to None.
|
||||
|
||||
Raises:
|
||||
subprocess.CalledProcessError: If the mount command fails.
|
||||
|
||||
Logs:
|
||||
Debug information about the mounting process, including the mount command, return code, stdout, and stderr.
|
||||
|
||||
Side Effects:
|
||||
Creates the mountpoint directory if it does not exist.
|
||||
Updates the internal list of mounted filesystems.
|
||||
"""
|
||||
self.logger.debug(f"Mounting {device} at {mountpoint}")
|
||||
|
||||
if not os.path.exists(mountpoint):
|
||||
self.logger.debug(f"Creating directory {mountpoint}")
|
||||
os.mkdir(mountpoint)
|
||||
|
||||
mount_cmd = ["/usr/bin/mount"]
|
||||
|
||||
if not filesystem is None:
|
||||
mount_cmd = mount_cmd + ["-t", filesystem]
|
||||
|
||||
mount_cmd = mount_cmd + [device, mountpoint]
|
||||
|
||||
self.logger.debug(f"Mount command: {mount_cmd}")
|
||||
result = subprocess.run(mount_cmd, check=True, capture_output = True)
|
||||
|
||||
self.logger.debug(f"retorno: {result.returncode}")
|
||||
self.logger.debug(f"stdout: {result.stdout}")
|
||||
self.logger.debug(f"stderr: {result.stderr}")
|
||||
|
||||
# We've mounted a new filesystem, update our filesystems list
|
||||
self.update_mounts()
|
||||
|
||||
def ensure_mounted(self, device):
|
||||
"""
|
||||
Ensure that the given device is mounted.
|
||||
|
||||
This method attempts to mount the specified device to a path derived from
|
||||
the base mount path and the device's basename. If the device is of type NTFS,
|
||||
it uses the NTFSLibrary to handle the mounting process. For other filesystem
|
||||
types, it uses a generic mount method.
|
||||
|
||||
Args:
|
||||
device (str): The path to the device that needs to be mounted.
|
||||
|
||||
Returns:
|
||||
str: The path where the device is mounted.
|
||||
|
||||
Logs:
|
||||
- Info: When starting the mounting process.
|
||||
- Debug: Various debug information including the mount path, filesystem type,
|
||||
and success message.
|
||||
|
||||
Raises:
|
||||
OSError: If there is an error creating the mount directory or mounting the device.
|
||||
"""
|
||||
|
||||
self.logger.info("Mounting %s", device)
|
||||
|
||||
self.unmount(device = device)
|
||||
path = os.path.join(self.base_mount_path, os.path.basename(device))
|
||||
|
||||
self.logger.debug(f"Will mount repo at {path}")
|
||||
if not os.path.exists(path):
|
||||
os.mkdir(path)
|
||||
|
||||
if self.filesystem_type(device) == "ntfs":
|
||||
self.logger.debug("Handing a NTFS filesystem")
|
||||
|
||||
self._modprobe("ntfs3")
|
||||
self.ntfsfix(device)
|
||||
|
||||
ntfs = NTFSLibrary(self.ntfs_implementation)
|
||||
ntfs.mount_filesystem(device, path)
|
||||
self.update_mounts()
|
||||
|
||||
else:
|
||||
self.logger.debug("Handling a non-NTFS filesystem")
|
||||
self.mount(device, path)
|
||||
|
||||
self.logger.debug("Successfully mounted at %s", path)
|
||||
return path
|
||||
|
||||
|
||||
def filesystem_type(self, device = None, mountpoint = None):
|
||||
"""
|
||||
Determine the filesystem type of a given device or mountpoint.
|
||||
|
||||
Args:
|
||||
device (str, optional): The device to probe. If not provided, the device
|
||||
will be determined based on the mountpoint.
|
||||
mountpoint (str, optional): The mountpoint to find the device for. This
|
||||
is used only if the device is not provided.
|
||||
|
||||
Returns:
|
||||
str: The filesystem type of the device.
|
||||
|
||||
Raises:
|
||||
KeyError: If the filesystem type cannot be determined from the probe.
|
||||
|
||||
Logs:
|
||||
Debug: Logs the process of finding the device, probing the device, and
|
||||
the determined filesystem type.
|
||||
"""
|
||||
|
||||
if device is None:
|
||||
self.logger.debug("Finding device for mountpoint %s", mountpoint)
|
||||
device = self.find_device(mountpoint)
|
||||
|
||||
self.logger.debug(f"Probing {device}")
|
||||
|
||||
pr = blkid.Probe()
|
||||
pr.set_device(device)
|
||||
pr.enable_superblocks(True)
|
||||
pr.set_superblocks_flags(blkid.SUBLKS_TYPE | blkid.SUBLKS_USAGE | blkid.SUBLKS_UUID | blkid.SUBLKS_UUIDRAW | blkid.SUBLKS_LABELRAW)
|
||||
pr.do_safeprobe()
|
||||
|
||||
fstype = pr["TYPE"].decode('utf-8')
|
||||
self.logger.debug(f"FS type is {fstype}")
|
||||
|
||||
return fstype
|
||||
|
||||
def is_filesystem(self, path):
|
||||
"""
|
||||
Check if the given path is a filesystem root.
|
||||
|
||||
Args:
|
||||
path (str): The path to check.
|
||||
|
||||
Returns:
|
||||
bool: True if the path is a filesystem root, False otherwise.
|
||||
"""
|
||||
|
||||
# This is just an alias for better code readability
|
||||
return self.is_mounted(mountpoint = path)
|
||||
|
||||
def create_filesystem(self, fs_type = None, fs_uuid = None, device = None):
|
||||
"""
|
||||
Create a filesystem on the specified device.
|
||||
|
||||
Parameters:
|
||||
fs_type (str): The type of filesystem to create (e.g., 'ntfs', 'ext4', 'xfs', 'btrfs').
|
||||
fs_uuid (str): The UUID to assign to the filesystem.
|
||||
device (str): The device on which to create the filesystem (e.g., '/dev/sda1').
|
||||
|
||||
Raises:
|
||||
RuntimeError: If the filesystem type is not recognized or if the filesystem creation command fails.
|
||||
|
||||
"""
|
||||
|
||||
self.logger.info(f"Creating filesystem {fs_type} with UUID {fs_uuid} in {device}")
|
||||
|
||||
if fs_type == "ntfs" or fs_type == "ntfs3":
|
||||
self.logger.debug("Creating NTFS filesystem")
|
||||
ntfs = NTFSLibrary(self.ntfs_implementation)
|
||||
ntfs.create_filesystem(device, "NTFS")
|
||||
ntfs.modify_uuid(device, fs_uuid)
|
||||
|
||||
else:
|
||||
command = [f"/usr/sbin/mkfs.{fs_type}"]
|
||||
command_args = []
|
||||
|
||||
if fs_type == "ext4" or fs_type == "ext3":
|
||||
command_args = ["-U", fs_uuid, "-F", device]
|
||||
elif fs_type == "xfs":
|
||||
command_args = ["-m", f"uuid={fs_uuid}", "-f", device]
|
||||
elif fs_type == "btrfs":
|
||||
command_args = ["-U", fs_uuid, "-f", device]
|
||||
else:
|
||||
raise RuntimeError(f"Don't know how to create filesystem of type {fs_type}")
|
||||
|
||||
command = command + command_args
|
||||
|
||||
self.logger.debug(f"Creating Linux filesystem of type {fs_type} on {device}, command {command}")
|
||||
result = subprocess.run(command, check = True, capture_output=True)
|
||||
|
||||
self.logger.debug(f"retorno: {result.returncode}")
|
||||
self.logger.debug(f"stdout: {result.stdout}")
|
||||
self.logger.debug(f"stderr: {result.stderr}")
|
||||
|
||||
|
||||
|
||||
def mklostandfound(self, path):
|
||||
"""
|
||||
Recreate the lost+found if necessary.
|
||||
|
||||
When cloning at the root of a filesystem, cleaning the contents
|
||||
removes the lost+found directory. This is a special directory that requires the use of
|
||||
a tool to recreate it.
|
||||
|
||||
It may fail if the filesystem does not need it. We consider this harmless and ignore it.
|
||||
|
||||
The command is entirely skipped on NTFS, as mklost+found may malfunction if run on it,
|
||||
and has no useful purpose.
|
||||
"""
|
||||
if self.is_filesystem(path):
|
||||
if self.filesystem_type(mountpoint=path) == "ntfs":
|
||||
self.logger.debug("Not running mklost+found on NTFS")
|
||||
return
|
||||
|
||||
|
||||
curdir = os.getcwd()
|
||||
result = None
|
||||
|
||||
try:
|
||||
self.logger.debug(f"Re-creating lost+found in {path}")
|
||||
os.chdir(path)
|
||||
result = subprocess.run(["/usr/sbin/mklost+found"], check=True, capture_output=True)
|
||||
except subprocess.SubprocessError as e:
|
||||
self.logger.warning(f"Error running mklost+found: {e}")
|
||||
|
||||
if result:
|
||||
self.logger.debug(f"retorno: {result.returncode}")
|
||||
self.logger.debug(f"stdout: {result.stdout}")
|
||||
self.logger.debug(f"stderr: {result.stderr}")
|
||||
|
||||
os.chdir(curdir)
|
||||
|
||||
def ntfsfix(self, device):
|
||||
"""
|
||||
Run the ntfsfix command on the specified device.
|
||||
|
||||
This method uses the ntfsfix utility to fix common NTFS problems on the given device.
|
||||
|
||||
This allows mounting an unclean NTFS filesystem.
|
||||
|
||||
Args:
|
||||
device (str): The path to the device to be fixed.
|
||||
|
||||
Raises:
|
||||
subprocess.CalledProcessError: If the ntfsfix command fails.
|
||||
"""
|
||||
self.logger.debug(f"Running ntfsfix on {device}")
|
||||
subprocess.run(["/usr/bin/ntfsfix", "-d", device], check=True)
|
||||
|
||||
|
||||
def unload_ntfs(self):
|
||||
"""
|
||||
Unloads the NTFS filesystem module.
|
||||
|
||||
This is a function added as a result of NTFS kernel module troubleshooting,
|
||||
to try to ensure that NTFS code is only active as long as necessary.
|
||||
|
||||
The module is internally loaded as needed, so there's no load_ntfs function.
|
||||
|
||||
It may be removed in the future.
|
||||
|
||||
Raises:
|
||||
RuntimeError: If the module cannot be removed.
|
||||
"""
|
||||
self._rmmod("ntfs3")
|
||||
|
||||
def find_boot_device(self):
|
||||
"""
|
||||
Searches for the EFI boot partition on the system.
|
||||
|
||||
This method scans the system's partitions to locate the EFI boot partition,
|
||||
which is identified by the GUID "C12A7328-F81F-11D2-BA4B-00A0C93EC93B".
|
||||
|
||||
Returns:
|
||||
str: The device node of the EFI partition if found, otherwise None.
|
||||
|
||||
Logs:
|
||||
- Debug messages indicating the progress of the search.
|
||||
- A warning message if the EFI partition is not found.
|
||||
"""
|
||||
disks = []
|
||||
|
||||
self.logger.debug("Looking for EFI partition")
|
||||
with open("/proc/partitions", "r", encoding='utf-8') as partitions_file:
|
||||
line_num=0
|
||||
for line in partitions_file:
|
||||
if line_num >=2:
|
||||
data = line.split()
|
||||
disk = data[3]
|
||||
disks.append(disk)
|
||||
self.logger.debug(f"Disk: {disk}")
|
||||
|
||||
line_num = line_num + 1
|
||||
|
||||
for disk in disks:
|
||||
self.logger.debug("Loading partitions for disk %s", disk)
|
||||
#disk_json_data = subprocess.run(["/usr/sbin/sfdisk", "-J", f"/dev/{disk}"], check=False, capture_output=True)
|
||||
sfdisk_out = subprocess.run(["/usr/sbin/sfdisk", "-J", f"/dev/{disk}"], check=False, capture_output=True)
|
||||
|
||||
if sfdisk_out.returncode == 0:
|
||||
disk_json_data = sfdisk_out.stdout
|
||||
disk_data = json.loads(disk_json_data)
|
||||
|
||||
for part in disk_data["partitiontable"]["partitions"]:
|
||||
self.logger.debug("Checking partition %s", part)
|
||||
if part["type"] == "C12A7328-F81F-11D2-BA4B-00A0C93EC93B":
|
||||
self.logger.debug("EFI partition found at %s", part["node"])
|
||||
return part["node"]
|
||||
else:
|
||||
self.logger.debug("sfdisk returned with code %i, error %s", sfdisk_out.returncode, sfdisk_out.stderr)
|
||||
|
||||
|
||||
self.logger.warning("Failed to find EFI partition!")
|
||||
|
||||
def temp_unmount(self, mountpoint):
|
||||
"""
|
||||
Temporarily unmounts the filesystem at the given mountpoint.
|
||||
|
||||
This method finds the device associated with the specified mountpoint,
|
||||
and returns the information to remount it with temp_remount.
|
||||
|
||||
The purpose of this function is to temporarily unmount a filesystem for
|
||||
actions like fsck, and to mount it back afterwards.
|
||||
|
||||
Args:
|
||||
mountpoint (str): The mountpoint of the filesystem to unmount.
|
||||
|
||||
Returns:
|
||||
dict: A dictionary containing the information needed to remount the filesystem.
|
||||
"""
|
||||
device = self.find_device(mountpoint)
|
||||
fs = self.filesystem_type(mountpoint = mountpoint)
|
||||
|
||||
data = {"mountpoint" : mountpoint, "device" :device, "filesystem" : fs}
|
||||
|
||||
self.logger.debug("Temporarily unmounting device %s, mounted on %s, fs type %s", mountpoint, device, fs)
|
||||
|
||||
self.unmount(mountpoint = mountpoint)
|
||||
return data
|
||||
|
||||
def temp_remount(self, unmount_data):
|
||||
"""
|
||||
Remounts a filesystem unmounted with temp_unmount
|
||||
|
||||
This method remounts a filesystem using the data provided by temp_unmount
|
||||
|
||||
Args:
|
||||
unmount_data (dict): A dictionary containing the data needed to remount the filesystem.
|
||||
|
||||
Returns:
|
||||
None
|
||||
"""
|
||||
|
||||
self.logger.debug("Remounting temporarily unmounted device %s on %s, fs type %s", unmount_data["device"], unmount_data["mountpoint"], unmount_data["filesystem"])
|
||||
self.mount(device = unmount_data["device"], mountpoint=unmount_data["mountpoint"], filesystem=unmount_data["filesystem"])
|
|
@ -1,52 +0,0 @@
|
|||
#!/usr/bin/env python3
|
||||
import unittest
|
||||
import logging
|
||||
import os
|
||||
import sys
|
||||
import urllib.request
|
||||
import tarfile
|
||||
import subprocess
|
||||
from shutil import rmtree
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
parent_dir = str(Path(__file__).parent.parent.absolute())
|
||||
sys.path.append(parent_dir)
|
||||
sys.path.append("/opengnsys/installer")
|
||||
print(parent_dir)
|
||||
|
||||
from gitlib import OpengnsysGitLibrary
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
class GitTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.logger = logging.getLogger("OpengnsysTest")
|
||||
self.oggit = OpengnsysGitLibrary()
|
||||
|
||||
self.logger.info("setUp()")
|
||||
if not hasattr(self, 'init_complete'):
|
||||
self.init_complete = True
|
||||
def test_init(self):
|
||||
self.assertIsNotNone(self.oggit)
|
||||
def test_acls(self):
|
||||
self.oggit.ogCreateAcl()
|
||||
|
||||
def test_sync_local(self):
|
||||
# self.oggit.ogSyncLocalGitImage()
|
||||
None
|
||||
|
||||
if __name__ == '__main__':
|
||||
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(name)20s - [%(levelname)5s] - %(message)s')
|
||||
logger = logging.getLogger(__name__)
|
||||
logger.setLevel(logging.DEBUG)
|
||||
logger.info("Inicio del programa")
|
||||
|
||||
unittest.main()
|
||||
|
||||
|
||||
|
||||
|
||||
|
1731
gitlib/gitlib.py
1731
gitlib/gitlib.py
File diff suppressed because it is too large
Load Diff
|
@ -1,22 +0,0 @@
|
|||
|
||||
|
||||
def parse_kernel_cmdline():
|
||||
"""Parse the kernel arguments to obtain configuration parameters in Oglive
|
||||
|
||||
OpenGnsys passes data in the kernel arguments, for example:
|
||||
[...] group=Aula_virtual ogrepo=192.168.2.1 oglive=192.168.2.1 [...]
|
||||
|
||||
Returns:
|
||||
dict: Dict of configuration parameters and their values.
|
||||
"""
|
||||
params = {}
|
||||
|
||||
with open("/proc/cmdline", encoding='utf-8') as cmdline:
|
||||
line = cmdline.readline()
|
||||
parts = line.split()
|
||||
for part in parts:
|
||||
if "=" in part:
|
||||
key, value = part.split("=")
|
||||
params[key] = value
|
||||
|
||||
return params
|
111
gitlib/ntfs.py
111
gitlib/ntfs.py
|
@ -1,111 +0,0 @@
|
|||
|
||||
import logging
|
||||
import subprocess
|
||||
|
||||
from enum import Enum
|
||||
|
||||
|
||||
class NTFSImplementation(Enum):
|
||||
KERNEL = 1
|
||||
NTFS3G = 2
|
||||
|
||||
|
||||
class NTFSLibrary:
|
||||
"""
|
||||
A library for managing NTFS filesystems.
|
||||
|
||||
Attributes:
|
||||
logger (logging.Logger): Logger for the class.
|
||||
implementation (NTFSImplementation): The implementation to use for mounting NTFS filesystems.
|
||||
"""
|
||||
|
||||
def __init__(self, implementation):
|
||||
"""
|
||||
Initializes the instance with the given implementation.
|
||||
|
||||
Args:
|
||||
implementation: The implementation to be used by the instance.
|
||||
|
||||
Attributes:
|
||||
logger (logging.Logger): Logger instance for the class, set to debug level.
|
||||
implementation: The implementation provided during initialization.
|
||||
"""
|
||||
self.logger = logging.getLogger("NTFSLibrary")
|
||||
self.logger.setLevel(logging.DEBUG)
|
||||
self.implementation = implementation
|
||||
|
||||
self.logger.debug("Initializing")
|
||||
|
||||
def create_filesystem(self, device, label):
|
||||
"""
|
||||
Creates an NTFS filesystem on the specified device with the given label.
|
||||
|
||||
Args:
|
||||
device (str): The device path where the NTFS filesystem will be created.
|
||||
label (str): The label to assign to the NTFS filesystem.
|
||||
|
||||
Returns:
|
||||
None
|
||||
|
||||
Logs:
|
||||
Logs the creation process with the device and label information.
|
||||
"""
|
||||
self.logger.info(f"Creating NTFS in {device} with label {label}")
|
||||
|
||||
subprocess.run(["/usr/sbin/mkntfs", device, "-Q", "-L", label], check=True)
|
||||
|
||||
|
||||
def mount_filesystem(self, device, mountpoint):
|
||||
"""
|
||||
Mounts a filesystem on the specified mountpoint using the specified NTFS implementation.
|
||||
|
||||
Args:
|
||||
device (str): The device path to be mounted (e.g., '/dev/sda1').
|
||||
mountpoint (str): The directory where the device will be mounted.
|
||||
|
||||
Raises:
|
||||
ValueError: If the NTFS implementation is unknown.
|
||||
|
||||
"""
|
||||
self.logger.info(f"Mounting {device} in {mountpoint} using implementation {self.implementation}")
|
||||
if self.implementation == NTFSImplementation.KERNEL:
|
||||
subprocess.run(["/usr/bin/mount", "-t", "ntfs3", device, mountpoint], check = True)
|
||||
elif self.implementation == NTFSImplementation.NTFS3G:
|
||||
subprocess.run(["/usr/bin/ntfs-3g", device, mountpoint], check = True)
|
||||
else:
|
||||
raise ValueError("Unknown NTFS implementation: {self.implementation}")
|
||||
|
||||
def modify_uuid(self, device, uuid):
|
||||
"""
|
||||
Modify the UUID of an NTFS device.
|
||||
|
||||
This function changes the UUID of the specified NTFS device to the given UUID.
|
||||
It reads the current UUID from the device, logs the change, and writes the new UUID.
|
||||
|
||||
Args:
|
||||
device (str): The path to the NTFS device file.
|
||||
uuid (str): The new UUID to be set, in hexadecimal string format.
|
||||
|
||||
Raises:
|
||||
IOError: If there is an error opening or writing to the device file.
|
||||
"""
|
||||
|
||||
ntfs_uuid_offset = 0x48
|
||||
ntfs_uuid_length = 8
|
||||
|
||||
binary_uuid = bytearray.fromhex(uuid)
|
||||
binary_uuid.reverse()
|
||||
|
||||
self.logger.info(f"Changing UUID on {device} to {uuid}")
|
||||
with open(device, 'r+b') as ntfs_dev:
|
||||
self.logger.debug("Reading %i bytes from offset %i", ntfs_uuid_length, ntfs_uuid_offset)
|
||||
|
||||
ntfs_dev.seek(ntfs_uuid_offset)
|
||||
prev_uuid = bytearray(ntfs_dev.read(ntfs_uuid_length))
|
||||
prev_uuid.reverse()
|
||||
prev_uuid_hex = bytearray.hex(prev_uuid)
|
||||
self.logger.debug(f"Previous UUID: {prev_uuid_hex}")
|
||||
|
||||
self.logger.debug("Writing...")
|
||||
ntfs_dev.seek(ntfs_uuid_offset)
|
||||
ntfs_dev.write(binary_uuid)
|
|
@ -1,11 +0,0 @@
|
|||
gitdb==4.0.11
|
||||
GitPython==3.1.43
|
||||
libarchive-c==5.1
|
||||
nose==1.3.7
|
||||
pathlib==1.0.1
|
||||
pkg_resources==0.0.0
|
||||
pylibacl==0.7.0
|
||||
pylibblkid==0.3
|
||||
pyxattr==0.8.1
|
||||
smmap==5.0.1
|
||||
tqdm==4.66.5
|
|
@ -1,32 +1,59 @@
|
|||
# Installing Dependencies for Python
|
||||
# Git component installer
|
||||
|
||||
Converting the code to Python 3 currently requires the packages specified in `requirements.txt`.
|
||||
This directory contains the installer for the git component for OpenGnsys.
|
||||
|
||||
To install Python dependencies, the `venv` module (https://docs.python.org/3/library/venv.html) is used, which installs all dependencies in an isolated environment separate from the system.
|
||||
It downloads, installs and configures Forgejo, creates the default repositories and configures SSH keys.
|
||||
|
||||
# Quick Installation
|
||||
|
||||
## Ubuntu 24.04
|
||||
|
||||
sudo apt install python3-git opengnsys-libarchive-c python3-termcolor bsdextrautils
|
||||
### Add the repository
|
||||
|
||||
## Add SSH Keys to oglive
|
||||
|
||||
The Git system accesses the ogrepository via SSH. To work, it needs the oglive to have an SSH key, and the ogrepository must accept it.
|
||||
Create the file `/etc/apt/sources.list.d/opengnsys.sources` with these contents:
|
||||
|
||||
The Git installer can make the required changes with:
|
||||
Types: deb
|
||||
URIs: https://ognproject.evlt.uma.es/debian-opengnsys/
|
||||
Suites: noble
|
||||
Components: main
|
||||
Signed-By:
|
||||
-----BEGIN PGP PUBLIC KEY BLOCK-----
|
||||
.
|
||||
mDMEZzx/SxYJKwYBBAHaRw8BAQdAa83CuAJ5/+7Pn9LHT/k34EAGpx5FnT/ExHSj
|
||||
XZG1JES0Ik9wZW5HbnN5cyA8b3Blbmduc3lzQG9wZW5nbnN5cy5lcz6ImQQTFgoA
|
||||
QRYhBC+J38Xsso227ZbDVt2S5xJQRhKDBQJnPH9LAhsDBQkFo5qABQsJCAcCAiIC
|
||||
BhUKCQgLAgQWAgMBAh4HAheAAAoJEN2S5xJQRhKDW/MBAO6swnpwdrbm48ypMyPh
|
||||
NboxvF7rCqBqHWwRHvkvrq7pAP9zd98r7z2AvqVXZxnaCsLTUNMEL12+DVZAUZ1G
|
||||
EquRBbg4BGc8f0sSCisGAQQBl1UBBQEBB0B6D6tkrwXSHi7ebGYsiMPntqwdkQ/S
|
||||
84SFTlSxRqdXfgMBCAeIfgQYFgoAJhYhBC+J38Xsso227ZbDVt2S5xJQRhKDBQJn
|
||||
PH9LAhsMBQkFo5qAAAoJEN2S5xJQRhKDJ+cBAM9jYbeq5VXkHLfODeVztgSXnSUe
|
||||
yklJ18oQmpeK5eWeAQDKYk/P0R+1ZJDItxkeP6pw62bCDYGQDvdDGPMAaIT6CA==
|
||||
=xcNc
|
||||
-----END PGP PUBLIC KEY BLOCK-----
|
||||
|
||||
./opengnsys_git_installer.py --set-ssh-key
|
||||
It's required to run `apt update` after creating this file
|
||||
|
||||
Or to do it for a specific oglive:
|
||||
### Install packages
|
||||
|
||||
./opengnsys_git_installer.py --set-ssh-key --oglive 1 # oglive number
|
||||
sudo apt install -y python3-git opengnsys-libarchive-c python3-termcolor python3-requests python3-tqdm bsdextrautils
|
||||
|
||||
Running this command automatically adds the SSH key to Forgejo.
|
||||
## Adding SSH Keys to oglive
|
||||
|
||||
The existing key can be extracted with:
|
||||
The Git system accesses the ogrepository via SSH. To function, it needs the oglive to have an SSH key, and for the ogrepository to accept it.
|
||||
|
||||
The Git installer can make the required changes by extracting an SSH key from an oglive and installing it in Forgejo. If there is a local ogboot installation, the installer will do this automatically. If there is not, it is necessary to provide the installer with an oglive from which to extract the key using the `--oglive-file` or `--oglive-url` parameter.
|
||||
|
||||
For example:
|
||||
|
||||
./opengnsys_git_installer.py --oglive-url https://example.com/ogLive-noble.iso
|
||||
|
||||
The installer will proceed to download the file, mount the ISO, and extract the key.
|
||||
|
||||
To perform the process after completing the installation and only add a key to an existing installation, use the `--set-ssh-key` parameter:
|
||||
|
||||
./opengnsys_git_installer.py --set-ssh-key --oglive-url https://example.com/ogLive-noble.iso
|
||||
|
||||
./opengnsys_git_installer.py --extract-ssh-key --quiet
|
||||
|
||||
# Running the Installer
|
||||
|
||||
|
|
|
@ -1,35 +1,58 @@
|
|||
# Instalación de dependencias para python
|
||||
# Instalador de componente Git
|
||||
|
||||
La conversion del código a Python 3 requiere actualmente los paquetes especificados en `requirements.txt`
|
||||
|
||||
Para instalar dependencias de python se usa el modulo venv (https://docs.python.org/3/library/venv.html) que instala todas las dependencias en un entorno independiente del sistema.
|
||||
Este directorio contiene el instalador de Git para OpenGnsys.
|
||||
|
||||
Descarga, instala y configura Forgejo, crea los repositorios por defecto, y configura claves de SSH.
|
||||
|
||||
# Instalación rápida
|
||||
|
||||
## Ubuntu 24.04
|
||||
|
||||
sudo apt install python3-git opengnsys-libarchive-c python3-termcolor bsdextrautils
|
||||
### Agregar repositorio
|
||||
|
||||
Crear el archivo `/etc/apt/sources.list.d/opengnsys.sources` con este contenido:
|
||||
|
||||
Types: deb
|
||||
URIs: https://ognproject.evlt.uma.es/debian-opengnsys/opengnsys
|
||||
Suites: noble
|
||||
Components: main
|
||||
Signed-By:
|
||||
-----BEGIN PGP PUBLIC KEY BLOCK-----
|
||||
.
|
||||
mDMEZzx/SxYJKwYBBAHaRw8BAQdAa83CuAJ5/+7Pn9LHT/k34EAGpx5FnT/ExHSj
|
||||
XZG1JES0Ik9wZW5HbnN5cyA8b3Blbmduc3lzQG9wZW5nbnN5cy5lcz6ImQQTFgoA
|
||||
QRYhBC+J38Xsso227ZbDVt2S5xJQRhKDBQJnPH9LAhsDBQkFo5qABQsJCAcCAiIC
|
||||
BhUKCQgLAgQWAgMBAh4HAheAAAoJEN2S5xJQRhKDW/MBAO6swnpwdrbm48ypMyPh
|
||||
NboxvF7rCqBqHWwRHvkvrq7pAP9zd98r7z2AvqVXZxnaCsLTUNMEL12+DVZAUZ1G
|
||||
EquRBbg4BGc8f0sSCisGAQQBl1UBBQEBB0B6D6tkrwXSHi7ebGYsiMPntqwdkQ/S
|
||||
84SFTlSxRqdXfgMBCAeIfgQYFgoAJhYhBC+J38Xsso227ZbDVt2S5xJQRhKDBQJn
|
||||
PH9LAhsMBQkFo5qAAAoJEN2S5xJQRhKDJ+cBAM9jYbeq5VXkHLfODeVztgSXnSUe
|
||||
yklJ18oQmpeK5eWeAQDKYk/P0R+1ZJDItxkeP6pw62bCDYGQDvdDGPMAaIT6CA==
|
||||
=xcNc
|
||||
-----END PGP PUBLIC KEY BLOCK-----
|
||||
|
||||
Es necesario ejecutar `apt update` después de crear el archivo.
|
||||
|
||||
### Instalar paquetes:
|
||||
|
||||
sudo apt install -y python3-git opengnsys-libarchive-c python3-termcolor python3-requests python3-tqdm bsdextrautils
|
||||
|
||||
|
||||
## Agregar claves de SSH a oglive
|
||||
|
||||
El sistema de Git accede al ogrepository por SSH. Para funcionar, necesita que el oglive tenga una clave de SSH, y que el ogrepository la acepte.
|
||||
|
||||
El instalador de Git puede realizar los cambios requeridos, con:
|
||||
El instalador de Git puede realizar los cambios requeridos, extrayendo una clave de SSH de un oglive e instalándola en Forgejo. Si hay una instalación de ogboot local, el instalador lo hará automáticamente. Si no la hay, es necesario darle al instalador un oglive del que extraer la clave con el parámetro `--oglive-file` o `--oglive-url`.
|
||||
|
||||
./opengnsys_git_installer.py --set-ssh-key
|
||||
Por ejemplo:
|
||||
|
||||
O para hacerlo contra un oglive especifico:
|
||||
./opengnsys_git_installer.py --oglive-url https://example.com/ogLive-noble.iso
|
||||
|
||||
./opengnsys_git_installer.py --set-ssh-key --oglive 1 # numero de oglive
|
||||
El instalador procederá a descargar el archivo, montar el ISO, y extraer la clave.
|
||||
|
||||
Ejecutar este comando agrega la clave de SSH a Forgejo automáticamente.
|
||||
Para hacer el proceso después de haber completado la instalación y solo agregar una clave a una instalación existente, usar el parámetro `--set-ssh-key`:
|
||||
|
||||
|
||||
La clave existente puede extraerse con:
|
||||
|
||||
./opengnsys_git_installer.py --extract-ssh-key --quiet
|
||||
./opengnsys_git_installer.py --set-ssh-key --oglive-url https://example.com/ogLive-noble.iso
|
||||
|
||||
# Ejecutar
|
||||
|
||||
|
@ -49,6 +72,8 @@ El usuario por defecto es `oggit` con password `opengnsys`.
|
|||
|
||||
El sistema OgGit requiere módulos de Python que no vienen en Ubuntu 24.04 o tienen versiones demasiado antiguas.
|
||||
|
||||
Los paquetes se pueden obtener desde el repositorio de OpenGnsys (ver arriba).
|
||||
|
||||
Los fuentes de los paquetes se encuentran en oggit/packages.
|
||||
|
||||
# Documentación de código fuente
|
||||
|
|
|
@ -0,0 +1,656 @@
|
|||
opengnsys-gitinstaller (0.5dev3) UNRELEASED; urgency=medium
|
||||
|
||||
[ OpenGnsys ]
|
||||
* Initial release.
|
||||
|
||||
[ Vadim Troshchinskiy ]
|
||||
* First commit
|
||||
* Add installer
|
||||
* Add requirements file
|
||||
|
||||
[ lgromero ]
|
||||
* refs #734 Creates first skeleton of symfony+swagger project
|
||||
|
||||
[ Vadim Troshchinskiy ]
|
||||
* Add Gitlib
|
||||
|
||||
[ lgromero ]
|
||||
* refs #734 Changes OgBootBundle name and adds a first endpoint to test
|
||||
* refs #734 Adds template of repository and branch endpoints
|
||||
|
||||
[ Vadim Troshchinskiy ]
|
||||
* Update docs to account for changes
|
||||
* Trivial API server
|
||||
* Ticket #753: Add repository listing
|
||||
* Ticket #735: List branches in repo
|
||||
* Add testing instructions
|
||||
* Agregar manejo de errrores
|
||||
* Ticket #741: Crear repo Ticket #736: Eliminar repo
|
||||
|
||||
[ lgromero ]
|
||||
* refs #734 Adds README for Api installation
|
||||
* refs #734 Control of errores and http codes in controler
|
||||
* refs #734 Renemas oggitservice
|
||||
|
||||
[ Vadim Troshchinskiy ]
|
||||
* Ticket #738, ticket #739: repo and sync backup protoype
|
||||
|
||||
[ lgromero ]
|
||||
* refs #734 Adds new endpoints sync and backup and status endpoint
|
||||
* refs #734 Adds nelmio api doc configuration
|
||||
* Adds .env file to root
|
||||
* refs #734 use environment variables in .env files and disable web depuration toolbar
|
||||
* refs #734 fix typo in .env and use oggit_url environment variable
|
||||
|
||||
[ Vadim Troshchinskiy ]
|
||||
* Ticket #738, ticket #739: git sync and backup
|
||||
|
||||
[ Nicolas Arenas ]
|
||||
* Add docker container files
|
||||
|
||||
[ Vadim Troshchinskiy ]
|
||||
* Ticket #737: GC
|
||||
* Use Paramiko and Gitpython for backups
|
||||
|
||||
[ Nicolas Arenas ]
|
||||
* Add mock api for testing dockerfile
|
||||
|
||||
[ Vadim Troshchinskiy ]
|
||||
* Ticket #740, listen on all hosts
|
||||
|
||||
[ lgromero ]
|
||||
* refs #734 Removes innecesaries parameters and changes php platform to 8.2
|
||||
* refs #734 just changes name and description in swagger web page
|
||||
|
||||
[ Vadim Troshchinskiy ]
|
||||
* Remove duplicated import
|
||||
* Documentation prototype
|
||||
* Update to 24.04, solves deployment issue
|
||||
* Add more documentation
|
||||
* Add API README
|
||||
* Add API examples
|
||||
* Update list of package requirements in oglive
|
||||
* Fix commandline parsing bug
|
||||
* Revert experimental Windows change
|
||||
* Fix ticket #770: Re-parse filesystems list after mounting
|
||||
* Use oglive server if ogrepository is not set
|
||||
* Ticket #770: Add sanity check
|
||||
* Ticket #771: Correctly create directories on metadata restoration
|
||||
* Ticket #780: Unmount before clone if needed
|
||||
* Fix ticket #800: sudo doesn't work
|
||||
|
||||
[ Vadim Trochinsky ]
|
||||
* Fix ticket #802: .git directory in filesystem root
|
||||
|
||||
[ Vadim Troshchinskiy ]
|
||||
* Fix ticket #805: Remove .git directory if it already exists when checking out
|
||||
* Ticket #770: Correctly update metadata when mounting and unmounting
|
||||
* Ticket #804: Move log
|
||||
* Fix ticket #902: .git directories can't be checked out
|
||||
* Lint fixes
|
||||
* Remove unused code
|
||||
* Lint fixes
|
||||
* Lint fixes
|
||||
* Lint fixes
|
||||
* Additional logging message
|
||||
* Lint fix
|
||||
* Fix ticket #907: mknod fails due to path not found
|
||||
* Initial implementation for commit, push, fetch.
|
||||
* Don't fail on empty lines in metadata, just skip them
|
||||
* Add documentation and functionality to progress hook (not used yet)
|
||||
* Pylint fixes
|
||||
* Ticket #908: Remove some unneeded warnings
|
||||
* Fix progress report
|
||||
* Ticket #906: Fix permissions on directories
|
||||
* Make pylint happy
|
||||
* Mount fix
|
||||
* Ticket #808: Initial implementation
|
||||
* Initial forgejo install
|
||||
* Deduplicate key extraction
|
||||
* Fix installer bugs and add documentation
|
||||
* Change user to oggit
|
||||
* Fix NTFS ID modification implementation
|
||||
* Implement system-specific EFI data support
|
||||
* Fix encoding when reading system uuid
|
||||
* Fix and refactor slightly EFI implementation
|
||||
* Add Windows BCD decoding tool
|
||||
* Check module loading and unloading, modprobe works on oglive now
|
||||
* Make EFI deployment more flexible
|
||||
* Add organization API call
|
||||
* Fix bash library path
|
||||
* Fix repo paths for forgejo
|
||||
* Update documentation
|
||||
* Sync to ensure everything is written
|
||||
* Refactoring and more pydoc
|
||||
* Add more documentation
|
||||
* Improve installer documentation
|
||||
* Improve gitlib instructions
|
||||
* Add missing files
|
||||
* Partial setsshkey implementation
|
||||
* Fix SSH key generation and extraction
|
||||
* Initial package contents
|
||||
* Add Debian packaging
|
||||
* Add pylkid
|
||||
* Add pyblkid debian files
|
||||
* Use packaged pyblkid
|
||||
* More detailed API logging
|
||||
* Improve logging
|
||||
* Add oglive key to forgejo
|
||||
* Add original source
|
||||
* Always re-download forgejo, even if installed.
|
||||
* Remove obsolete code that stopped being relevant with Forgejo
|
||||
* Move python modules to /opt/opengnsys-modules
|
||||
* Use absolute paths in initrd modification
|
||||
* Add timestamp to ssh key title, forgejo doesn't like duplicates
|
||||
* Skip past symlinks and problems in oglive modification
|
||||
* Get keys from squashfs instead of initrd to work with current oglive packaging
|
||||
* Fix trivial bug
|
||||
* Move modules to /usr/share/opengnsys
|
||||
* Move packages to /usr/share
|
||||
|
||||
[ Angel Rodriguez ]
|
||||
* Add gitlib/README-en.md
|
||||
* Add api/README-en.md
|
||||
* Add installer/README-en.md
|
||||
|
||||
[ Vadim Troshchinskiy ]
|
||||
* Skip NTFS code on non-Windows
|
||||
* Store and restore GPT partition UUIDs
|
||||
* Update READMEs
|
||||
* BCD constants
|
||||
* Use tqdm
|
||||
* Constants
|
||||
* Add extra mounts update
|
||||
* Better status reports
|
||||
* Make log filename machine-dependent Move kernel args parsing
|
||||
* Make unmounting more robust
|
||||
* Improve repository initialization
|
||||
* Make --pull work like the other commands
|
||||
* Add packages
|
||||
* Update documentation
|
||||
* Ignore python cache
|
||||
* Ignore more files
|
||||
* add python libarchive-c original package
|
||||
* Add pyblkid copyright file
|
||||
* Add make_orig script
|
||||
* Reorder and fix for ogrepository reorganization
|
||||
* Restructure git installer to work without ogboot on the same machine, update docs
|
||||
* Update english documentation
|
||||
* Improve installation process, make it possible to extract keys from oglive
|
||||
* Fix namespaces
|
||||
* Fix ogrepository paths
|
||||
* Change git repo path
|
||||
* Improvements for logging and error handling
|
||||
* Fix HTTP exception handling
|
||||
* Improve task management, cleanup when there are too many
|
||||
* More error logging
|
||||
* Mark git repo as a safe directory
|
||||
* Rework the ability to use a custom SSH key
|
||||
* Log every request
|
||||
* Branch deletion
|
||||
* Make branch deletion RESTful
|
||||
* Initial version of the API server
|
||||
* Add original repo_api
|
||||
* Convert to blueprint
|
||||
* Add port argument
|
||||
* Fix error handling
|
||||
* Add README
|
||||
* Load swagger from disk
|
||||
* Fix repository URL
|
||||
* Bump forgejo version
|
||||
* Add helpful script
|
||||
* Fix port argument
|
||||
* Refactoring for package support
|
||||
* Remove old code
|
||||
* Refactoring for packaging
|
||||
* opengnsys-forgejo package
|
||||
* Fix post-install for forgejo deployment
|
||||
* Fixes for running under gunicorn
|
||||
* Debian packaging
|
||||
* Add branches and tags creation endpoints
|
||||
* Add missing file
|
||||
* Rename service
|
||||
* Add templates
|
||||
* Disable tests
|
||||
* Fix permission problem
|
||||
* Fix ini path
|
||||
* Update changelog
|
||||
* Update changelog
|
||||
* Add package files
|
||||
* Add git image creation script
|
||||
* Slightly improve API for ogrepo usability
|
||||
* First commit
|
||||
* Add installer
|
||||
* Add requirements file
|
||||
|
||||
[ lgromero ]
|
||||
* refs #734 Creates first skeleton of symfony+swagger project
|
||||
|
||||
[ Vadim Troshchinskiy ]
|
||||
* Add Gitlib
|
||||
|
||||
[ lgromero ]
|
||||
* refs #734 Changes OgBootBundle name and adds a first endpoint to test
|
||||
* refs #734 Adds template of repository and branch endpoints
|
||||
|
||||
[ Vadim Troshchinskiy ]
|
||||
* Update docs to account for changes
|
||||
* Trivial API server
|
||||
* Ticket #753: Add repository listing
|
||||
* Ticket #735: List branches in repo
|
||||
* Add testing instructions
|
||||
* Agregar manejo de errrores
|
||||
* Ticket #741: Crear repo Ticket #736: Eliminar repo
|
||||
|
||||
[ lgromero ]
|
||||
* refs #734 Adds README for Api installation
|
||||
* refs #734 Control of errores and http codes in controler
|
||||
* refs #734 Renemas oggitservice
|
||||
|
||||
[ Vadim Troshchinskiy ]
|
||||
* Ticket #738, ticket #739: repo and sync backup protoype
|
||||
|
||||
[ lgromero ]
|
||||
* refs #734 Adds new endpoints sync and backup and status endpoint
|
||||
* refs #734 Adds nelmio api doc configuration
|
||||
* Adds .env file to root
|
||||
* refs #734 use environment variables in .env files and disable web depuration toolbar
|
||||
* refs #734 fix typo in .env and use oggit_url environment variable
|
||||
|
||||
[ Vadim Troshchinskiy ]
|
||||
* Ticket #738, ticket #739: git sync and backup
|
||||
|
||||
[ Nicolas Arenas ]
|
||||
* Add docker container files
|
||||
|
||||
[ Vadim Troshchinskiy ]
|
||||
* Ticket #737: GC
|
||||
* Use Paramiko and Gitpython for backups
|
||||
|
||||
[ Nicolas Arenas ]
|
||||
* Add mock api for testing dockerfile
|
||||
|
||||
[ Vadim Troshchinskiy ]
|
||||
* Ticket #740, listen on all hosts
|
||||
|
||||
[ lgromero ]
|
||||
* refs #734 Removes innecesaries parameters and changes php platform to 8.2
|
||||
* refs #734 just changes name and description in swagger web page
|
||||
|
||||
[ Vadim Troshchinskiy ]
|
||||
* Remove duplicated import
|
||||
* Documentation prototype
|
||||
* Update to 24.04, solves deployment issue
|
||||
* Add more documentation
|
||||
* Add API README
|
||||
* Add API examples
|
||||
* Update list of package requirements in oglive
|
||||
* Fix commandline parsing bug
|
||||
* Revert experimental Windows change
|
||||
* Fix ticket #770: Re-parse filesystems list after mounting
|
||||
* Use oglive server if ogrepository is not set
|
||||
* Ticket #770: Add sanity check
|
||||
* Ticket #771: Correctly create directories on metadata restoration
|
||||
* Ticket #780: Unmount before clone if needed
|
||||
* Fix ticket #800: sudo doesn't work
|
||||
|
||||
[ Vadim Trochinsky ]
|
||||
* Fix ticket #802: .git directory in filesystem root
|
||||
|
||||
[ Vadim Troshchinskiy ]
|
||||
* Fix ticket #805: Remove .git directory if it already exists when checking out
|
||||
* Ticket #770: Correctly update metadata when mounting and unmounting
|
||||
* Ticket #804: Move log
|
||||
* Fix ticket #902: .git directories can't be checked out
|
||||
* Lint fixes
|
||||
* Remove unused code
|
||||
* Lint fixes
|
||||
* Lint fixes
|
||||
* Lint fixes
|
||||
* Additional logging message
|
||||
* Lint fix
|
||||
* Fix ticket #907: mknod fails due to path not found
|
||||
* Initial implementation for commit, push, fetch.
|
||||
* Don't fail on empty lines in metadata, just skip them
|
||||
* Add documentation and functionality to progress hook (not used yet)
|
||||
* Pylint fixes
|
||||
* Ticket #908: Remove some unneeded warnings
|
||||
* Fix progress report
|
||||
* Ticket #906: Fix permissions on directories
|
||||
* Make pylint happy
|
||||
* Mount fix
|
||||
* Ticket #808: Initial implementation
|
||||
* Initial forgejo install
|
||||
* Deduplicate key extraction
|
||||
* Fix installer bugs and add documentation
|
||||
* Change user to oggit
|
||||
* Fix NTFS ID modification implementation
|
||||
* Implement system-specific EFI data support
|
||||
* Fix encoding when reading system uuid
|
||||
* Fix and refactor slightly EFI implementation
|
||||
* Add Windows BCD decoding tool
|
||||
* Check module loading and unloading, modprobe works on oglive now
|
||||
* Make EFI deployment more flexible
|
||||
* Add organization API call
|
||||
* Fix bash library path
|
||||
* Fix repo paths for forgejo
|
||||
* Update documentation
|
||||
* Sync to ensure everything is written
|
||||
* Refactoring and more pydoc
|
||||
* Add more documentation
|
||||
* Improve installer documentation
|
||||
* Improve gitlib instructions
|
||||
* Add missing files
|
||||
* Partial setsshkey implementation
|
||||
* Fix SSH key generation and extraction
|
||||
* Initial package contents
|
||||
* Add Debian packaging
|
||||
* Add pylkid
|
||||
* Add pyblkid debian files
|
||||
* Use packaged pyblkid
|
||||
* More detailed API logging
|
||||
* Improve logging
|
||||
* Add oglive key to forgejo
|
||||
* Add original source
|
||||
* Always re-download forgejo, even if installed.
|
||||
* Remove obsolete code that stopped being relevant with Forgejo
|
||||
* Move python modules to /opt/opengnsys-modules
|
||||
* Use absolute paths in initrd modification
|
||||
* Add timestamp to ssh key title, forgejo doesn't like duplicates
|
||||
* Skip past symlinks and problems in oglive modification
|
||||
* Get keys from squashfs instead of initrd to work with current oglive packaging
|
||||
* Fix trivial bug
|
||||
* Move modules to /usr/share/opengnsys
|
||||
* Move packages to /usr/share
|
||||
|
||||
[ Angel Rodriguez ]
|
||||
* Add gitlib/README-en.md
|
||||
* Add api/README-en.md
|
||||
* Add installer/README-en.md
|
||||
|
||||
[ Vadim Troshchinskiy ]
|
||||
* Skip NTFS code on non-Windows
|
||||
* Store and restore GPT partition UUIDs
|
||||
* Update READMEs
|
||||
* BCD constants
|
||||
* Use tqdm
|
||||
* Constants
|
||||
* Add extra mounts update
|
||||
* Better status reports
|
||||
* Make log filename machine-dependent Move kernel args parsing
|
||||
* Make unmounting more robust
|
||||
* Improve repository initialization
|
||||
* Make --pull work like the other commands
|
||||
* Add packages
|
||||
* Update documentation
|
||||
* Ignore python cache
|
||||
* Ignore more files
|
||||
* add python libarchive-c original package
|
||||
* Add pyblkid copyright file
|
||||
* Add make_orig script
|
||||
* Reorder and fix for ogrepository reorganization
|
||||
* Restructure git installer to work without ogboot on the same machine, update docs
|
||||
* Update english documentation
|
||||
* Improve installation process, make it possible to extract keys from oglive
|
||||
* Fix namespaces
|
||||
* Fix ogrepository paths
|
||||
* Change git repo path
|
||||
* Improvements for logging and error handling
|
||||
* Fix HTTP exception handling
|
||||
* Improve task management, cleanup when there are too many
|
||||
* More error logging
|
||||
* Mark git repo as a safe directory
|
||||
* Rework the ability to use a custom SSH key
|
||||
* Log every request
|
||||
* Branch deletion
|
||||
* Make branch deletion RESTful
|
||||
* Initial version of the API server
|
||||
* Add original repo_api
|
||||
* Convert to blueprint
|
||||
* Add port argument
|
||||
* Fix error handling
|
||||
* Add README
|
||||
* Load swagger from disk
|
||||
* Fix repository URL
|
||||
* Bump forgejo version
|
||||
* Add helpful script
|
||||
* Fix port argument
|
||||
* Refactoring for package support
|
||||
* Remove old code
|
||||
* Refactoring for packaging
|
||||
* opengnsys-forgejo package
|
||||
* Fix post-install for forgejo deployment
|
||||
* Fixes for running under gunicorn
|
||||
* Debian packaging
|
||||
* Add branches and tags creation endpoints
|
||||
* Add missing file
|
||||
* Rename service
|
||||
* Add templates
|
||||
* Disable tests
|
||||
* Fix permission problem
|
||||
* Fix ini path
|
||||
* Update changelog
|
||||
* Update changelog
|
||||
* Add package files
|
||||
* Add git image creation script
|
||||
* Slightly improve API for ogrepo usability
|
||||
* Update changelog
|
||||
* First commit
|
||||
* Add installer
|
||||
* Add requirements file
|
||||
|
||||
[ lgromero ]
|
||||
* refs #734 Creates first skeleton of symfony+swagger project
|
||||
|
||||
[ Vadim Troshchinskiy ]
|
||||
* Add Gitlib
|
||||
|
||||
[ lgromero ]
|
||||
* refs #734 Changes OgBootBundle name and adds a first endpoint to test
|
||||
* refs #734 Adds template of repository and branch endpoints
|
||||
|
||||
[ Vadim Troshchinskiy ]
|
||||
* Update docs to account for changes
|
||||
* Trivial API server
|
||||
* Ticket #753: Add repository listing
|
||||
* Ticket #735: List branches in repo
|
||||
* Add testing instructions
|
||||
* Agregar manejo de errrores
|
||||
* Ticket #741: Crear repo Ticket #736: Eliminar repo
|
||||
|
||||
[ lgromero ]
|
||||
* refs #734 Adds README for Api installation
|
||||
* refs #734 Control of errores and http codes in controler
|
||||
* refs #734 Renemas oggitservice
|
||||
|
||||
[ Vadim Troshchinskiy ]
|
||||
* Ticket #738, ticket #739: repo and sync backup protoype
|
||||
|
||||
[ lgromero ]
|
||||
* refs #734 Adds new endpoints sync and backup and status endpoint
|
||||
* refs #734 Adds nelmio api doc configuration
|
||||
* Adds .env file to root
|
||||
* refs #734 use environment variables in .env files and disable web depuration toolbar
|
||||
* refs #734 fix typo in .env and use oggit_url environment variable
|
||||
|
||||
[ Vadim Troshchinskiy ]
|
||||
* Ticket #738, ticket #739: git sync and backup
|
||||
|
||||
[ Nicolas Arenas ]
|
||||
* Add docker container files
|
||||
|
||||
[ Vadim Troshchinskiy ]
|
||||
* Ticket #737: GC
|
||||
* Use Paramiko and Gitpython for backups
|
||||
|
||||
[ Nicolas Arenas ]
|
||||
* Add mock api for testing dockerfile
|
||||
|
||||
[ Vadim Troshchinskiy ]
|
||||
* Ticket #740, listen on all hosts
|
||||
|
||||
[ lgromero ]
|
||||
* refs #734 Removes innecesaries parameters and changes php platform to 8.2
|
||||
* refs #734 just changes name and description in swagger web page
|
||||
|
||||
[ Vadim Troshchinskiy ]
|
||||
* Remove duplicated import
|
||||
* Documentation prototype
|
||||
* Update to 24.04, solves deployment issue
|
||||
* Add more documentation
|
||||
* Add API README
|
||||
* Add API examples
|
||||
* Update list of package requirements in oglive
|
||||
* Fix commandline parsing bug
|
||||
* Revert experimental Windows change
|
||||
* Fix ticket #770: Re-parse filesystems list after mounting
|
||||
* Use oglive server if ogrepository is not set
|
||||
* Ticket #770: Add sanity check
|
||||
* Ticket #771: Correctly create directories on metadata restoration
|
||||
* Ticket #780: Unmount before clone if needed
|
||||
* Fix ticket #800: sudo doesn't work
|
||||
|
||||
[ Vadim Trochinsky ]
|
||||
* Fix ticket #802: .git directory in filesystem root
|
||||
|
||||
[ Vadim Troshchinskiy ]
|
||||
* Fix ticket #805: Remove .git directory if it already exists when checking out
|
||||
* Ticket #770: Correctly update metadata when mounting and unmounting
|
||||
* Ticket #804: Move log
|
||||
* Fix ticket #902: .git directories can't be checked out
|
||||
* Lint fixes
|
||||
* Remove unused code
|
||||
* Lint fixes
|
||||
* Lint fixes
|
||||
* Lint fixes
|
||||
* Additional logging message
|
||||
* Lint fix
|
||||
* Fix ticket #907: mknod fails due to path not found
|
||||
* Initial implementation for commit, push, fetch.
|
||||
* Don't fail on empty lines in metadata, just skip them
|
||||
* Add documentation and functionality to progress hook (not used yet)
|
||||
* Pylint fixes
|
||||
* Ticket #908: Remove some unneeded warnings
|
||||
* Fix progress report
|
||||
* Ticket #906: Fix permissions on directories
|
||||
* Make pylint happy
|
||||
* Mount fix
|
||||
* Ticket #808: Initial implementation
|
||||
* Initial forgejo install
|
||||
* Deduplicate key extraction
|
||||
* Fix installer bugs and add documentation
|
||||
* Change user to oggit
|
||||
* Fix NTFS ID modification implementation
|
||||
* Implement system-specific EFI data support
|
||||
* Fix encoding when reading system uuid
|
||||
* Fix and refactor slightly EFI implementation
|
||||
* Add Windows BCD decoding tool
|
||||
* Check module loading and unloading, modprobe works on oglive now
|
||||
* Make EFI deployment more flexible
|
||||
* Add organization API call
|
||||
* Fix bash library path
|
||||
* Fix repo paths for forgejo
|
||||
* Update documentation
|
||||
* Sync to ensure everything is written
|
||||
* Refactoring and more pydoc
|
||||
* Add more documentation
|
||||
* Improve installer documentation
|
||||
* Improve gitlib instructions
|
||||
* Add missing files
|
||||
* Partial setsshkey implementation
|
||||
* Fix SSH key generation and extraction
|
||||
* Initial package contents
|
||||
* Add Debian packaging
|
||||
* Add pylkid
|
||||
* Add pyblkid debian files
|
||||
* Use packaged pyblkid
|
||||
* More detailed API logging
|
||||
* Improve logging
|
||||
* Add oglive key to forgejo
|
||||
* Add original source
|
||||
* Always re-download forgejo, even if installed.
|
||||
* Remove obsolete code that stopped being relevant with Forgejo
|
||||
* Move python modules to /opt/opengnsys-modules
|
||||
* Use absolute paths in initrd modification
|
||||
* Add timestamp to ssh key title, forgejo doesn't like duplicates
|
||||
* Skip past symlinks and problems in oglive modification
|
||||
* Get keys from squashfs instead of initrd to work with current oglive packaging
|
||||
* Fix trivial bug
|
||||
* Move modules to /usr/share/opengnsys
|
||||
* Move packages to /usr/share
|
||||
|
||||
[ Angel Rodriguez ]
|
||||
* Add gitlib/README-en.md
|
||||
* Add api/README-en.md
|
||||
* Add installer/README-en.md
|
||||
|
||||
[ Vadim Troshchinskiy ]
|
||||
* Skip NTFS code on non-Windows
|
||||
* Store and restore GPT partition UUIDs
|
||||
* Update READMEs
|
||||
* BCD constants
|
||||
* Use tqdm
|
||||
* Constants
|
||||
* Add extra mounts update
|
||||
* Better status reports
|
||||
* Make log filename machine-dependent Move kernel args parsing
|
||||
* Make unmounting more robust
|
||||
* Improve repository initialization
|
||||
* Make --pull work like the other commands
|
||||
* Add packages
|
||||
* Update documentation
|
||||
* Ignore python cache
|
||||
* Ignore more files
|
||||
* add python libarchive-c original package
|
||||
* Add pyblkid copyright file
|
||||
* Add make_orig script
|
||||
* Reorder and fix for ogrepository reorganization
|
||||
* Restructure git installer to work without ogboot on the same machine, update docs
|
||||
* Update english documentation
|
||||
* Improve installation process, make it possible to extract keys from oglive
|
||||
* Fix namespaces
|
||||
* Fix ogrepository paths
|
||||
* Change git repo path
|
||||
* Improvements for logging and error handling
|
||||
* Fix HTTP exception handling
|
||||
* Improve task management, cleanup when there are too many
|
||||
* More error logging
|
||||
* Mark git repo as a safe directory
|
||||
* Rework the ability to use a custom SSH key
|
||||
* Log every request
|
||||
* Branch deletion
|
||||
* Make branch deletion RESTful
|
||||
* Initial version of the API server
|
||||
* Add original repo_api
|
||||
* Convert to blueprint
|
||||
* Add port argument
|
||||
* Fix error handling
|
||||
* Add README
|
||||
* Load swagger from disk
|
||||
* Fix repository URL
|
||||
* Bump forgejo version
|
||||
* Add helpful script
|
||||
* Fix port argument
|
||||
* Refactoring for package support
|
||||
* Remove old code
|
||||
* Refactoring for packaging
|
||||
* opengnsys-forgejo package
|
||||
* Fix post-install for forgejo deployment
|
||||
* Fixes for running under gunicorn
|
||||
* Debian packaging
|
||||
* Add branches and tags creation endpoints
|
||||
* Add missing file
|
||||
* Rename service
|
||||
* Add templates
|
||||
* Disable tests
|
||||
* Fix permission problem
|
||||
* Fix ini path
|
||||
* Update changelog
|
||||
* Update changelog
|
||||
* Add package files
|
||||
* Add git image creation script
|
||||
* Slightly improve API for ogrepo usability
|
||||
* Update changelog
|
||||
* Update changelog
|
||||
|
||||
-- OpenGnsys <opengnsys@opengnsys.com> Mon, 16 Jun 2025 21:23:34 +0000
|
|
@ -0,0 +1,29 @@
|
|||
Source: opengnsys-gitinstaller
|
||||
Section: unknown
|
||||
Priority: optional
|
||||
Maintainer: OpenGnsys <opengnsys@opengnsys.es>
|
||||
Rules-Requires-Root: no
|
||||
Build-Depends:
|
||||
debhelper-compat (= 13),
|
||||
Standards-Version: 4.6.2
|
||||
Homepage: https://opengnsys.es
|
||||
#Vcs-Browser: https://salsa.debian.org/debian/ogboot
|
||||
#Vcs-Git: https://salsa.debian.org/debian/ogboot.git
|
||||
|
||||
Package: opengnsys-gitinstaller
|
||||
Architecture: any
|
||||
Multi-Arch: foreign
|
||||
Depends:
|
||||
${shlibs:Depends},
|
||||
${misc:Depends},
|
||||
bsdextrautils,
|
||||
debconf (>= 1.5.0),
|
||||
opengnsys-libarchive-c,
|
||||
python3,
|
||||
python3-aniso8601,
|
||||
python3-git,
|
||||
python3-termcolor,
|
||||
python3-tqdm
|
||||
Conflicts:
|
||||
Description: Opengnsys installer library for OgGit
|
||||
Files for OpenGnsys Git support
|
|
@ -0,0 +1,43 @@
|
|||
Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
|
||||
Source: <url://example.com>
|
||||
Upstream-Name: ogboot
|
||||
Upstream-Contact: <preferred name and address to reach the upstream project>
|
||||
|
||||
Files:
|
||||
*
|
||||
Copyright:
|
||||
<years> <put author's name and email here>
|
||||
<years> <likewise for another author>
|
||||
License: GPL-3.0+
|
||||
|
||||
Files:
|
||||
debian/*
|
||||
Copyright:
|
||||
2025 vagrant <vagrant@build>
|
||||
License: GPL-3.0+
|
||||
|
||||
License: GPL-3.0+
|
||||
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 3 of the License, or
|
||||
(at your option) any later version.
|
||||
.
|
||||
This package 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, see <https://www.gnu.org/licenses/>.
|
||||
Comment:
|
||||
On Debian systems, the complete text of the GNU General
|
||||
Public License version 3 can be found in "/usr/share/common-licenses/GPL-3".
|
||||
|
||||
# Please also look if there are files or directories which have a
|
||||
# different copyright/license attached and list them here.
|
||||
# Please avoid picking licenses with terms that are more restrictive than the
|
||||
# packaged work, as it may make Debian's contributions unacceptable upstream.
|
||||
#
|
||||
# If you need, there are some extra license texts available in two places:
|
||||
# /usr/share/debhelper/dh_make/licenses/
|
||||
# /usr/share/common-licenses/
|
|
@ -0,0 +1,2 @@
|
|||
opengnsys-gitinstaller_0.5_amd64.buildinfo unknown optional
|
||||
opengnsys-gitinstaller_0.5_amd64.deb unknown optional
|
|
@ -0,0 +1 @@
|
|||
/opt/opengnsys/ogrepository/oggit/lib
|
|
@ -0,0 +1 @@
|
|||
opengnsys_git_installer.py /opt/opengnsys/ogrepository/oggit/lib
|
|
@ -0,0 +1,2 @@
|
|||
misc:Depends=
|
||||
misc:Pre-Depends=
|
|
@ -0,0 +1,33 @@
|
|||
#!/usr/bin/make -f
|
||||
|
||||
# See debhelper(7) (uncomment to enable).
|
||||
# Output every command that modifies files on the build system.
|
||||
#export DH_VERBOSE = 1
|
||||
|
||||
|
||||
# See FEATURE AREAS in dpkg-buildflags(1).
|
||||
#export DEB_BUILD_MAINT_OPTIONS = hardening=+all
|
||||
|
||||
# See ENVIRONMENT in dpkg-buildflags(1).
|
||||
# Package maintainers to append CFLAGS.
|
||||
#export DEB_CFLAGS_MAINT_APPEND = -Wall -pedantic
|
||||
# Package maintainers to append LDFLAGS.
|
||||
#export DEB_LDFLAGS_MAINT_APPEND = -Wl,--as-needed
|
||||
|
||||
|
||||
%:
|
||||
dh $@
|
||||
|
||||
|
||||
%:
|
||||
dh $@
|
||||
|
||||
# Ejecutar composer install durante la fase de construcción
|
||||
override_dh_auto_build:
|
||||
|
||||
|
||||
# dh_make generated override targets.
|
||||
# This is an example for Cmake (see <https://bugs.debian.org/641051>).
|
||||
#override_dh_auto_configure:
|
||||
# dh_auto_configure -- \
|
||||
# -DCMAKE_LIBRARY_PATH=$(DEB_HOST_MULTIARCH)
|
|
@ -0,0 +1,11 @@
|
|||
[Service]
|
||||
RestartSec=10s
|
||||
Type=simple
|
||||
User={gitapi_user}
|
||||
Group={gitapi_group}
|
||||
WorkingDirectory={gitapi_work_path}
|
||||
ExecStart=/usr/bin/gunicorn -w 4 -b {gitapi_host}:{gitapi_port} gitapi:app
|
||||
Restart=always
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
|
@ -0,0 +1,31 @@
|
|||
#!/bin/bash
|
||||
|
||||
set -e
|
||||
|
||||
if [ ! -f "/etc/apt/sources.list.d/opengnsys.sources" ] ; then
|
||||
|
||||
cat > /etc/apt/sources.list.d/opengnsys.sources <<HERE
|
||||
Types: deb
|
||||
URIs: https://ognproject.evlt.uma.es/debian-opengnsys/opengnsys
|
||||
Suites: noble
|
||||
Components: main
|
||||
Signed-By:
|
||||
-----BEGIN PGP PUBLIC KEY BLOCK-----
|
||||
.
|
||||
mDMEZzx/SxYJKwYBBAHaRw8BAQdAa83CuAJ5/+7Pn9LHT/k34EAGpx5FnT/ExHSj
|
||||
XZG1JES0Ik9wZW5HbnN5cyA8b3Blbmduc3lzQG9wZW5nbnN5cy5lcz6ImQQTFgoA
|
||||
QRYhBC+J38Xsso227ZbDVt2S5xJQRhKDBQJnPH9LAhsDBQkFo5qABQsJCAcCAiIC
|
||||
BhUKCQgLAgQWAgMBAh4HAheAAAoJEN2S5xJQRhKDW/MBAO6swnpwdrbm48ypMyPh
|
||||
NboxvF7rCqBqHWwRHvkvrq7pAP9zd98r7z2AvqVXZxnaCsLTUNMEL12+DVZAUZ1G
|
||||
EquRBbg4BGc8f0sSCisGAQQBl1UBBQEBB0B6D6tkrwXSHi7ebGYsiMPntqwdkQ/S
|
||||
84SFTlSxRqdXfgMBCAeIfgQYFgoAJhYhBC+J38Xsso227ZbDVt2S5xJQRhKDBQJn
|
||||
PH9LAhsMBQkFo5qAAAoJEN2S5xJQRhKDJ+cBAM9jYbeq5VXkHLfODeVztgSXnSUe
|
||||
yklJ18oQmpeK5eWeAQDKYk/P0R+1ZJDItxkeP6pw62bCDYGQDvdDGPMAaIT6CA==
|
||||
=xcNc
|
||||
-----END PGP PUBLIC KEY BLOCK-----
|
||||
HERE
|
||||
fi
|
||||
|
||||
|
||||
apt update
|
||||
apt install -y python3-git opengnsys-libarchive-c python3-termcolor python3-requests python3-tqdm bsdextrautils
|
|
@ -28,13 +28,28 @@ import requests
|
|||
import tempfile
|
||||
import hashlib
|
||||
import datetime
|
||||
import tqdm
|
||||
|
||||
#FORGEJO_VERSION="8.0.3"
|
||||
FORGEJO_VERSION="9.0.0"
|
||||
FORGEJO_VERSION="10.0.3"
|
||||
FORGEJO_URL=f"https://codeberg.org/forgejo/forgejo/releases/download/v{FORGEJO_VERSION}/forgejo-{FORGEJO_VERSION}-linux-amd64"
|
||||
|
||||
|
||||
|
||||
def download_with_progress(url, output_file):
|
||||
|
||||
with requests.get(url, stream=True, timeout=60) as req:
|
||||
progress = tqdm.tqdm()
|
||||
progress.total = int(req.headers["Content-Length"])
|
||||
progress.unit_scale = True
|
||||
progress.desc = "Downloading"
|
||||
|
||||
for chunk in req.iter_content(chunk_size=8192):
|
||||
output_file.write(chunk)
|
||||
progress.n = progress.n + len(chunk)
|
||||
progress.refresh()
|
||||
|
||||
progress.close()
|
||||
|
||||
def show_error(*args):
|
||||
"""
|
||||
|
@ -65,6 +80,23 @@ class RequirementException(Exception):
|
|||
super().__init__(message)
|
||||
self.message = message
|
||||
|
||||
|
||||
class OptionalDependencyException(Exception):
|
||||
"""Excepción que indica que nos falta algún requisito opcional
|
||||
|
||||
Attributes:
|
||||
message (str): Mensaje de error mostrado al usuario
|
||||
"""
|
||||
|
||||
def __init__(self, message):
|
||||
"""Inicializar OptionalDependencyException.
|
||||
|
||||
Args:
|
||||
message (str): Mensaje de error mostrado al usuario
|
||||
"""
|
||||
super().__init__(message)
|
||||
self.message = message
|
||||
|
||||
class FakeTemporaryDirectory:
|
||||
"""Imitación de TemporaryDirectory para depuración"""
|
||||
def __init__(self, dirname):
|
||||
|
@ -74,6 +106,57 @@ class FakeTemporaryDirectory:
|
|||
def __str__(self):
|
||||
return self.name
|
||||
|
||||
|
||||
class OgliveMounter:
|
||||
"""
|
||||
A class to handle mounting of Oglive images from a given URL or local file.
|
||||
|
||||
Attributes:
|
||||
logger (logging.Logger): Logger instance for logging messages.
|
||||
squashfs (str): Path to the squashfs file within the mounted Oglive image.
|
||||
initrd (str): Path to the initrd image within the mounted Oglive image.
|
||||
kernel (str): Path to the kernel image within the mounted Oglive image.
|
||||
|
||||
Methods:
|
||||
__init__(url):
|
||||
Initializes the OgliveMounter instance, downloads the Oglive image if URL is provided,
|
||||
and mounts the image to a temporary directory.
|
||||
|
||||
__del__():
|
||||
Unmounts the mounted directory and cleans up resources.
|
||||
"""
|
||||
def __init__(self, url):
|
||||
self.logger = logging.getLogger("OgliveMounter")
|
||||
self.mountdir = tempfile.TemporaryDirectory()
|
||||
|
||||
self.logger.info("Will mount oglive found at %s", url)
|
||||
|
||||
if url.startswith("http://") or url.startswith("https://"):
|
||||
self.logger.debug("We got an URL, downloading %s", url)
|
||||
self.tempfile = tempfile.NamedTemporaryFile(mode='wb')
|
||||
filename = self.tempfile.name
|
||||
|
||||
download_with_progress(url, self.tempfile)
|
||||
else:
|
||||
self.logger.debug("We got a filename")
|
||||
filename = url
|
||||
|
||||
self.logger.debug("Mounting %s at %s", filename, self.mountdir.name)
|
||||
subprocess.run(["/usr/bin/mount", filename, self.mountdir.name], check=True)
|
||||
|
||||
self.squashfs = os.path.join(self.mountdir.name, "ogclient", "ogclient.sqfs")
|
||||
self.initrd = os.path.join(self.mountdir.name, "ogclient", "oginitrd.img")
|
||||
self.kernel = os.path.join(self.mountdir.name, "ogclient", "ogvmlinuz")
|
||||
|
||||
|
||||
def __del__(self):
|
||||
self.logger.debug("Unmounting directory %s", self.mountdir.name)
|
||||
subprocess.run(["/usr/bin/umount", self.mountdir.name], check=True)
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
class Oglive:
|
||||
"""Interfaz a utilidad oglivecli
|
||||
|
||||
|
@ -88,6 +171,10 @@ class Oglive:
|
|||
|
||||
def _cmd(self, args):
|
||||
cmd = [self.binary] + args
|
||||
|
||||
if not os.path.exists(self.binary):
|
||||
raise OptionalDependencyException("Missing oglivecli command. Please use --squashfs-file (see README.md for more details)")
|
||||
|
||||
self.__logger.debug("comando: %s", cmd)
|
||||
|
||||
proc = subprocess.run(cmd, shell=False, check=True, capture_output=True)
|
||||
|
@ -122,19 +209,46 @@ class OpengnsysGitInstaller:
|
|||
self.__logger.debug("Inicializando")
|
||||
self.testmode = False
|
||||
self.base_path = "/opt/opengnsys"
|
||||
self.ogrepository_base_path = os.path.join(self.base_path, "ogrepository")
|
||||
self.git_basedir = "base.git"
|
||||
self.email = "OpenGnsys@opengnsys.com"
|
||||
|
||||
self.opengnsys_bin_path = os.path.join(self.base_path, "bin")
|
||||
self.opengnsys_etc_path = os.path.join(self.base_path, "etc")
|
||||
|
||||
self.forgejo_user = "oggit"
|
||||
self.forgejo_password = "opengnsys"
|
||||
self.forgejo_organization = "opengnsys"
|
||||
self.forgejo_port = 3000
|
||||
self.forgejo_port = 3100
|
||||
|
||||
self.forgejo_bin_path = os.path.join(self.ogrepository_base_path, "bin")
|
||||
self.forgejo_exe = os.path.join(self.forgejo_bin_path, "forgejo")
|
||||
self.forgejo_conf_dir_path = os.path.join(self.ogrepository_base_path, "etc", "forgejo")
|
||||
|
||||
self.lfs_dir_path = os.path.join(self.ogrepository_base_path, "oggit", "git-lfs")
|
||||
self.git_dir_path = os.path.join(self.ogrepository_base_path, "oggit", "git")
|
||||
|
||||
self.forgejo_var_dir_path = os.path.join(self.ogrepository_base_path, "var", "lib", "forgejo")
|
||||
self.forgejo_work_dir_path = os.path.join(self.forgejo_var_dir_path, "work")
|
||||
self.forgejo_work_custom_dir_path = os.path.join(self.forgejo_work_dir_path, "custom")
|
||||
self.forgejo_db_dir_path = os.path.join(self.forgejo_var_dir_path, "db")
|
||||
self.forgejo_data_dir_path = os.path.join(self.forgejo_var_dir_path, "data")
|
||||
|
||||
self.forgejo_db_path = os.path.join(self.forgejo_db_dir_path, "forgejo.db")
|
||||
|
||||
self.forgejo_log_dir_path = os.path.join(self.ogrepository_base_path, "log", "forgejo")
|
||||
|
||||
|
||||
self.dependencies = ["git", "python3-flask", "python3-flasgger", "gunicorn", ]
|
||||
|
||||
self.set_ssh_user_group("oggit", "oggit")
|
||||
|
||||
self.temp_dir = None
|
||||
self.script_path = os.path.realpath(os.path.dirname(__file__))
|
||||
|
||||
# Where we look for forgejo-app.ini and similar templates.
|
||||
self.template_path = self.script_path
|
||||
|
||||
# Possible names for SSH public keys
|
||||
self.ssh_key_users = ["root", "opengnsys"]
|
||||
self.key_names = ["id_rsa.pub", "id_ed25519.pub", "id_ecdsa.pub", "id_ed25519_sk.pub", "id_ecdsa_sk.pub"]
|
||||
|
@ -147,10 +261,14 @@ class OpengnsysGitInstaller:
|
|||
for kp in self.key_paths:
|
||||
self.key_paths_dict[kp] = 1
|
||||
|
||||
os.environ["PATH"] += os.pathsep + os.path.join(self.base_path, "bin")
|
||||
|
||||
self.oglive = Oglive()
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
def set_testmode(self, value):
|
||||
"""Establece el modo de prueba"""
|
||||
self.testmode = value
|
||||
|
@ -159,10 +277,6 @@ class OpengnsysGitInstaller:
|
|||
"""Ignorar requisito de clave de ssh para el instalador"""
|
||||
self.ignoresshkey = value
|
||||
|
||||
def set_usesshkey(self, value):
|
||||
"""Usar clave de ssh especificada"""
|
||||
self.usesshkey = value
|
||||
|
||||
def set_basepath(self, value):
|
||||
"""Establece ruta base de OpenGnsys
|
||||
Valor por defecto: /opt/opengnsys
|
||||
|
@ -218,7 +332,7 @@ class OpengnsysGitInstaller:
|
|||
def init_git_repo(self, reponame):
|
||||
"""Inicializa un repositorio Git"""
|
||||
# Creamos repositorio
|
||||
ogdir_images = os.path.join(self.base_path, "images")
|
||||
ogdir_images = os.path.join(self.ogrepository_base_path, "oggit")
|
||||
self.__logger.info("Creando repositorio de GIT %s", reponame)
|
||||
|
||||
os.makedirs(os.path.join(ogdir_images, self.git_basedir), exist_ok=True)
|
||||
|
@ -294,42 +408,60 @@ class OpengnsysGitInstaller:
|
|||
raise TimeoutError("Timed out waiting for connection!")
|
||||
|
||||
|
||||
def add_ssh_key_from_squashfs(self, oglive_num = None):
|
||||
def add_ssh_key_from_squashfs(self, oglive_num = None, squashfs_file = None, oglive_file = None):
|
||||
|
||||
name = "(unknown)"
|
||||
mounter = None
|
||||
|
||||
if not oglive_file is None:
|
||||
mounter = OgliveMounter(oglive_file)
|
||||
squashfs_file = mounter.squashfs
|
||||
|
||||
if squashfs_file is None:
|
||||
if oglive_num is None:
|
||||
self.__logger.info("Using default oglive")
|
||||
oglive_num = self.oglive.get_default()
|
||||
else:
|
||||
self.__logger.info("Using oglive %i", oglive_num)
|
||||
|
||||
name = self.oglive.get_clients()[str(oglive_num)]
|
||||
|
||||
if oglive_num is None:
|
||||
self.__logger.info("Using default oglive")
|
||||
oglive_num = int(self.oglive.get_default())
|
||||
else:
|
||||
self.__logger.info("Using oglive %i", oglive_num)
|
||||
self.__logger.info("Using specified squashfs file %s", squashfs_file)
|
||||
name = os.path.basename(squashfs_file)
|
||||
|
||||
oglive_client = self.oglive.get_clients()[str(oglive_num)]
|
||||
self.__logger.info("Oglive is %s", oglive_client)
|
||||
|
||||
keys = installer.extract_ssh_keys(oglive_num = oglive_num)
|
||||
keys = self.extract_ssh_keys_from_squashfs(oglive_num = oglive_num, squashfs_file=squashfs_file)
|
||||
retvals = []
|
||||
for k in keys:
|
||||
timestamp = '{:%Y-%m-%d %H:%M:%S}'.format(datetime.datetime.now())
|
||||
installer.add_forgejo_sshkey(k, f"Key for {oglive_client} ({timestamp})")
|
||||
retvals = retvals + [self.add_forgejo_sshkey(k, f"Key for {name} ({timestamp})")]
|
||||
|
||||
return retvals
|
||||
|
||||
|
||||
|
||||
def extract_ssh_keys(self, oglive_num = None):
|
||||
def extract_ssh_keys_from_squashfs(self, oglive_num = None, squashfs_file = None):
|
||||
public_keys = []
|
||||
|
||||
|
||||
squashfs = "ogclient.sqfs"
|
||||
|
||||
tftp_dir = os.path.join(self.base_path, "tftpboot")
|
||||
if squashfs_file is None:
|
||||
tftp_dir = os.path.join(self.base_path, "tftpboot")
|
||||
|
||||
if oglive_num is None:
|
||||
self.__logger.info("Reading from default oglive")
|
||||
oglive_num = self.oglive.get_default()
|
||||
if oglive_num is None:
|
||||
self.__logger.info("Reading from default oglive")
|
||||
oglive_num = self.oglive.get_default()
|
||||
else:
|
||||
self.__logger.info("Reading from oglive %i", oglive_num)
|
||||
|
||||
oglive_client = self.oglive.get_clients()[str(oglive_num)]
|
||||
self.__logger.info("Oglive is %s", oglive_client)
|
||||
|
||||
client_squashfs_path = os.path.join(tftp_dir, oglive_client, squashfs)
|
||||
else:
|
||||
self.__logger.info("Reading from oglive %i", oglive_num)
|
||||
|
||||
oglive_client = self.oglive.get_clients()[str(oglive_num)]
|
||||
self.__logger.info("Oglive is %s", oglive_client)
|
||||
|
||||
client_squashfs_path = os.path.join(tftp_dir, oglive_client, squashfs)
|
||||
self.__logger.info("Using specified squashfs file %s", squashfs_file)
|
||||
client_squashfs_path = squashfs_file
|
||||
|
||||
self.__logger.info("Mounting %s", client_squashfs_path)
|
||||
mount_tempdir = tempfile.TemporaryDirectory()
|
||||
|
@ -352,49 +484,75 @@ class OpengnsysGitInstaller:
|
|||
return public_keys
|
||||
|
||||
|
||||
def _extract_ssh_key_from_initrd(self):
|
||||
def extract_ssh_key_from_initrd(self, oglive_number = None, initrd_file = None):
|
||||
public_key=""
|
||||
|
||||
INITRD = "oginitrd.img"
|
||||
|
||||
tftp_dir = os.path.join(self.base_path, "tftpboot")
|
||||
default_num = self.oglive.get_default()
|
||||
default_client = self.oglive.get_clients()[default_num]
|
||||
client_initrd_path = os.path.join(tftp_dir, default_client, INITRD)
|
||||
self.__logger.debug("Extracting ssh key from initrd")
|
||||
|
||||
#self.temp_dir = self._get_tempdir()
|
||||
if initrd_file is None:
|
||||
self.__logger.debug("Looking for initrd file")
|
||||
tftp_dir = os.path.join(self.base_path, "tftpboot")
|
||||
if oglive_number is None:
|
||||
oglive_number = self.oglive.get_default()
|
||||
|
||||
if self.usesshkey:
|
||||
with open(self.usesshkey, 'r') as f:
|
||||
public_key = f.read().strip()
|
||||
oglive_client = self.oglive.get_clients()[oglive_number]
|
||||
client_initrd_path = os.path.join(tftp_dir, oglive_client, INITRD)
|
||||
|
||||
self.__logger.debug("Found at %s", client_initrd_path)
|
||||
else:
|
||||
if os.path.isfile(client_initrd_path):
|
||||
#os.makedirs(temp_dir, exist_ok=True)
|
||||
#os.chdir(self.temp_dir.name)
|
||||
self.__logger.debug("Descomprimiendo %s", client_initrd_path)
|
||||
public_key = None
|
||||
with libarchive.file_reader(client_initrd_path) as initrd:
|
||||
for file in initrd:
|
||||
self.__logger.debug("Archivo: %s", file)
|
||||
self.__logger.debug("Using provided initrd file %s", initrd_file)
|
||||
client_initrd_path = initrd_file
|
||||
|
||||
pathname = file.pathname;
|
||||
if pathname.startswith("./"):
|
||||
pathname = pathname[2:]
|
||||
self.__logger.debug("Extracting key from %s", client_initrd_path)
|
||||
|
||||
if pathname in self.key_paths_dict:
|
||||
data = bytearray()
|
||||
for block in file.get_blocks():
|
||||
data = data + block
|
||||
public_key = data.decode('utf-8').strip()
|
||||
if os.path.isfile(client_initrd_path):
|
||||
#os.makedirs(temp_dir, exist_ok=True)
|
||||
#os.chdir(self.temp_dir.name)
|
||||
self.__logger.debug("Uncompressing %s", client_initrd_path)
|
||||
public_key = None
|
||||
with libarchive.file_reader(client_initrd_path) as initrd:
|
||||
for file in initrd:
|
||||
self.__logger.debug("File: %s", file)
|
||||
|
||||
break
|
||||
else:
|
||||
print(f"No se encuentra la imagen de initrd {client_initrd_path}")
|
||||
exit(2)
|
||||
pathname = file.pathname;
|
||||
if pathname.startswith("./"):
|
||||
pathname = pathname[2:]
|
||||
|
||||
if pathname in self.key_paths_dict:
|
||||
self.__logger.info("Found key %s, extracting", pathname)
|
||||
|
||||
data = bytearray()
|
||||
for block in file.get_blocks():
|
||||
data = data + block
|
||||
public_key = data.decode('utf-8').strip()
|
||||
|
||||
break
|
||||
else:
|
||||
print(f"Failed to find initrd at {client_initrd_path}")
|
||||
exit(2)
|
||||
|
||||
if not public_key:
|
||||
self.__logger.warning("Failed to find a SSH key")
|
||||
|
||||
return public_key
|
||||
|
||||
def get_image_paths(self, oglive_num = None):
|
||||
squashfs = "ogclient.sqfs"
|
||||
|
||||
if oglive_num is None:
|
||||
self.__logger.info("Will modify default client")
|
||||
oglive_num = self.oglive.get_default()
|
||||
|
||||
tftp_dir = os.path.join(self.base_path, "tftpboot")
|
||||
oglive_client = self.oglive.get_clients()[str(oglive_num)]
|
||||
|
||||
client_squashfs_path = os.path.join(tftp_dir, oglive_client, squashfs)
|
||||
|
||||
self.__logger.info("Squashfs: %s", client_squashfs_path)
|
||||
|
||||
|
||||
def set_ssh_key_in_initrd(self, client_num = None):
|
||||
INITRD = "oginitrd.img"
|
||||
|
||||
|
@ -534,7 +692,25 @@ class OpengnsysGitInstaller:
|
|||
|
||||
self.add_forgejo_sshkey(oglive_public_key, f"Key for {ogclient} ({timestamp})")
|
||||
|
||||
def install(self):
|
||||
|
||||
def verify_requirements(self):
|
||||
self.__logger.info("verify_requirements()")
|
||||
|
||||
# Control básico de errores.
|
||||
self.__logger.debug("Comprobando euid")
|
||||
if os.geteuid() != 0:
|
||||
raise RequirementException("Sólo ejecutable por root")
|
||||
|
||||
if not os.path.exists("/etc/debian_version"):
|
||||
raise RequirementException("Instalación sólo soportada en Debian y Ubuntu")
|
||||
|
||||
|
||||
MIN_PYTHON = (3, 8)
|
||||
if sys.version_info < MIN_PYTHON:
|
||||
raise RequirementException(f"Python %s.%s mínimo requerido.\n" % MIN_PYTHON)
|
||||
|
||||
|
||||
def install_dependencies(self):
|
||||
"""Instalar
|
||||
|
||||
Ejecuta todo el proceso de instalación incluyendo:
|
||||
|
@ -551,32 +727,11 @@ class OpengnsysGitInstaller:
|
|||
"""
|
||||
self.__logger.info("install()")
|
||||
|
||||
ogdir_images = os.path.join(self.base_path, "images")
|
||||
ENGINECFG = os.path.join(self.base_path, "client/etc/engine.cfg")
|
||||
|
||||
os.environ["PATH"] += os.pathsep + os.path.join(self.base_path, "bin")
|
||||
tftp_dir = os.path.join(self.base_path, "tftpboot")
|
||||
INITRD = "oginitrd.img"
|
||||
self.temp_dir = self._get_tempdir()
|
||||
SSHUSER = "opengnsys"
|
||||
self.verify_requirements()
|
||||
|
||||
|
||||
# Control básico de errores.
|
||||
self.__logger.debug("Comprobando euid")
|
||||
if os.geteuid() != 0:
|
||||
raise RequirementException("Sólo ejecutable por root")
|
||||
|
||||
if not os.path.exists("/etc/debian_version"):
|
||||
raise RequirementException("Instalación sólo soportada en Debian y Ubuntu")
|
||||
|
||||
|
||||
MIN_PYTHON = (3, 8)
|
||||
if sys.version_info < MIN_PYTHON:
|
||||
raise RequirementException(f"Python %s.%s mínimo requerido.\n" % MIN_PYTHON)
|
||||
|
||||
|
||||
self.__logger.debug("Instalando dependencias")
|
||||
subprocess.run(["apt-get", "install", "-y", "git"], check=True)
|
||||
self.__logger.debug("Installing dependencies")
|
||||
subprocess.run(["apt-get", "install", "-y"] + self.dependencies, check=True)
|
||||
|
||||
def _install_template(self, template, destination, keysvalues):
|
||||
|
||||
|
@ -587,7 +742,10 @@ class OpengnsysGitInstaller:
|
|||
data = template_file.read()
|
||||
|
||||
for key in keysvalues.keys():
|
||||
data = data.replace("{" + key + "}", keysvalues[key])
|
||||
if isinstance(keysvalues[key], int):
|
||||
data = data.replace("{" + key + "}", str(keysvalues[key]))
|
||||
else:
|
||||
data = data.replace("{" + key + "}", keysvalues[key])
|
||||
|
||||
with open(destination, "w+", encoding="utf-8") as out_file:
|
||||
out_file.write(data)
|
||||
|
@ -598,88 +756,112 @@ class OpengnsysGitInstaller:
|
|||
ret = subprocess.run(cmd, check=True,capture_output=True, encoding='utf-8')
|
||||
return ret.stdout.strip()
|
||||
|
||||
def install_forgejo(self):
|
||||
self.__logger.info("Installing Forgejo")
|
||||
def install_api(self):
|
||||
self.__logger.info("Installing Git API")
|
||||
|
||||
opengnsys_bin_path = os.path.join(self.base_path, "bin")
|
||||
opengnsys_etc_path = os.path.join(self.base_path, "etc")
|
||||
|
||||
pathlib.Path(opengnsys_bin_path).mkdir(parents=True, exist_ok=True)
|
||||
|
||||
|
||||
data = {
|
||||
"gitapi_user" : "opengnsys",
|
||||
"gitapi_group" : "opengnsys",
|
||||
"gitapi_host" : "0.0.0.0",
|
||||
"gitapi_port" : 8087,
|
||||
"gitapi_work_path" : opengnsys_bin_path
|
||||
}
|
||||
|
||||
shutil.copy("../api/gitapi.py", opengnsys_bin_path + "/gitapi.py")
|
||||
shutil.copy("opengnsys_git_installer.py", opengnsys_bin_path + "/opengnsys_git_installer.py")
|
||||
|
||||
self._install_template(os.path.join(self.template_path, "gitapi.service"), "/etc/systemd/system/gitapi.service", data)
|
||||
|
||||
|
||||
|
||||
|
||||
bin_path = os.path.join(self.base_path, "bin", "forgejo")
|
||||
conf_dir_path = os.path.join(self.base_path, "etc", "forgejo")
|
||||
self.__logger.debug("Reloading systemd and starting service")
|
||||
subprocess.run(["systemctl", "daemon-reload"], check=True)
|
||||
subprocess.run(["systemctl", "enable", "gitapi"], check=True)
|
||||
subprocess.run(["systemctl", "restart", "gitapi"], check=True)
|
||||
|
||||
|
||||
lfs_dir_path = os.path.join(self.base_path, "images", "git-lfs")
|
||||
git_dir_path = os.path.join(self.base_path, "images", "git")
|
||||
def _get_forgejo_data(self):
|
||||
conf_path = os.path.join(self.forgejo_conf_dir_path, "app.ini")
|
||||
|
||||
forgejo_work_dir_path = os.path.join(self.base_path, "var", "lib", "forgejo/work")
|
||||
forgejo_db_dir_path = os.path.join(self.base_path, "var", "lib", "forgejo/db")
|
||||
forgejo_data_dir_path = os.path.join(self.base_path, "var", "lib", "forgejo/data")
|
||||
data = {
|
||||
"forgejo_user" : self.ssh_user,
|
||||
"forgejo_group" : self.ssh_group,
|
||||
"forgejo_port" : str(self.forgejo_port),
|
||||
"forgejo_bin" : self.forgejo_exe,
|
||||
"forgejo_app_ini" : conf_path,
|
||||
"forgejo_work_path" : self.forgejo_work_dir_path,
|
||||
"forgejo_data_path" : self.forgejo_data_dir_path,
|
||||
"forgejo_db_path" : self.forgejo_db_path,
|
||||
"forgejo_repository_root" : self.git_dir_path,
|
||||
"forgejo_lfs_path" : self.lfs_dir_path,
|
||||
"forgejo_log_path" : self.forgejo_log_dir_path,
|
||||
"forgejo_hostname" : self._runcmd("hostname"),
|
||||
"forgejo_lfs_jwt_secret" : self._runcmd([self.forgejo_exe,"generate", "secret", "LFS_JWT_SECRET"]),
|
||||
"forgejo_jwt_secret" : self._runcmd([self.forgejo_exe,"generate", "secret", "JWT_SECRET"]),
|
||||
"forgejo_internal_token" : self._runcmd([self.forgejo_exe,"generate", "secret", "INTERNAL_TOKEN"]),
|
||||
"forgejo_secret_key" : self._runcmd([self.forgejo_exe,"generate", "secret", "SECRET_KEY"])
|
||||
}
|
||||
|
||||
forgejo_db_path = os.path.join(forgejo_db_dir_path, "forgejo.db")
|
||||
return data
|
||||
|
||||
forgejo_log_dir_path = os.path.join(self.base_path, "log", "forgejo")
|
||||
def install_forgejo(self, download=True):
|
||||
self.__logger.info("Installing Forgejo version %s", FORGEJO_VERSION)
|
||||
|
||||
conf_path = os.path.join(self.forgejo_conf_dir_path, "app.ini")
|
||||
|
||||
conf_path = os.path.join(conf_dir_path, "app.ini")
|
||||
self.__logger.info("Stopping opengnsys-forgejo service. This may cause a harmless warning.")
|
||||
|
||||
self.__logger.debug("Stopping opengnsys-forgejo service")
|
||||
subprocess.run(["systemctl", "stop", "opengnsys-forgejo"], check=False)
|
||||
subprocess.run(["/usr/bin/systemctl", "stop", "opengnsys-forgejo"], check=False)
|
||||
|
||||
self.__logger.debug("Downloading from %s into %s", FORGEJO_URL, bin_path)
|
||||
urllib.request.urlretrieve(FORGEJO_URL, bin_path)
|
||||
os.chmod(bin_path, 0o755)
|
||||
self.__logger.debug("Downloading from %s into %s", FORGEJO_URL, self.forgejo_exe)
|
||||
pathlib.Path(self.forgejo_bin_path).mkdir(parents=True, exist_ok=True)
|
||||
|
||||
if os.path.exists(forgejo_db_path):
|
||||
with open(self.forgejo_exe, "wb") as forgejo_bin:
|
||||
download_with_progress(FORGEJO_URL, forgejo_bin)
|
||||
|
||||
os.chmod(self.forgejo_exe, 0o755)
|
||||
|
||||
if os.path.exists(self.forgejo_db_path):
|
||||
self.__logger.debug("Removing old configuration")
|
||||
os.unlink(forgejo_db_path)
|
||||
os.unlink(self.forgejo_db_path)
|
||||
else:
|
||||
self.__logger.debug("Old configuration not present, ok.")
|
||||
|
||||
self.__logger.debug("Wiping old data")
|
||||
for dir in [conf_dir_path, git_dir_path, lfs_dir_path, forgejo_work_dir_path, forgejo_data_dir_path, forgejo_db_dir_path]:
|
||||
for dir in [self.forgejo_conf_dir_path, self.git_dir_path, self.lfs_dir_path, self.forgejo_work_dir_path, self.forgejo_data_dir_path, self.forgejo_db_dir_path]:
|
||||
if os.path.exists(dir):
|
||||
self.__logger.debug("Removing %s", dir)
|
||||
shutil.rmtree(dir)
|
||||
|
||||
self.__logger.debug("Creating directories")
|
||||
|
||||
pathlib.Path(conf_dir_path).mkdir(parents=True, exist_ok=True)
|
||||
pathlib.Path(git_dir_path).mkdir(parents=True, exist_ok=True)
|
||||
pathlib.Path(lfs_dir_path).mkdir(parents=True, exist_ok=True)
|
||||
pathlib.Path(forgejo_work_dir_path).mkdir(parents=True, exist_ok=True)
|
||||
pathlib.Path(forgejo_data_dir_path).mkdir(parents=True, exist_ok=True)
|
||||
pathlib.Path(forgejo_db_dir_path).mkdir(parents=True, exist_ok=True)
|
||||
pathlib.Path(forgejo_log_dir_path).mkdir(parents=True, exist_ok=True)
|
||||
pathlib.Path(self.opengnsys_etc_path).mkdir(parents=True, exist_ok=True)
|
||||
pathlib.Path(self.forgejo_conf_dir_path).mkdir(parents=True, exist_ok=True)
|
||||
pathlib.Path(self.git_dir_path).mkdir(parents=True, exist_ok=True)
|
||||
pathlib.Path(self.lfs_dir_path).mkdir(parents=True, exist_ok=True)
|
||||
pathlib.Path(self.forgejo_work_dir_path).mkdir(parents=True, exist_ok=True)
|
||||
pathlib.Path(self.forgejo_data_dir_path).mkdir(parents=True, exist_ok=True)
|
||||
pathlib.Path(self.forgejo_db_dir_path).mkdir(parents=True, exist_ok=True)
|
||||
pathlib.Path(self.forgejo_log_dir_path).mkdir(parents=True, exist_ok=True)
|
||||
|
||||
|
||||
os.chown(lfs_dir_path, self.ssh_uid, self.ssh_gid)
|
||||
os.chown(git_dir_path, self.ssh_uid, self.ssh_gid)
|
||||
os.chown(forgejo_data_dir_path, self.ssh_uid, self.ssh_gid)
|
||||
os.chown(forgejo_work_dir_path, self.ssh_uid, self.ssh_gid)
|
||||
os.chown(forgejo_db_dir_path, self.ssh_uid, self.ssh_gid)
|
||||
os.chown(forgejo_log_dir_path, self.ssh_uid, self.ssh_gid)
|
||||
os.chown(self.lfs_dir_path, self.ssh_uid, self.ssh_gid)
|
||||
os.chown(self.git_dir_path, self.ssh_uid, self.ssh_gid)
|
||||
os.chown(self.forgejo_data_dir_path, self.ssh_uid, self.ssh_gid)
|
||||
os.chown(self.forgejo_work_dir_path, self.ssh_uid, self.ssh_gid)
|
||||
os.chown(self.forgejo_db_dir_path, self.ssh_uid, self.ssh_gid)
|
||||
os.chown(self.forgejo_log_dir_path, self.ssh_uid, self.ssh_gid)
|
||||
|
||||
data = {
|
||||
"forgejo_user" : self.ssh_user,
|
||||
"forgejo_group" : self.ssh_group,
|
||||
"forgejo_port" : str(self.forgejo_port),
|
||||
"forgejo_bin" : bin_path,
|
||||
"forgejo_app_ini" : conf_path,
|
||||
"forgejo_work_path" : forgejo_work_dir_path,
|
||||
"forgejo_data_path" : forgejo_data_dir_path,
|
||||
"forgejo_db_path" : forgejo_db_path,
|
||||
"forgejo_repository_root" : git_dir_path,
|
||||
"forgejo_lfs_path" : lfs_dir_path,
|
||||
"forgejo_log_path" : forgejo_log_dir_path,
|
||||
"forgejo_hostname" : self._runcmd("hostname"),
|
||||
"forgejo_lfs_jwt_secret" : self._runcmd([bin_path,"generate", "secret", "LFS_JWT_SECRET"]),
|
||||
"forgejo_jwt_secret" : self._runcmd([bin_path,"generate", "secret", "JWT_SECRET"]),
|
||||
"forgejo_internal_token" : self._runcmd([bin_path,"generate", "secret", "INTERNAL_TOKEN"]),
|
||||
"forgejo_secret_key" : self._runcmd([bin_path,"generate", "secret", "SECRET_KEY"])
|
||||
}
|
||||
data = self._get_forgejo_data()
|
||||
|
||||
self._install_template(os.path.join(self.script_path, "forgejo-app.ini"), conf_path, data)
|
||||
self._install_template(os.path.join(self.script_path, "forgejo.service"), "/etc/systemd/system/opengnsys-forgejo.service", data)
|
||||
self._install_template(os.path.join(self.template_path, "forgejo-app.ini"), conf_path, data)
|
||||
self._install_template(os.path.join(self.template_path, "opengnsys-forgejo.service"), "/etc/systemd/system/opengnsys-forgejo.service", data)
|
||||
|
||||
|
||||
self.__logger.debug("Reloading systemd and starting service")
|
||||
|
@ -694,7 +876,7 @@ class OpengnsysGitInstaller:
|
|||
self.__logger.info("Configuring forgejo")
|
||||
|
||||
def run_forge_cmd(args):
|
||||
cmd = [bin_path, "--config", conf_path] + args
|
||||
cmd = [self.forgejo_exe, "--config", conf_path] + args
|
||||
self.__logger.debug("Running command: %s", cmd)
|
||||
|
||||
ret = subprocess.run(cmd, check=False, capture_output=True, encoding='utf-8', user=self.ssh_user)
|
||||
|
@ -715,10 +897,80 @@ class OpengnsysGitInstaller:
|
|||
with open(os.path.join(self.base_path, "etc", "ogGitApiToken.cfg"), "w+", encoding='utf-8') as token_file:
|
||||
token_file.write(token)
|
||||
|
||||
def configure_forgejo(self):
|
||||
data = self._get_forgejo_data()
|
||||
self.__logger.debug("Creating directories")
|
||||
|
||||
ssh_key = self._extract_ssh_key_from_initrd()
|
||||
pathlib.Path(self.opengnsys_etc_path).mkdir(parents=True, exist_ok=True)
|
||||
pathlib.Path(self.forgejo_conf_dir_path).mkdir(parents=True, exist_ok=True)
|
||||
pathlib.Path(self.git_dir_path).mkdir(parents=True, exist_ok=True)
|
||||
pathlib.Path(self.lfs_dir_path).mkdir(parents=True, exist_ok=True)
|
||||
pathlib.Path(self.forgejo_work_dir_path).mkdir(parents=True, exist_ok=True)
|
||||
pathlib.Path(self.forgejo_work_custom_dir_path).mkdir(parents=True, exist_ok=True)
|
||||
pathlib.Path(self.forgejo_data_dir_path).mkdir(parents=True, exist_ok=True)
|
||||
pathlib.Path(self.forgejo_db_dir_path).mkdir(parents=True, exist_ok=True)
|
||||
pathlib.Path(self.forgejo_log_dir_path).mkdir(parents=True, exist_ok=True)
|
||||
|
||||
self.add_forgejo_sshkey(ssh_key, "Default key")
|
||||
|
||||
os.chown(self.lfs_dir_path, self.ssh_uid, self.ssh_gid)
|
||||
os.chown(self.git_dir_path, self.ssh_uid, self.ssh_gid)
|
||||
os.chown(self.forgejo_data_dir_path, self.ssh_uid, self.ssh_gid)
|
||||
os.chown(self.forgejo_work_dir_path, self.ssh_uid, self.ssh_gid)
|
||||
os.chown(self.forgejo_db_dir_path, self.ssh_uid, self.ssh_gid)
|
||||
os.chown(self.forgejo_log_dir_path, self.ssh_uid, self.ssh_gid)
|
||||
|
||||
|
||||
|
||||
conf_path = os.path.join(self.forgejo_conf_dir_path, "app.ini")
|
||||
self._install_template(os.path.join(self.template_path, "forgejo-app.ini"), conf_path, data)
|
||||
self._install_template(os.path.join(self.template_path, "opengnsys-forgejo.service"), "/etc/systemd/system/opengnsys-forgejo.service", data)
|
||||
|
||||
|
||||
|
||||
self.__logger.debug("Reloading systemd and starting service")
|
||||
subprocess.run(["systemctl", "daemon-reload"], check=True)
|
||||
subprocess.run(["systemctl", "enable", "opengnsys-forgejo"], check=True)
|
||||
|
||||
subprocess.run(["systemctl", "restart", "opengnsys-forgejo"], check=True)
|
||||
|
||||
self.__logger.info("Waiting for forgejo to start")
|
||||
self._wait_for_port("localhost", self.forgejo_port)
|
||||
|
||||
|
||||
self.__logger.info("Configuring forgejo")
|
||||
|
||||
def run_forge_cmd(args, ignore_errors = []):
|
||||
cmd = [self.forgejo_exe, "--config", conf_path] + args
|
||||
self.__logger.info("Running command: %s", cmd)
|
||||
|
||||
ret = subprocess.run(cmd, check=False, capture_output=True, encoding='utf-8', user=self.ssh_user)
|
||||
if ret.returncode == 0:
|
||||
return ret.stdout.strip()
|
||||
else:
|
||||
self.__logger.error("Failed to run command: %s, return code %i", cmd, ret.returncode)
|
||||
self.__logger.error("stdout: %s", ret.stdout.strip())
|
||||
self.__logger.error("stderr: %s", ret.stderr.strip())
|
||||
|
||||
for err in ignore_errors:
|
||||
if err in ret.stderr:
|
||||
self.__logger.info("Ignoring error, it's in the ignore list")
|
||||
return ret.stdout.strip()
|
||||
|
||||
raise RuntimeError("Failed to run necessary command")
|
||||
|
||||
run_forge_cmd(["migrate"])
|
||||
|
||||
run_forge_cmd(["admin", "doctor", "check"])
|
||||
|
||||
run_forge_cmd(["admin", "user", "create", "--username", self.forgejo_user, "--password", self.forgejo_password, "--email", self.email], ignore_errors=["user already exists"])
|
||||
|
||||
token = run_forge_cmd(["admin", "user", "generate-access-token", "--username", self.forgejo_user, "-t", "gitapi", "--scopes", "all", "--raw"], ignore_errors = ["access token name has been used already"])
|
||||
|
||||
if token:
|
||||
with open(os.path.join(self.base_path, "etc", "ogGitApiToken.cfg"), "w+", encoding='utf-8') as token_file:
|
||||
token_file.write(token)
|
||||
else:
|
||||
self.__logger.info("Keeping the old token")
|
||||
|
||||
|
||||
def add_forgejo_repo(self, repository_name, description = ""):
|
||||
|
@ -764,6 +1016,7 @@ class OpengnsysGitInstaller:
|
|||
)
|
||||
|
||||
self.__logger.info("Request status was %i, content %s", r.status_code, r.content)
|
||||
return r.status_code, r.content.decode('utf-8')
|
||||
|
||||
def add_forgejo_organization(self, pubkey, description = ""):
|
||||
token = ""
|
||||
|
@ -799,8 +1052,7 @@ if __name__ == '__main__':
|
|||
streamLog = logging.StreamHandler()
|
||||
streamLog.setLevel(logging.INFO)
|
||||
|
||||
if not os.path.exists(opengnsys_log_dir):
|
||||
os.mkdir(opengnsys_log_dir)
|
||||
pathlib.Path(opengnsys_log_dir).mkdir(parents=True, exist_ok=True)
|
||||
|
||||
logFilePath = f"{opengnsys_log_dir}/git_installer.log"
|
||||
fileLog = logging.FileHandler(logFilePath)
|
||||
|
@ -815,6 +1067,25 @@ if __name__ == '__main__':
|
|||
logger.addHandler(fileLog)
|
||||
|
||||
|
||||
if "postinst" in os.path.basename(__file__):
|
||||
logger.info("Running as post-install script")
|
||||
installer=OpengnsysGitInstaller()
|
||||
|
||||
logger.debug("Obtaining configuration from debconf")
|
||||
import debconf
|
||||
with debconf.Debconf(run_frontend=True) as db:
|
||||
installer.forgejo_organization = db.get('opengnsys/forgejo_organization')
|
||||
installer.forgejo_user = db.get('opengnsys/forgejo_user')
|
||||
installer.forgejo_password = db.get('opengnsys/forgejo_password')
|
||||
installer.email = db.get('opengnsys/forgejo_email')
|
||||
installer.forgejo_port = int(db.get('opengnsys/forgejo_port'))
|
||||
|
||||
# Templates get installed here
|
||||
installer.template_path = "/usr/share/opengnsys-forgejo/"
|
||||
installer.configure_forgejo()
|
||||
sys.exit(0)
|
||||
|
||||
|
||||
parser = argparse.ArgumentParser(
|
||||
prog="OpenGnsys Installer",
|
||||
description="Script para la instalación del repositorio git",
|
||||
|
@ -824,15 +1095,23 @@ if __name__ == '__main__':
|
|||
|
||||
parser.add_argument('--testmode', action='store_true', help="Modo de prueba")
|
||||
parser.add_argument('--ignoresshkey', action='store_true', help="Ignorar clave de SSH")
|
||||
parser.add_argument('--usesshkey', type=str, help="Usar clave SSH especificada")
|
||||
parser.add_argument('--use-ssh-key', metavar="FILE", type=str, help="Add the SSH key from the specified file")
|
||||
parser.add_argument('--test-createuser', action='store_true')
|
||||
parser.add_argument('--extract-ssh-key', action='store_true', help="Extract SSH key from oglive squashfs")
|
||||
parser.add_argument('--set-ssh-key', action='store_true', help="Read SSH key from oglive squashfs and set it in Forgejo")
|
||||
|
||||
parser.add_argument('--extract-ssh-key-from-initrd', action='store_true', help="Extract SSH key from oglive initrd (obsolete)")
|
||||
|
||||
parser.add_argument('--initrd-file', metavar="FILE", help="Initrd file to extract SSH key from")
|
||||
parser.add_argument('--squashfs-file', metavar="FILE", help="Squashfs file to extract SSH key from")
|
||||
parser.add_argument('--oglive-file', metavar="FILE", help="Oglive file (ISO) to extract SSH key from")
|
||||
parser.add_argument('--oglive-url', metavar="URL", help="URL to oglive file (ISO) to extract SSH key from")
|
||||
|
||||
|
||||
parser.add_argument('--set-ssh-key-in-initrd', action='store_true', help="Configure SSH key in oglive (obsolete)")
|
||||
parser.add_argument('--oglive', type=int, metavar='NUM', help = "Do SSH key manipulation on this oglive")
|
||||
parser.add_argument('--quiet', action='store_true', help="Quiet console output")
|
||||
parser.add_argument('--get-image-paths', action='store_true', help="Get paths to image files")
|
||||
parser.add_argument("-v", "--verbose", action="store_true", help = "Verbose console output")
|
||||
|
||||
|
||||
|
@ -848,7 +1127,6 @@ if __name__ == '__main__':
|
|||
installer = OpengnsysGitInstaller()
|
||||
installer.set_testmode(args.testmode)
|
||||
installer.set_ignoresshkey(args.ignoresshkey)
|
||||
installer.set_usesshkey(args.usesshkey)
|
||||
|
||||
logger.debug("Inicio de instalación")
|
||||
|
||||
|
@ -860,25 +1138,40 @@ if __name__ == '__main__':
|
|||
elif args.test_createuser:
|
||||
installer.set_ssh_user_group("oggit2", "oggit2")
|
||||
elif args.extract_ssh_key:
|
||||
keys = installer.extract_ssh_keys(oglive_num = args.oglive)
|
||||
keys = installer.extract_ssh_keys_from_squashfs(oglive_num = args.oglive)
|
||||
print(f"{keys}")
|
||||
elif args.extract_ssh_key_from_initrd:
|
||||
key = installer._extract_ssh_key_from_initrd()
|
||||
key = installer.extract_ssh_key_from_initrd(oglive_number = args.oglive, initrd_file = args.initrd_file)
|
||||
print(f"{key}")
|
||||
elif args.set_ssh_key:
|
||||
installer.add_ssh_key_from_squashfs(oglive_num=args.oglive)
|
||||
installer.add_ssh_key_from_squashfs(oglive_num=args.oglive, squashfs_file=args.squashfs_file, oglive_file = args.oglive_file or args.oglive_url)
|
||||
elif args.use_ssh_key:
|
||||
with open(args.use_ssh_key, 'r', encoding='utf-8') as ssh_key_file:
|
||||
ssh_key_data = ssh_key_file.read().strip()
|
||||
(keytype, keydata, description) = ssh_key_data.split(" ", 2)
|
||||
|
||||
installer.add_forgejo_sshkey(f"{keytype} {keydata}", description)
|
||||
|
||||
elif args.set_ssh_key_in_initrd:
|
||||
installer.set_ssh_key_in_initrd()
|
||||
elif args.get_image_paths:
|
||||
installer.get_image_paths(oglive_num = args.oglive)
|
||||
else:
|
||||
installer.install()
|
||||
installer.install_dependencies()
|
||||
installer.install_api()
|
||||
installer.install_forgejo()
|
||||
|
||||
installer.add_forgejo_repo("windows", "Windows")
|
||||
installer.add_forgejo_repo("linux", "Linux")
|
||||
installer.add_forgejo_repo("mac", "Mac")
|
||||
|
||||
installer.add_ssh_key_from_squashfs(oglive_num = args.oglive, squashfs_file=args.squashfs_file, oglive_file = args.oglive_file or args.oglive_url)
|
||||
|
||||
except RequirementException as req:
|
||||
show_error(f"Requisito para la instalación no satisfecho: {req.message}")
|
||||
exit(1)
|
||||
except OptionalDependencyException as optreq:
|
||||
show_error(optreq.message)
|
||||
exit(1)
|
||||
|
||||
|
||||
|
|
|
@ -18,5 +18,8 @@ override_dh_gencontrol:
|
|||
override_dh_installdocs:
|
||||
# Nothing, we don't want docs
|
||||
|
||||
override_dh_auto_test:
|
||||
# Nothing
|
||||
#
|
||||
override_dh_installchangelogs:
|
||||
# Nothing, we don't want the changelog
|
||||
|
|
Binary file not shown.
|
@ -0,0 +1,23 @@
|
|||
opengnsys-forgejo (0.5.4) UNRELEASED; urgency=medium
|
||||
|
||||
* refs #2364 Fix incorrect template defaults
|
||||
|
||||
-- OpenGnsys <opengnsys@opengnsys.com> Tue, 01 Jul 2025 16:20:30 +0000
|
||||
|
||||
opengnsys-forgejo (0.5.3) UNRELEASED; urgency=medium
|
||||
|
||||
* refs #2364 Update forgejo to LTS version
|
||||
|
||||
-- OpenGnsys <opengnsys@opengnsys.com> Tue, 01 Jul 2025 12:15:35 +0000
|
||||
|
||||
opengnsys-forgejo (0.5.2) UNRELEASED; urgency=medium
|
||||
|
||||
* refs #2364 Redo post-install script, minimize dependencies
|
||||
|
||||
-- OpenGnsys <opengnsys@opengnsys.com> Tue, 01 Jul 2025 12:00:30 +0000
|
||||
|
||||
opengnsys-forgejo (0.5.1dev1) UNRELEASED; urgency=medium
|
||||
|
||||
* Initial version
|
||||
|
||||
-- OpenGnsys <opengnsys@opengnsys.com> Thu, 05 Jun 2025 21:46:30 +0000
|
|
@ -0,0 +1,26 @@
|
|||
Source: opengnsys-forgejo
|
||||
Section: unknown
|
||||
Priority: optional
|
||||
Maintainer: OpenGnsys <opengnsys@opengnsys.es>
|
||||
Rules-Requires-Root: no
|
||||
Build-Depends:
|
||||
debhelper-compat (= 13),
|
||||
Standards-Version: 4.6.2
|
||||
Homepage: https://opengnsys.es
|
||||
#Vcs-Browser: https://salsa.debian.org/debian/ogboot
|
||||
#Vcs-Git: https://salsa.debian.org/debian/ogboot.git
|
||||
|
||||
Package: opengnsys-forgejo
|
||||
Architecture: any
|
||||
Multi-Arch: foreign
|
||||
Depends:
|
||||
${shlibs:Depends},
|
||||
${misc:Depends},
|
||||
bsdextrautils,
|
||||
debconf (>= 1.5.0),
|
||||
python3 (>= 3.12.0),
|
||||
python3-requests (>= 2.31),
|
||||
python3-debconf (>= 1.5.0)
|
||||
Conflicts:
|
||||
Description: Opengnsys Forgejo package for OgGit
|
||||
Forgejo installation configured for OpenGnsys
|
|
@ -0,0 +1,43 @@
|
|||
Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
|
||||
Source: <url://example.com>
|
||||
Upstream-Name: ogboot
|
||||
Upstream-Contact: <preferred name and address to reach the upstream project>
|
||||
|
||||
Files:
|
||||
*
|
||||
Copyright:
|
||||
<years> <put author's name and email here>
|
||||
<years> <likewise for another author>
|
||||
License: GPL-3.0+
|
||||
|
||||
Files:
|
||||
debian/*
|
||||
Copyright:
|
||||
2025 vagrant <vagrant@build>
|
||||
License: GPL-3.0+
|
||||
|
||||
License: GPL-3.0+
|
||||
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 3 of the License, or
|
||||
(at your option) any later version.
|
||||
.
|
||||
This package 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, see <https://www.gnu.org/licenses/>.
|
||||
Comment:
|
||||
On Debian systems, the complete text of the GNU General
|
||||
Public License version 3 can be found in "/usr/share/common-licenses/GPL-3".
|
||||
|
||||
# Please also look if there are files or directories which have a
|
||||
# different copyright/license attached and list them here.
|
||||
# Please avoid picking licenses with terms that are more restrictive than the
|
||||
# packaged work, as it may make Debian's contributions unacceptable upstream.
|
||||
#
|
||||
# If you need, there are some extra license texts available in two places:
|
||||
# /usr/share/debhelper/dh_make/licenses/
|
||||
# /usr/share/common-licenses/
|
|
@ -0,0 +1,2 @@
|
|||
opengnsys-forgejo_0.5_amd64.buildinfo unknown optional
|
||||
opengnsys-forgejo_0.5_amd64.deb unknown optional
|
|
@ -0,0 +1,2 @@
|
|||
/opt/opengnsys/oggit/bin
|
||||
/opt/opengnsys/ogrepository/etc/forgejo/
|
|
@ -0,0 +1,3 @@
|
|||
forgejo /opt/opengnsys/ogrepository/bin
|
||||
forgejo-app.ini /usr/share/opengnsys-forgejo/
|
||||
opengnsys-forgejo.service /usr/share/opengnsys-forgejo/
|
|
@ -0,0 +1,2 @@
|
|||
misc:Depends=
|
||||
misc:Pre-Depends=
|
|
@ -0,0 +1,25 @@
|
|||
Template: opengnsys/forgejo_organization
|
||||
Type: string
|
||||
Default: opengnsys
|
||||
Description: Organizacion de Forgejo
|
||||
|
||||
Template: opengnsys/forgejo_user
|
||||
Type: string
|
||||
Default: oggit
|
||||
Description: Usuario de oggit Forgejo
|
||||
|
||||
Template: opengnsys/forgejo_password
|
||||
Type: password
|
||||
Default: opengnsys
|
||||
Description: Password de cuenta de oggit de Forgejo
|
||||
|
||||
Template: opengnsys/forgejo_email
|
||||
Type: string
|
||||
Default: opegnsys@opengnsys.com
|
||||
Description: Email de cuenta de oggit de Forgejo
|
||||
|
||||
Template: opengnsys/forgejo_port
|
||||
Type: string
|
||||
Default: 3100
|
||||
Description: Puerto TCP de Forgejo
|
||||
|
|
@ -0,0 +1,43 @@
|
|||
#!/usr/bin/env python3
|
||||
|
||||
data = {
|
||||
"forgejo_user" : self.ssh_user,
|
||||
"forgejo_group" : self.ssh_group,
|
||||
"forgejo_port" : str(self.forgejo_port),
|
||||
"forgejo_bin" : bin_path,
|
||||
"forgejo_app_ini" : conf_path,
|
||||
"forgejo_work_path" : forgejo_work_dir_path,
|
||||
"forgejo_data_path" : forgejo_data_dir_path,
|
||||
"forgejo_db_path" : forgejo_db_path,
|
||||
"forgejo_repository_root" : git_dir_path,
|
||||
"forgejo_lfs_path" : lfs_dir_path,
|
||||
"forgejo_log_path" : forgejo_log_dir_path,
|
||||
"forgejo_hostname" : _runcmd("hostname"),
|
||||
"forgejo_lfs_jwt_secret" : _runcmd([bin_path,"generate", "secret", "LFS_JWT_SECRET"]),
|
||||
"forgejo_jwt_secret" : _runcmd([bin_path,"generate", "secret", "JWT_SECRET"]),
|
||||
"forgejo_internal_token" : _runcmd([bin_path,"generate", "secret", "INTERNAL_TOKEN"]),
|
||||
"forgejo_secret_key" : _runcmd([bin_path,"generate", "secret", "SECRET_KEY"])
|
||||
}
|
||||
|
||||
ini_template = "/usr/share/opengnsys-forgejo/forgejo-app.ini"
|
||||
|
||||
|
||||
def _install_template(self, template, destination, keysvalues):
|
||||
data = ""
|
||||
with open(template, "r", encoding="utf-8") as template_file:
|
||||
data = template_file.read()
|
||||
|
||||
for key in keysvalues.keys():
|
||||
if isinstance(keysvalues[key], int):
|
||||
data = data.replace("{" + key + "}", str(keysvalues[key]))
|
||||
else:
|
||||
data = data.replace("{" + key + "}", keysvalues[key])
|
||||
|
||||
with open(destination, "w+", encoding="utf-8") as out_file:
|
||||
out_file.write(data)
|
||||
|
||||
|
||||
|
||||
|
||||
_install_template(os.path.join(self.script_path, "forgejo-app.ini"), conf_path, data)
|
||||
|
|
@ -0,0 +1,37 @@
|
|||
#!/usr/bin/make -f
|
||||
|
||||
# See debhelper(7) (uncomment to enable).
|
||||
# Output every command that modifies files on the build system.
|
||||
#export DH_VERBOSE = 1
|
||||
|
||||
|
||||
# See FEATURE AREAS in dpkg-buildflags(1).
|
||||
#export DEB_BUILD_MAINT_OPTIONS = hardening=+all
|
||||
|
||||
# See ENVIRONMENT in dpkg-buildflags(1).
|
||||
# Package maintainers to append CFLAGS.
|
||||
#export DEB_CFLAGS_MAINT_APPEND = -Wall -pedantic
|
||||
# Package maintainers to append LDFLAGS.
|
||||
#export DEB_LDFLAGS_MAINT_APPEND = -Wl,--as-needed
|
||||
|
||||
|
||||
%:
|
||||
dh $@
|
||||
|
||||
|
||||
%:
|
||||
dh $@
|
||||
|
||||
override_dh_auto_install:
|
||||
dh_auto_install
|
||||
mkdir -p debian/opengnsys-forgejo/opt/opengnsys/ogrepository/var/lib/forgejo
|
||||
mkdir -p debian/opengnsys-forgejo/opt/opengnsys/ogrepository/var/lib/forgejo/work
|
||||
# fails under fakeroot for some reason, fix in postinst
|
||||
# chown -R oggit:oggit debian/opengnsys-forgejo/opt/opengnsys/ogrepository/var/lib/forgejo
|
||||
|
||||
|
||||
# dh_make generated override targets.
|
||||
# This is an example for Cmake (see <https://bugs.debian.org/641051>).
|
||||
#override_dh_auto_configure:
|
||||
# dh_auto_configure -- \
|
||||
# -DCMAKE_LIBRARY_PATH=$(DEB_HOST_MULTIARCH)
|
|
@ -0,0 +1,6 @@
|
|||
#!/bin/bash
|
||||
VERSION=11.0.2
|
||||
|
||||
wget https://codeberg.org/forgejo/forgejo/releases/download/v${VERSION}/forgejo-${VERSION}-linux-amd64 -O forgejo
|
||||
chmod 755 forgejo
|
||||
|
|
@ -0,0 +1,78 @@
|
|||
APP_NAME = OpenGnsys Git
|
||||
APP_SLOGAN =
|
||||
RUN_USER = {forgejo_user}
|
||||
WORK_PATH = {forgejo_work_path}
|
||||
RUN_MODE = prod
|
||||
|
||||
[database]
|
||||
DB_TYPE = sqlite3
|
||||
HOST = 127.0.0.1:3306
|
||||
NAME = forgejo
|
||||
USER = forgejo
|
||||
PASSWD =
|
||||
SCHEMA =
|
||||
SSL_MODE = disable
|
||||
PATH = {forgejo_db_path}
|
||||
LOG_SQL = false
|
||||
|
||||
[repository]
|
||||
ROOT = {forgejo_repository_root}
|
||||
|
||||
[server]
|
||||
SSH_DOMAIN = og-admin
|
||||
DOMAIN = og-admin
|
||||
HTTP_PORT = {forgejo_port}
|
||||
ROOT_URL = http://{forgejo_hostname}:{forgejo_port}/
|
||||
APP_DATA_PATH = {forgejo_data_path}
|
||||
DISABLE_SSH = false
|
||||
SSH_PORT = 22
|
||||
LFS_START_SERVER = true
|
||||
LFS_JWT_SECRET = {forgejo_lfs_jwt_secret}
|
||||
OFFLINE_MODE = true
|
||||
|
||||
[lfs]
|
||||
PATH = {forgejo_lfs_path}
|
||||
|
||||
[mailer]
|
||||
ENABLED = false
|
||||
|
||||
[service]
|
||||
REGISTER_EMAIL_CONFIRM = false
|
||||
ENABLE_NOTIFY_MAIL = false
|
||||
DISABLE_REGISTRATION = true
|
||||
ALLOW_ONLY_EXTERNAL_REGISTRATION = false
|
||||
ENABLE_CAPTCHA = false
|
||||
REQUIRE_SIGNIN_VIEW = false
|
||||
DEFAULT_KEEP_EMAIL_PRIVATE = false
|
||||
DEFAULT_ALLOW_CREATE_ORGANIZATION = true
|
||||
DEFAULT_ENABLE_TIMETRACKING = true
|
||||
NO_REPLY_ADDRESS = noreply.localhost
|
||||
|
||||
[openid]
|
||||
ENABLE_OPENID_SIGNIN = true
|
||||
ENABLE_OPENID_SIGNUP = true
|
||||
|
||||
[cron.update_checker]
|
||||
ENABLED = true
|
||||
|
||||
[session]
|
||||
PROVIDER = file
|
||||
|
||||
[log]
|
||||
MODE = console
|
||||
LEVEL = info
|
||||
ROOT_PATH = {forgejo_log_path} #/tmp/log
|
||||
|
||||
[repository.pull-request]
|
||||
DEFAULT_MERGE_STYLE = merge
|
||||
|
||||
[repository.signing]
|
||||
DEFAULT_TRUST_MODEL = committer
|
||||
|
||||
[security]
|
||||
INSTALL_LOCK = true
|
||||
INTERNAL_TOKEN = {forgejo_internal_token}
|
||||
PASSWORD_HASH_ALGO = pbkdf2_hi
|
||||
|
||||
[oauth2]
|
||||
JWT_SECRET = {forgejo_jwt_secret}
|
|
@ -0,0 +1,11 @@
|
|||
[Service]
|
||||
RestartSec=10s
|
||||
Type=simple
|
||||
User=oggit
|
||||
Group=oggit
|
||||
WorkingDirectory=/opt/opengnsys/ogrepository/var/lib/forgejo/work
|
||||
ExecStart=/opt/opengnsys/ogrepository/bin/forgejo web --config /opt/opengnsys/ogrepository/etc/forgejo/app.ini
|
||||
Restart=always
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
|
@ -0,0 +1,17 @@
|
|||
#!/bin/bash
|
||||
set -e
|
||||
|
||||
git clone https://github.com/vojtechtrefny/pyblkid opengnsys-pyblkid
|
||||
cd opengnsys-pyblkid
|
||||
version=`python3 ./setup.py --version`
|
||||
cd ..
|
||||
|
||||
if [ -d "opengnsys-pyblkid-${version}" ] ; then
|
||||
echo "Directory opengnsys-pyblkid-${version} already exists, won't overwrite"
|
||||
exit 1
|
||||
else
|
||||
rm -rf opengnsys-pyblkid/.git
|
||||
mv opengnsys-pyblkid "opengnsys-pyblkid-${version}"
|
||||
tar -c --xz -v -f "opengnsys-pyblkid_${version}.orig.tar.xz" "opengnsys-pyblkid-${version}"
|
||||
fi
|
||||
|
|
@ -0,0 +1,208 @@
|
|||
Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
|
||||
Upstream-Name: python-libarchive-c
|
||||
Source: https://github.com/Changaco/python-libarchive-c
|
||||
|
||||
Files: *
|
||||
Copyright: 2014-2018 Changaco <changaco@changaco.oy.lc>
|
||||
License: CC-0
|
||||
|
||||
Files: tests/surrogateescape.py
|
||||
Copyright: 2015 Changaco <changaco@changaco.oy.lc>
|
||||
2011-2013 Victor Stinner <victor.stinner@gmail.com>
|
||||
License: BSD-2-clause or PSF-2
|
||||
|
||||
Files: debian/*
|
||||
Copyright: 2015 Jerémy Bobbio <lunar@debian.org>
|
||||
2019 Mattia Rizzolo <mattia@debian.org>
|
||||
License: permissive
|
||||
Copying and distribution of this package, with or without
|
||||
modification, are permitted in any medium without royalty
|
||||
provided the copyright notice and this notice are
|
||||
preserved.
|
||||
|
||||
License: BSD-2-clause
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions
|
||||
are met:
|
||||
* Redistributions of source code must retain the above copyright
|
||||
notice, this list of conditions and the following disclaimer.
|
||||
* Redistributions in binary form must reproduce the above copyright
|
||||
notice, this list of conditions and the following disclaimer in
|
||||
the documentation and/or other materials provided with the
|
||||
distribution.
|
||||
.
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
|
||||
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
|
||||
COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
|
||||
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
|
||||
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
|
||||
OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
|
||||
AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
||||
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
|
||||
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGE.
|
||||
|
||||
License: PSF-2
|
||||
1. This LICENSE AGREEMENT is between the Python Software Foundation ("PSF"),
|
||||
and the Individual or Organization ("Licensee") accessing and otherwise using
|
||||
this software ("Python") in source or binary form and its associated
|
||||
documentation.
|
||||
.
|
||||
2. Subject to the terms and conditions of this License Agreement, PSF hereby
|
||||
grants Licensee a nonexclusive, royalty-free, world-wide license to
|
||||
reproduce, analyze, test, perform and/or display publicly, prepare derivative
|
||||
works, distribute, and otherwise use Python alone or in any derivative
|
||||
version, provided, however, that PSF's License Agreement and PSF's notice of
|
||||
copyright, i.e., "Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006 Python
|
||||
Software Foundation; All Rights Reserved" are retained in Python alone or in
|
||||
any derivative version prepared by Licensee.
|
||||
.
|
||||
3. In the event Licensee prepares a derivative work that is based on or
|
||||
incorporates Python or any part thereof, and wants to make the derivative
|
||||
work available to others as provided herein, then Licensee hereby agrees to
|
||||
include in any such work a brief summary of the changes made to Python.
|
||||
.
|
||||
4. PSF is making Python available to Licensee on an "AS IS" basis. PSF MAKES
|
||||
NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED. BY WAY OF EXAMPLE, BUT
|
||||
NOT LIMITATION, PSF MAKES NO AND DISCLAIMS ANY REPRESENTATION OR WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF
|
||||
PYTHON WILL NOT INFRINGE ANY THIRD PARTY RIGHTS.
|
||||
.
|
||||
5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON FOR ANY
|
||||
INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF
|
||||
MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON, OR ANY DERIVATIVE
|
||||
THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
|
||||
.
|
||||
6. This License Agreement will automatically terminate upon a material breach
|
||||
of its terms and conditions.
|
||||
.
|
||||
7. Nothing in this License Agreement shall be deemed to create any
|
||||
relationship of agency, partnership, or joint venture between PSF and
|
||||
Licensee. This License Agreement does not grant permission to use PSF
|
||||
trademarks or trade name in a trademark sense to endorse or promote products
|
||||
or services of Licensee, or any third party.
|
||||
.
|
||||
8. By copying, installing or otherwise using Python, Licensee agrees to be
|
||||
bound by the terms and conditions of this License Agreement.
|
||||
|
||||
License: CC-0
|
||||
Statement of Purpose
|
||||
.
|
||||
The laws of most jurisdictions throughout the world automatically
|
||||
confer exclusive Copyright and Related Rights (defined below) upon
|
||||
the creator and subsequent owner(s) (each and all, an "owner") of an
|
||||
original work of authorship and/or a database (each, a "Work").
|
||||
.
|
||||
Certain owners wish to permanently relinquish those rights to a Work
|
||||
for the purpose of contributing to a commons of creative, cultural
|
||||
and scientific works ("Commons") that the public can reliably and
|
||||
without fear of later claims of infringement build upon, modify,
|
||||
incorporate in other works, reuse and redistribute as freely as
|
||||
possible in any form whatsoever and for any purposes, including
|
||||
without limitation commercial purposes. These owners may contribute
|
||||
to the Commons to promote the ideal of a free culture and the further
|
||||
production of creative, cultural and scientific works, or to gain
|
||||
reputation or greater distribution for their Work in part through the
|
||||
use and efforts of others.
|
||||
.
|
||||
For these and/or other purposes and motivations, and without any
|
||||
expectation of additional consideration or compensation, the person
|
||||
associating CC0 with a Work (the "Affirmer"), to the extent that he
|
||||
or she is an owner of Copyright and Related Rights in the Work,
|
||||
voluntarily elects to apply CC0 to the Work and publicly distribute
|
||||
the Work under its terms, with knowledge of his or her Copyright and
|
||||
Related Rights in the Work and the meaning and intended legal effect
|
||||
of CC0 on those rights.
|
||||
.
|
||||
1. Copyright and Related Rights. A Work made available under CC0 may
|
||||
be protected by copyright and related or neighboring rights
|
||||
("Copyright and Related Rights"). Copyright and Related Rights
|
||||
include, but are not limited to, the following:
|
||||
.
|
||||
i. the right to reproduce, adapt, distribute, perform, display,
|
||||
communicate, and translate a Work;
|
||||
ii. moral rights retained by the original author(s) and/or
|
||||
performer(s);
|
||||
iii. publicity and privacy rights pertaining to a person's image
|
||||
or likeness depicted in a Work;
|
||||
iv. rights protecting against unfair competition in regards to a
|
||||
Work, subject to the limitations in paragraph 4(a), below;
|
||||
v. rights protecting the extraction, dissemination, use and
|
||||
reuse of data in a Work;
|
||||
vi. database rights (such as those arising under Directive
|
||||
96/9/EC of the European Parliament and of the Council of 11
|
||||
March 1996 on the legal protection of databases, and under
|
||||
any national implementation thereof, including any amended or
|
||||
successor version of such directive); and
|
||||
vii. other similar, equivalent or corresponding rights throughout
|
||||
the world based on applicable law or treaty, and any national
|
||||
implementations thereof.
|
||||
.
|
||||
2. Waiver. To the greatest extent permitted by, but not in
|
||||
contravention of, applicable law, Affirmer hereby overtly, fully,
|
||||
permanently, irrevocably and unconditionally waives, abandons, and
|
||||
surrenders all of Affirmer's Copyright and Related Rights and
|
||||
associated claims and causes of action, whether now known or
|
||||
unknown (including existing as well as future claims and causes of
|
||||
action), in the Work (i) in all territories worldwide, (ii) for
|
||||
the maximum duration provided by applicable law or treaty
|
||||
(including future time extensions), (iii) in any current or future
|
||||
medium and for any number of copies, and (iv) for any purpose
|
||||
whatsoever, including without limitation commercial, advertising
|
||||
or promotional purposes (the "Waiver"). Affirmer makes the Waiver
|
||||
for the benefit of each member of the public at large and to the
|
||||
detriment of Affirmer's heirs and successors, fully intending that
|
||||
such Waiver shall not be subject to revocation, rescission,
|
||||
cancellation, termination, or any other legal or equitable action
|
||||
to disrupt the quiet enjoyment of the Work by the public as
|
||||
contemplated by Affirmer's express Statement of Purpose.
|
||||
.
|
||||
3. Public License Fallback. Should any part of the Waiver for any
|
||||
reason be judged legally invalid or ineffective under applicable law,
|
||||
then the Waiver shall be preserved to the maximum extent permitted
|
||||
taking into account Affirmer's express Statement of Purpose. In
|
||||
addition, to the extent the Waiver is so judged Affirmer hereby
|
||||
grants to each affected person a royalty-free, non transferable, non
|
||||
sublicensable, non exclusive, irrevocable and unconditional license
|
||||
to exercise Affirmer's Copyright and Related Rights in the Work (i)
|
||||
in all territories worldwide, (ii) for the maximum duration provided
|
||||
by applicable law or treaty (including future time extensions), (iii)
|
||||
in any current or future medium and for any number of copies, and
|
||||
(iv) for any purpose whatsoever, including without limitation
|
||||
commercial, advertising or promotional purposes (the "License"). The
|
||||
License shall be deemed effective as of the date CC0 was applied by
|
||||
Affirmer to the Work. Should any part of the License for any reason
|
||||
be judged legally invalid or ineffective under applicable law, such
|
||||
partial invalidity or ineffectiveness shall not invalidate the
|
||||
remainder of the License, and in such case Affirmer hereby affirms
|
||||
that he or she will not (i) exercise any of his or her remaining
|
||||
Copyright and Related Rights in the Work or (ii) assert any
|
||||
associated claims and causes of action with respect to the Work, in
|
||||
either case contrary to Affirmer's express Statement of Purpose.
|
||||
.
|
||||
4. Limitations and Disclaimers.
|
||||
.
|
||||
a. No trademark or patent rights held by Affirmer are waived,
|
||||
abandoned, surrendered, licensed or otherwise affected by
|
||||
this document.
|
||||
b. Affirmer offers the Work as-is and makes no representations
|
||||
or warranties of any kind concerning the Work, express,
|
||||
implied, statutory or otherwise, including without limitation
|
||||
warranties of title, merchantability, fitness for a
|
||||
particular purpose, non infringement, or the absence of
|
||||
latent or other defects, accuracy, or the present or absence
|
||||
of errors, whether or not discoverable, all to the greatest
|
||||
extent permissible under applicable law.
|
||||
c. Affirmer disclaims responsibility for clearing rights of
|
||||
other persons that may apply to the Work or any use thereof,
|
||||
including without limitation any person's Copyright and
|
||||
Related Rights in the Work. Further, Affirmer disclaims
|
||||
responsibility for obtaining any necessary consents,
|
||||
permissions or other rights required for any use of the
|
||||
Work.
|
||||
d. Affirmer understands and acknowledges that Creative Commons
|
||||
is not a party to this document and has no duty or obligation
|
||||
with respect to this CC0 or use of the Work.
|
||||
|
|
@ -0,0 +1,2 @@
|
|||
Tests: upstream-tests
|
||||
Depends: @, python3-mock, python3-pytest
|
|
@ -0,0 +1,14 @@
|
|||
#!/bin/sh
|
||||
|
||||
set -e
|
||||
|
||||
if ! [ -d "$AUTOPKGTEST_TMP" ]; then
|
||||
echo "AUTOPKGTEST_TMP not set." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
cp -rv tests "$AUTOPKGTEST_TMP"
|
||||
cd "$AUTOPKGTEST_TMP"
|
||||
mkdir -v libarchive
|
||||
touch README.rst
|
||||
py.test-3 tests -vv -l -r a
|
Loading…
Reference in New Issue