Compare commits
57 Commits
fix_ssh_ke
...
main
Author | SHA1 | Date |
---|---|---|
|
2ad4848a5e | |
|
6e8d9d4132 | |
|
d048ee782c | |
|
73c0220ab3 | |
|
037ac63c97 | |
|
83b0fd7c03 | |
|
199ef8c5e1 | |
|
05b51de851 | |
|
228bd85aa8 | |
|
3992ff27f0 | |
|
8728682936 | |
|
a1f0561f5c | |
|
e355562714 | |
|
8dcd1faefd | |
|
05b963d611 | |
|
da5d6fd8c5 | |
|
3c2fc27e2e | |
|
b04bf3c5b1 | |
|
bff65cde01 | |
|
984b251615 | |
|
28f2537aed | |
|
c949cfb9a9 | |
|
9f87997722 | |
|
a387af27d0 | |
|
9a9cf17403 | |
|
ba5384ea77 | |
|
74efebf3c8 | |
|
88953696e7 | |
|
f972ae1ae9 | |
|
95524ac9cf | |
|
ccf04ba8fc | |
|
9f170c23c7 | |
|
6236be85d8 | |
|
0118ca53a5 | |
|
bada82e88a | |
|
a3b938e41e | |
|
dd60800c97 | |
|
ecbba3d45e | |
|
a58023f893 | |
|
c23b4ddddb | |
|
2507c035ae | |
|
d0149f40f8 | |
|
fba880c477 | |
|
29f653a527 | |
|
b9d3f5c4c7 | |
|
5406e67b95 | |
|
15769dde0f | |
|
f8cb868a2a | |
|
4316217faa | |
|
b77aa1fc4d | |
|
d7869c35b7 | |
|
8af857c9ef | |
|
48d10b7cd9 | |
|
90fd5b274f | |
|
311ecc7f3a | |
|
6ba0788bc0 | |
|
826625f66a |
41
CHANGELOG.md
41
CHANGELOG.md
|
@ -1,5 +1,44 @@
|
|||
# Changelog
|
||||
|
||||
## [0.10.0] - 2025-07-07
|
||||
|
||||
### Added
|
||||
|
||||
- OgGit functionality (#2371, #2363, #2363, #2317)
|
||||
|
||||
## [0.9.0] - 2025-06-25
|
||||
|
||||
## Added
|
||||
|
||||
- Changed old tools for tools non dependant of Pyhton2 in repo
|
||||
- mktorrent to handle creation of torrent files
|
||||
- aria2c as torrent client for initial seeding
|
||||
- opentracker as torrent tracker tool
|
||||
|
||||
## [0.8.2] - 2025-06-01
|
||||
|
||||
### Changed
|
||||
|
||||
- Modified sudoersfile to start torrent
|
||||
|
||||
## [0.8.1] - 2025-04-01
|
||||
|
||||
### Changed
|
||||
|
||||
- Add sudo to cancel transfers endpoints (#1796)
|
||||
|
||||
## [0.8.0] - 2025-03-25
|
||||
|
||||
### Added
|
||||
|
||||
- Rename Image functionality (#1733)
|
||||
|
||||
## [0.7.3] - 2025-03-19
|
||||
|
||||
### Changed
|
||||
|
||||
- Fix permissions problem and authorized_keys file in debian package
|
||||
|
||||
## [0.7.2] - 2025-03-19
|
||||
|
||||
### Changed
|
||||
|
@ -176,7 +215,7 @@
|
|||
|
||||
### Changed
|
||||
|
||||
- API improvements (#631)
|
||||
- API improvements (#631)
|
||||
|
||||
## [0.5.1] - 2024-11-15
|
||||
|
||||
|
|
|
@ -49,15 +49,23 @@ pipeline {
|
|||
}
|
||||
}
|
||||
|
||||
stage('Generate Changelog (Nightly)'){
|
||||
when {
|
||||
branch 'main'
|
||||
}
|
||||
steps {
|
||||
script {
|
||||
def devName = params.DEV_NAME ? params.DEV_NAME : env.DEFAULT_DEV_NAME
|
||||
def devEmail = params.DEV_EMAIL ? params.DEV_EMAIL : env.DEFAULT_DEV_EMAIL
|
||||
generateDebianChangelog(env.BUILD_DIR, devName, devEmail,"nightly")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
stage('Build') {
|
||||
steps {
|
||||
dir("${env.BUILD_DIR}") {
|
||||
sh '''
|
||||
dpkg-buildpackage -us -uc
|
||||
mkdir -p ../artifacts && mv ../*.deb ../*.changes ../*.buildinfo ../artifacts/
|
||||
ssh aptly@172.17.8.68 "rm -rf /var/tmp/opengnsys/debian-repo/ogrepository && mkdir -p /var/tmp/opengnsys/debian-repo/ogrepository"
|
||||
scp -r ../artifacts/* aptly@172.17.8.68:/var/tmp/opengnsys/debian-repo/ogrepository
|
||||
'''
|
||||
script {
|
||||
construirPaquete(env.BUILD_DIR, "../artifacts", "172.17.8.68", "/var/tmp/opengnsys/debian-repo/ogrepository")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -69,7 +77,24 @@ pipeline {
|
|||
}
|
||||
agent { label 'debian-repo' }
|
||||
steps {
|
||||
sh "aptly repo add opengnsys-devel /var/tmp/opengnsys/debian-repo/ogrepository/*.deb"
|
||||
script {
|
||||
// Construir el patrón de versión esperado en el nombre del paquete
|
||||
def versionPattern = "${env.TAG_NAME}-${env.BUILD_NUMBER}"
|
||||
publicarEnAptly('/var/tmp/opengnsys/debian-repo/ogrepository', 'opengnsys-devel', versionPattern)
|
||||
}
|
||||
}
|
||||
}
|
||||
stage ('Publish to Debian Repository (Nightly)') {
|
||||
when {
|
||||
branch 'main'
|
||||
}
|
||||
agent { label 'debian-repo' }
|
||||
steps {
|
||||
script {
|
||||
// Construir el patrón de versión esperado en el nombre del paquete
|
||||
def versionPattern = "-${env.BUILD_NUMBER}~nightly"
|
||||
publicarEnAptly('/var/tmp/opengnsys/debian-repo/ogrepository', 'nightly', versionPattern)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
29
README.md
29
README.md
|
@ -74,8 +74,9 @@ El presente documento detalla los endpoints de la API, con sus respectivos pará
|
|||
18. [Hacer Backup de una Imagen](#hacer-backup-de-una-imagen) - `PUT /ogrepository/v1/repo/images`
|
||||
19. [Convertir Imagen Virtual a Imagen OpenGnsys](#convertir-imagen-virtual-a-imagen-opengnsys) - `POST /ogrepository/v1/images/virtual`
|
||||
20. [Convertir Imagen OpenGnsys a Imagen Virtual](#convertir-imagen-opengnsys-a-imagen-virtual) - `PUT /ogrepository/v1/images/virtual`
|
||||
21. [Crear archivos auxiliares](#crear-archivos-auxiliares) - `POST /ogrepository/v1/images/torrentsum`
|
||||
22. [Enviar paquete Wake On Lan](#enviar-paquete-wake-on-lan) - `POST /ogrepository/v1/wol`
|
||||
21. [Renombrar una Imagen](#renombrar-una-imagen) - `POST /ogrepository/v1/images/rename`
|
||||
22. [Crear archivos auxiliares](#crear-archivos-auxiliares) - `POST /ogrepository/v1/images/torrentsum`
|
||||
23. [Enviar paquete Wake On Lan](#enviar-paquete-wake-on-lan) - `POST /ogrepository/v1/wol`
|
||||
|
||||
---
|
||||
### Obtener Información de Estado de ogRepository
|
||||
|
@ -677,6 +678,30 @@ curl -X PUT -H "Authorization: $API_KEY" -H "Content-Type: application/json" -d
|
|||
- **Código 400 Bad Request:** No se ha encontrado la imagen especificada.
|
||||
- **Código 200 OK:** La imagen se está convirtiendo a virtual.
|
||||
|
||||
---
|
||||
### Renombrar una Imagen
|
||||
|
||||
Se renombrará la imagen especificada como primer parámetro (y todos sus archivos asociados), asignando el nombre especificado como segundo parámetro.
|
||||
Se puede hacer con el script "**renameImage.py**", que debe ser llamado por el endpoint.
|
||||
**NOTA**: El script requiere que se le pase el nombre de la imagen (sin extensión) como primer parámetro, y el nuevo nombre a asignar como segundo parámetro. El primer parámetro se obtiene en la API, a partir del ID de la imagen (que corresponde al contenido del archivo "full.sum"), pero el nuevo nombre a asignar debe enviarse en el JSON.
|
||||
|
||||
**URL:** `/ogrepository/v1/images/rename`
|
||||
**Método HTTP:** POST
|
||||
|
||||
**Cuerpo de la Solicitud (JSON):**
|
||||
- **ID_img**: Identificador de la imagen (correspondiente al contenido del archivo "full.sum" asociado).
|
||||
- **image_new_name**: Nuevo nombre a asignar a la imagen.
|
||||
|
||||
**Ejemplo de Solicitud:**
|
||||
|
||||
```bash
|
||||
curl -X POST -H "Authorization: $API_KEY" -H "Content-Type: application/json" -d '{"ID_img":"22735b9070e4a8043371b8c6ae52b90d", "image_new_name":"Ubuntu_BKP"}' http://example.com/ogrepository/v1/images/rename
|
||||
```
|
||||
**Respuestas:**
|
||||
- **Código 500 Internal Server Error:** Ocurrió un error al renombrar la imagen.
|
||||
- **Código 400 Bad Request:** No se ha encontrado la imagen especificada.
|
||||
- **Código 200 OK:** La imagen se ha renombrado exitosamente.
|
||||
|
||||
---
|
||||
### Crear archivos auxiliares
|
||||
|
||||
|
|
|
@ -28,8 +28,9 @@ El presente documento detalla los endpoints de la API, con sus respectivos pará
|
|||
18. [Hacer Backup de una Imagen](#hacer-backup-de-una-imagen) - `PUT /ogrepository/v1/repo/images`
|
||||
19. [Convertir Imagen Virtual a Imagen OpenGnsys](#convertir-imagen-virtual-a-imagen-opengnsys) - `POST /ogrepository/v1/images/virtual`
|
||||
20. [Convertir Imagen OpenGnsys a Imagen Virtual](#convertir-imagen-opengnsys-a-imagen-virtual) - `PUT /ogrepository/v1/images/virtual`
|
||||
21. [Crear archivos auxiliares](#crear-archivos-auxiliares) - `POST /ogrepository/v1/images/torrentsum`
|
||||
22. [Enviar paquete Wake On Lan](#enviar-paquete-wake-on-lan) - `POST /ogrepository/v1/wol`
|
||||
21. [Renombrar una Imagen](#renombrar-una-imagen) - `POST /ogrepository/v1/images/rename`
|
||||
22. [Crear archivos auxiliares](#crear-archivos-auxiliares) - `POST /ogrepository/v1/images/torrentsum`
|
||||
23. [Enviar paquete Wake On Lan](#enviar-paquete-wake-on-lan) - `POST /ogrepository/v1/wol`
|
||||
|
||||
---
|
||||
### Obtener Información de Estado de ogRepository
|
||||
|
@ -631,6 +632,30 @@ curl -X PUT -H "Authorization: $API_KEY" -H "Content-Type: application/json" -d
|
|||
- **Código 400 Bad Request:** No se ha encontrado la imagen especificada.
|
||||
- **Código 200 OK:** La imagen se está convirtiendo a virtual.
|
||||
|
||||
---
|
||||
### Renombrar una Imagen
|
||||
|
||||
Se renombrará la imagen especificada como primer parámetro (y todos sus archivos asociados), asignando el nombre especificado como segundo parámetro.
|
||||
Se puede hacer con el script "**renameImage.py**", que debe ser llamado por el endpoint.
|
||||
**NOTA**: El script requiere que se le pase el nombre de la imagen (sin extensión) como primer parámetro, y el nuevo nombre a asignar como segundo parámetro. El primer parámetro se obtiene en la API, a partir del ID de la imagen (que corresponde al contenido del archivo "full.sum"), pero el nuevo nombre a asignar debe enviarse en el JSON.
|
||||
|
||||
**URL:** `/ogrepository/v1/images/rename`
|
||||
**Método HTTP:** POST
|
||||
|
||||
**Cuerpo de la Solicitud (JSON):**
|
||||
- **ID_img**: Identificador de la imagen (correspondiente al contenido del archivo "full.sum" asociado).
|
||||
- **image_new_name**: Nuevo nombre a asignar a la imagen.
|
||||
|
||||
**Ejemplo de Solicitud:**
|
||||
|
||||
```bash
|
||||
curl -X POST -H "Authorization: $API_KEY" -H "Content-Type: application/json" -d '{"ID_img":"22735b9070e4a8043371b8c6ae52b90d", "image_new_name":"Ubuntu_BKP"}' http://example.com/ogrepository/v1/images/rename
|
||||
```
|
||||
**Respuestas:**
|
||||
- **Código 500 Internal Server Error:** Ocurrió un error al renombrar la imagen.
|
||||
- **Código 400 Bad Request:** No se ha encontrado la imagen especificada.
|
||||
- **Código 200 OK:** La imagen se ha renombrado exitosamente.
|
||||
|
||||
---
|
||||
### Crear archivos auxiliares
|
||||
|
||||
|
|
874
api/repo_api.py
874
api/repo_api.py
File diff suppressed because it is too large
Load Diff
650
api/swagger.yaml
650
api/swagger.yaml
|
@ -4,7 +4,7 @@ info:
|
|||
version: "1.0"
|
||||
description: |
|
||||
---
|
||||
|
||||
|
||||
# -----------------------------------------------------------------------------------------------------------
|
||||
|
||||
# Esto hace que el Swagger se ordene por los tags (apartados), de la forma especificada:
|
||||
|
@ -18,7 +18,7 @@ tags:
|
|||
- name: "Transferencia entre Repositorios y Backup"
|
||||
- name: "Importar y Exportar Máquinas Virtuales"
|
||||
- name: "Varios"
|
||||
|
||||
- name: "Git"
|
||||
|
||||
# -----------------------------------------------------------------------------------------------------------
|
||||
# Apartado "Estado de ogRepository"
|
||||
|
@ -30,7 +30,7 @@ paths:
|
|||
summary: "Obtener Información de Estado de ogRepository"
|
||||
description: >
|
||||
Este endpoint ejecuta el script "**getRepoStatus.py**" y devuelve su salida en formato JSON,
|
||||
incluyendo información sobre la CPU, memoria RAM, disco duro, servicios, y procesos específicos de ogRepository, e instalación de ogGit.
|
||||
incluyendo información sobre la CPU, memoria RAM, disco duro, servicios, y procesos específicos de ogRepository, e instalación de ogGit.
|
||||
tags:
|
||||
- "Estado de ogRepository"
|
||||
responses:
|
||||
|
@ -140,14 +140,14 @@ paths:
|
|||
# -----------------------------------------------------------------------------------------------------------
|
||||
# Apartado "Información de Imágenes"
|
||||
# -----------------------------------------------------------------------------------------------------------
|
||||
|
||||
|
||||
/ogrepository/v1/images:
|
||||
put:
|
||||
summary: "Actualizar Información del Repositorio"
|
||||
description: |
|
||||
Este endpoint actualiza la información de las imágenes almacenadas en el repositorio, reflejándola en los archivos "**repoinfo.json**" y "**trashinfo.json**".
|
||||
Utiliza el script "**updateRepoInfo.py**", que a su vez llama al script "**updateTrashInfo.py**", para actualizar también la información de la papelera.
|
||||
|
||||
|
||||
No hace falta que se le llame al crear o exportar una imagen, ya que lo llama el endpoint "**Crear archivos auxiliares**" (que sí debe ser llamado en esos casos).
|
||||
tags:
|
||||
- "Información de Imágenes"
|
||||
|
@ -192,7 +192,7 @@ paths:
|
|||
get:
|
||||
summary: "Obtener Información de todas las Imágenes"
|
||||
description: |
|
||||
Este endpoint ejecuta el script "**getRepoInfo.py**" con el parámetro "**all**", para devolver información de todas las imágenes almacenadas en el repositorio y en la papelera, que a su vez llama al script "**updateRepoInfo.py**", para actualizar previamente la información del repositorio.
|
||||
Este endpoint ejecuta el script "**getRepoInfo.py**" con el parámetro "**all**", para devolver información de todas las imágenes almacenadas en el repositorio y en la papelera, que a su vez llama al script "**updateRepoInfo.py**", para actualizar previamente la información del repositorio.
|
||||
Devuelve detalles como el nombre de la imagen, tipo, nombre del cliente, clonador, compresor, sistema de archivos, tamaño de los datos, tamaño de la imagen, y hashes MD5.
|
||||
tags:
|
||||
- "Información de Imágenes"
|
||||
|
@ -1257,7 +1257,7 @@ paths:
|
|||
|
||||
# -----------------------------------------------------------------------------------------------------------
|
||||
|
||||
#/ogrepository/v1/p2p:
|
||||
#/ogrepository/v1/p2p:
|
||||
delete:
|
||||
summary: "Cancelar Transmisiones P2P"
|
||||
description: |
|
||||
|
@ -1311,10 +1311,10 @@ paths:
|
|||
Este endpoint importa la imagen especificada desde un repositorio remoto al repositorio local (en el que se ejecuta el endpoint).
|
||||
Utiliza el script "**importImage.py**", que recibe como parámetros el nombre de la imagen, la IP o hostname del servidor remoto, y el usuario con el que conectar al servidor remoto.
|
||||
que a su vez llama al script "**updateRepoInfo.py**", para actualizar la información del repositorio.
|
||||
|
||||
|
||||
**NOTA**: Este endpoint es asíncrono, ya que puede tardar mucho tiempo, por lo que solo informa de que la imagen se está importando, y abre un proceso paralelo, que avisará a ogCore cuando finalice la tarea (llamando a un endpoint de ogCore).
|
||||
tags:
|
||||
- "Transferencia entre Repositorios y Backup"
|
||||
- "Transferencia entre Repositorios y Backup"
|
||||
parameters:
|
||||
- name: JSON
|
||||
in: body
|
||||
|
@ -1436,7 +1436,7 @@ paths:
|
|||
* **ID_img** - Identificador de la imagen, correspondiente al contenido del archivo 'full.sum'
|
||||
* **repo_ip** - Dirección IP del servidor remoto
|
||||
* **user** - Usuario con el que conectar al servidor remoto
|
||||
* **remote_path** - Ruta remota en la que copiar la imagen
|
||||
* **remote_path** - Ruta remota en la que copiar la imagen
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
|
@ -1457,7 +1457,7 @@ paths:
|
|||
example: "/home/opengnsys"
|
||||
responses:
|
||||
"200":
|
||||
description: "Se está haciendo backup de la imagen."
|
||||
description: "Se está haciendo backup de la imagen."
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
|
@ -1532,20 +1532,20 @@ paths:
|
|||
post:
|
||||
summary: "Convertir Imagen Virtual a Imagen OpenGnsys"
|
||||
description: |
|
||||
Este endpoint convierte la imagen virtual especificada como primer parámetro en una imagen "img" como las que se generan desde OpenGnsys, debiendo haberse copiado previamente en la ruta "opt/opengnsys/ogrepository/images_virtual".
|
||||
Utiliza el script "**convertVMtoIMG.py**", que recibe como parámetros el nombre de la imagen virtual, y el sistema de archivos de la partición a clonar (en formato "blkid").
|
||||
Se puede comprobar todos los sistemas de archivos aceptados por "blkid" ejecutando el comando "blkid -k".
|
||||
|
||||
Este endpoint convierte la imagen virtual especificada como primer parámetro en una imagen "img" como las que se generan desde OpenGnsys, debiendo haberse copiado previamente en la ruta "opt/opengnsys/ogrepository/images_virtual".
|
||||
Utiliza el script "**convertVMtoIMG.py**", que recibe como parámetros el nombre de la imagen virtual, y el sistema de archivos de la partición a clonar (en formato "blkid").
|
||||
Se puede comprobar todos los sistemas de archivos aceptados por "blkid" ejecutando el comando "blkid -k".
|
||||
|
||||
**NOTA**: Este endpoint es asíncrono, ya que puede tardar mucho tiempo, por lo que solo informa de que la imagen virtual se está convirtiendo, y abre un proceso paralelo, que avisará a ogCore cuando finalice la tarea (llamando a un endpoint de ogCore).
|
||||
tags:
|
||||
- "Importar y Exportar Máquinas Virtuales"
|
||||
- "Importar y Exportar Máquinas Virtuales"
|
||||
parameters:
|
||||
- name: JSON
|
||||
in: body
|
||||
required: true
|
||||
description: |
|
||||
* **virtual_image** - Nombre de la imagen virtual, con extensión
|
||||
* **filesystem** - Sistema de archivos de la partición a clonar, en formato "blkid"
|
||||
* **virtual_image** - Nombre de la imagen virtual, con extensión
|
||||
* **filesystem** - Sistema de archivos de la partición a clonar, en formato "blkid"
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
|
@ -1640,19 +1640,19 @@ paths:
|
|||
put:
|
||||
summary: "Convertir Imagen OpenGnsys a Imagen Virtual"
|
||||
description: |
|
||||
Este endpoint convierte la imagen "img" especificada como primer parámetro en una imagen virtual con la extensión especificada como segundo parámetro ("vdi", "vmdk", etc), guardándola en la ruta "opt/opengnsys/ogrepository/images_virtual/export".
|
||||
Utiliza el script "**convertIMGtoVM.py**", que recibe como parámetros el nombre de la imagen, y la extensión del disco virtual destino ("vdi", "vmdk", etc).
|
||||
|
||||
Este endpoint convierte la imagen "img" especificada como primer parámetro en una imagen virtual con la extensión especificada como segundo parámetro ("vdi", "vmdk", etc), guardándola en la ruta "opt/opengnsys/ogrepository/images_virtual/export".
|
||||
Utiliza el script "**convertIMGtoVM.py**", que recibe como parámetros el nombre de la imagen, y la extensión del disco virtual destino ("vdi", "vmdk", etc).
|
||||
|
||||
**NOTA**: Este endpoint es asíncrono, ya que puede tardar mucho tiempo, por lo que solo informa de que la imagen se está convirtiendo a virtual, y abre un proceso paralelo, que avisará a ogCore cuando finalice la tarea (llamando a un endpoint de ogCore).
|
||||
tags:
|
||||
- "Importar y Exportar Máquinas Virtuales"
|
||||
- "Importar y Exportar Máquinas Virtuales"
|
||||
parameters:
|
||||
- name: JSON
|
||||
in: body
|
||||
required: true
|
||||
description: |
|
||||
* **ID_img** - Identificador de la imagen, correspondiente al contenido del archivo 'full.sum'
|
||||
* **vm_extension** - Extensión del disco virtual destino ("vdi", "vmdk", etc)
|
||||
* **vm_extension** - Extensión del disco virtual destino ("vdi", "vmdk", etc)
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
|
@ -1877,3 +1877,607 @@ paths:
|
|||
example: "(Exception description)"
|
||||
|
||||
# -----------------------------------------------------------------------------------------------------------
|
||||
|
||||
/ogrepository/v1/images/rename:
|
||||
put:
|
||||
summary: "Renombrar una Imagen"
|
||||
description: |
|
||||
Este endpoint renombra la imagen especificada como primer parámetro (y todos sus archivos asociados), asignando el nombre especificado como segundo parámetro.
|
||||
Utiliza el script "**renameImage.py**", que recibe como parámetros el nombre original y el nuevo nombre a asignar.
|
||||
tags:
|
||||
- "Varios"
|
||||
parameters:
|
||||
- name: JSON
|
||||
in: body
|
||||
required: true
|
||||
description: |
|
||||
* **ID_img** - Identificador de la imagen, correspondiente al contenido del archivo 'full.sum'
|
||||
* **image_new_name** - Nuevo nombre a asignar a la imagen
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
ID_img:
|
||||
type: string
|
||||
example: "22735b9070e4a8043371b8c6ae52b90d"
|
||||
image_new_name:
|
||||
type: string
|
||||
example: "Ubuntu_BKP"
|
||||
responses:
|
||||
"200":
|
||||
description: "La imagen se ha renombrado exitosamente."
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
success:
|
||||
type: boolean
|
||||
example: true
|
||||
output:
|
||||
type: string
|
||||
example: "Image renamed successfully"
|
||||
"400 (Image not found)":
|
||||
description: "No se ha encontrado la imagen."
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
success:
|
||||
type: boolean
|
||||
example: false
|
||||
exception:
|
||||
type: string
|
||||
example: "Image not found"
|
||||
"400 (Name incorrect)":
|
||||
description: "Ya existe una imagen con el nombre a asignar."
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
success:
|
||||
type: boolean
|
||||
example: false
|
||||
exception:
|
||||
type: string
|
||||
example: "There is an image with the name to assign"
|
||||
"500 (Error)":
|
||||
description: "Error al renombrar la imagen."
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
success:
|
||||
type: boolean
|
||||
example: false
|
||||
error:
|
||||
type: string
|
||||
example: "(Error description)"
|
||||
"500 (Exception)":
|
||||
description: "Excepción inesperada al renombrar la imagen."
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
success:
|
||||
type: boolean
|
||||
example: false
|
||||
exception:
|
||||
type: string
|
||||
example: "(Exception description)"
|
||||
|
||||
# -----------------------------------------------------------------------------------------------------------
|
||||
|
||||
|
||||
# -----------------------------------------------------------
|
||||
# ____ _ _
|
||||
# / ___(_) |_
|
||||
# | | _| | __|
|
||||
# | |_| | | |_
|
||||
# \____|_|\__|
|
||||
#
|
||||
# -----------------------------------------------------------
|
||||
|
||||
/ogrepository/v1/git/ssh_key:
|
||||
post:
|
||||
summary: "Agregar clave de SSH de ogLive"
|
||||
description: |
|
||||
Agrega una clave de SSH que va a usarse desde el ogLive
|
||||
para interactuar con Git.
|
||||
|
||||
Es necesario especificar **ssh_key** o **oglive**.
|
||||
|
||||
Especificando **ssh_key** se agrega la cclave especificada directamente.
|
||||
|
||||
tags:
|
||||
- "Git"
|
||||
parameters:
|
||||
- name: JSON
|
||||
in: body
|
||||
required: true
|
||||
description: |
|
||||
* **ssh_key** - Clave de SSH (opcional)
|
||||
* **oglive** - URL a ogLive (opcional, NO USAR DE MOMENTO)
|
||||
* **description** - Descripcion (opcional)
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
ssh_key:
|
||||
type: string
|
||||
example: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAINEOttwhJ+9THRZ1Zv/6QUwPUDq1X7opG9V7EFLVWxQV"
|
||||
required: False
|
||||
description:
|
||||
type: string
|
||||
example: "OgLive r20250518"
|
||||
required: False
|
||||
responses:
|
||||
"200":
|
||||
description: "Exito"
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
success:
|
||||
type: boolean
|
||||
example: True
|
||||
required: True
|
||||
output:
|
||||
type: string
|
||||
example: "SSH key added"
|
||||
required: True
|
||||
job_id:
|
||||
type: string
|
||||
example: "GitSshKey_873f353f"
|
||||
required: False
|
||||
|
||||
/ogrepository/v1/git/repositories:
|
||||
get:
|
||||
summary: "Obtener lista de repositorios"
|
||||
description: |
|
||||
Devuelve una lista de repositorios de Git
|
||||
tags:
|
||||
- "Git"
|
||||
responses:
|
||||
"200":
|
||||
description: "Lista de repositorios"
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
repositories:
|
||||
type: array
|
||||
items:
|
||||
type: string
|
||||
example: linux
|
||||
|
||||
"500":
|
||||
description: "Excepción"
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
success:
|
||||
type: boolean
|
||||
example: false
|
||||
exception:
|
||||
type: string
|
||||
example: "(Exception description)"
|
||||
post:
|
||||
summary: "Crear repositorio"
|
||||
description: |
|
||||
Crea un repositorio nuevo de Git
|
||||
tags:
|
||||
- "Git"
|
||||
parameters:
|
||||
- name: JSON
|
||||
in: body
|
||||
required: true
|
||||
description: |
|
||||
* **name** - Nombre de repositorio
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
name:
|
||||
type: string
|
||||
example: linux
|
||||
responses:
|
||||
"201":
|
||||
description: "Repositorio creado"
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
status:
|
||||
type: string
|
||||
example: "Repository created"
|
||||
"500 (Exception)":
|
||||
description: "JSON post data missing"
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
error:
|
||||
type: string
|
||||
example: "Parameters missing"
|
||||
/ogrepository/v1/git/repositories/{repository}/tags:
|
||||
get:
|
||||
summary: "Obtener lista de tags"
|
||||
description: |
|
||||
Devuelve una lista de tags de Git
|
||||
tags:
|
||||
- "Git"
|
||||
parameters:
|
||||
- name: repository
|
||||
in: path
|
||||
required: true
|
||||
type: string
|
||||
description: "Nombre de repositorio"
|
||||
responses:
|
||||
"200":
|
||||
description: "Lista de tags"
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
tags:
|
||||
type: array
|
||||
items:
|
||||
type: object
|
||||
properties:
|
||||
name:
|
||||
type: string
|
||||
example: v0.1
|
||||
commit:
|
||||
type: string
|
||||
example: db8e84d5d2548f589ee503c1c6d5003cc6a0d803
|
||||
committer:
|
||||
type: string
|
||||
example: John Smith
|
||||
committed_datetime:
|
||||
type: int
|
||||
example: 1745360193
|
||||
message:
|
||||
type: string
|
||||
example: "Initial release"
|
||||
required: False
|
||||
tagged_date:
|
||||
type: int
|
||||
example: 1745360194
|
||||
required: False
|
||||
tagger:
|
||||
type: string
|
||||
example: John Smith
|
||||
required: False
|
||||
tagger_tz_offset:
|
||||
type: int
|
||||
example: -7200
|
||||
required: False
|
||||
|
||||
"500":
|
||||
description: "Excepción"
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
success:
|
||||
type: boolean
|
||||
example: false
|
||||
exception:
|
||||
type: string
|
||||
example: "(Exception description)"
|
||||
post:
|
||||
summary: "Crear tag"
|
||||
description: |
|
||||
Crea una tag de git
|
||||
tags:
|
||||
- "Git"
|
||||
parameters:
|
||||
- name: repository
|
||||
in: path
|
||||
required: true
|
||||
type: string
|
||||
description: "Nombre de repositorio"
|
||||
- name: JSON
|
||||
in: body
|
||||
required: true
|
||||
description: |
|
||||
* **name** - Nombre del tag
|
||||
* **commit** - Commit al que apunta el tag nuevo. Puede ser un nombre de otra rama/tag.
|
||||
* **message** - Mensaje descriptivo para el tag. Opcional, si no se especifica se asume una cadena vacía.
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
name:
|
||||
type: string
|
||||
example: v1.0
|
||||
required: True
|
||||
commit:
|
||||
type: string
|
||||
example: HEAD
|
||||
required: True
|
||||
message:
|
||||
type: string
|
||||
example: Version 1.0
|
||||
required: False
|
||||
responses:
|
||||
"201":
|
||||
description: "Tag creado"
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
status:
|
||||
type: string
|
||||
example: created
|
||||
|
||||
"500":
|
||||
description: "Excepción"
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
success:
|
||||
type: boolean
|
||||
example: false
|
||||
exception:
|
||||
type: string
|
||||
example: "(Exception description)"
|
||||
"404":
|
||||
description: "El repositorio no existe"
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
error:
|
||||
type: string
|
||||
example: "Repository not found"
|
||||
"409":
|
||||
description: "El tag ya existe"
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
error:
|
||||
type: string
|
||||
example: "Tag already exists"
|
||||
delete:
|
||||
summary: "Eliminar tag"
|
||||
description: |
|
||||
Elimina un tag de git
|
||||
tags:
|
||||
- "Git"
|
||||
parameters:
|
||||
- name: repository
|
||||
in: path
|
||||
required: true
|
||||
type: string
|
||||
description: "Nombre de repositorio"
|
||||
- name: tag
|
||||
in: path
|
||||
required: true
|
||||
type: string
|
||||
description: "Rama del repositorio"
|
||||
responses:
|
||||
"200":
|
||||
description: "Tag eliminado"
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
status:
|
||||
type: string
|
||||
example: deleted
|
||||
"500":
|
||||
description: "Excepción"
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
success:
|
||||
type: boolean
|
||||
example: false
|
||||
exception:
|
||||
type: string
|
||||
example: "(Exception description)"
|
||||
/ogrepository/v1/git/repositories/{repository}/branches/{branch}/commits:
|
||||
get:
|
||||
summary: "Obtener lista de commits en una rama"
|
||||
description: |
|
||||
Devuelve una lista de commits de Git.
|
||||
|
||||
**Filtrado de commits:**
|
||||
Por defecto algunos commits que no son utiles para restaurar una imagen se ocultan.
|
||||
Pasar filter_commits=0 para desactivar esta funcionalidad y ver todos los commits
|
||||
del repositorio.
|
||||
tags:
|
||||
- "Git"
|
||||
parameters:
|
||||
- name: repository
|
||||
in: path
|
||||
required: true
|
||||
type: string
|
||||
description: "Nombre de repositorio"
|
||||
- name: branch
|
||||
in: path
|
||||
required: true
|
||||
type: string
|
||||
description: "Rama dentro del repositorio"
|
||||
- name: max_commits
|
||||
in: query
|
||||
required: false
|
||||
type: int
|
||||
description: "Máximo de commits a obtener"
|
||||
- name: skip
|
||||
in: query
|
||||
required: false
|
||||
type: int
|
||||
description: "Commits a saltar (para paginación)"
|
||||
- name: filter_commits
|
||||
in: query
|
||||
required: false
|
||||
type: int
|
||||
description: "Si aplicar filtrado de commits. Por defecto 1."
|
||||
responses:
|
||||
"200":
|
||||
description: "Lista de commits"
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
commits:
|
||||
type: array
|
||||
items:
|
||||
type: object
|
||||
properties:
|
||||
committed_date:
|
||||
type: int
|
||||
example: 1745360193
|
||||
hexsha:
|
||||
type: string
|
||||
example: "db8e84d5d2548f589ee503c1c6d5003cc6a0d803"
|
||||
message:
|
||||
type: string
|
||||
example: "Install updates"
|
||||
size:
|
||||
type: int
|
||||
example: 67108864
|
||||
tags:
|
||||
type: array
|
||||
example: ["updates"]
|
||||
|
||||
"500":
|
||||
description: "Excepción"
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
success:
|
||||
type: boolean
|
||||
example: false
|
||||
exception:
|
||||
type: string
|
||||
example: "(Exception description)"
|
||||
"404":
|
||||
description: "El repositorio o branch no existe"
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
error:
|
||||
type: string
|
||||
example: "Repository not found"
|
||||
|
||||
/ogrepository/v1/git/repositories/{repository}/branches:
|
||||
get:
|
||||
summary: "Obtener lista de branches"
|
||||
description: |
|
||||
Devuelve una lista de branches de Git
|
||||
tags:
|
||||
- "Git"
|
||||
parameters:
|
||||
- name: repository
|
||||
in: path
|
||||
required: true
|
||||
type: string
|
||||
description: "Nombre de repositorio"
|
||||
responses:
|
||||
"200":
|
||||
description: "Lista de branches"
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
branches:
|
||||
type: array
|
||||
items:
|
||||
type: string
|
||||
example: main
|
||||
|
||||
"500":
|
||||
description: "Excepción"
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
success:
|
||||
type: boolean
|
||||
example: false
|
||||
exception:
|
||||
type: string
|
||||
example: "(Exception description)"
|
||||
"404":
|
||||
description: "El repositorio no existe"
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
error:
|
||||
type: string
|
||||
example: "Repository not found"
|
||||
"409":
|
||||
description: "El branch ya existe"
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
error:
|
||||
type: string
|
||||
example: "Branch already exists"
|
||||
post:
|
||||
summary: "Crear branch"
|
||||
description: |
|
||||
Crea una rama de git
|
||||
tags:
|
||||
- "Git"
|
||||
parameters:
|
||||
- name: repository
|
||||
in: path
|
||||
required: true
|
||||
type: string
|
||||
description: "Nombre de repositorio"
|
||||
- name: JSON
|
||||
in: body
|
||||
required: true
|
||||
description: |
|
||||
* **commit** - Commit al que apunta la rama nueva. Puede ser un nombre de otra rama/tag.
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
name:
|
||||
type: string
|
||||
example: devel
|
||||
required: True
|
||||
commit:
|
||||
type: string
|
||||
example: HEAD
|
||||
required: True
|
||||
responses:
|
||||
"201":
|
||||
description: "Rama creada"
|
||||
schema:
|
||||
type: array
|
||||
items:
|
||||
type: string
|
||||
example: main
|
||||
|
||||
"500":
|
||||
description: "Git no instalado"
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
success:
|
||||
type: boolean
|
||||
example: false
|
||||
exception:
|
||||
type: string
|
||||
example: "(Exception description)"
|
||||
delete:
|
||||
summary: "Eliminar branch"
|
||||
description: |
|
||||
Elimina una rama de git
|
||||
tags:
|
||||
- "Git"
|
||||
parameters:
|
||||
- name: repository
|
||||
in: path
|
||||
required: true
|
||||
type: string
|
||||
description: "Nombre de repositorio"
|
||||
- name: branch
|
||||
in: path
|
||||
required: true
|
||||
type: string
|
||||
description: "Branch del repositorio"
|
||||
responses:
|
||||
"200":
|
||||
description: "Branch eliminado"
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
status:
|
||||
type: string
|
||||
example: deleted
|
||||
"500":
|
||||
description: "Excepción"
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
success:
|
||||
type: boolean
|
||||
example: false
|
||||
exception:
|
||||
type: string
|
||||
example: "(Exception description)"
|
|
@ -1109,6 +1109,62 @@ class RepoApiTestCase(unittest.TestCase):
|
|||
self.assertIn('Error al cancelar las transmisiones P2P', response.data.decode())
|
||||
|
||||
|
||||
# ------------------------------------------------------------------- Tests "Renombrar una Imagen"
|
||||
|
||||
|
||||
@patch('repo_api.get_image_params')
|
||||
@patch('repo_api.subprocess.run')
|
||||
def test_rename_image(self, mock_subprocess, mock_get_image_params):
|
||||
""" Método de prueba del endpoint "Renombrar una Imagen".
|
||||
"""
|
||||
print("Testing endpoint 'Renombrar una Imagen'...")
|
||||
mock_get_image_params.return_value = {'name': 'test4unittest', 'extension': 'img'}
|
||||
mock_subprocess.return_value = MagicMock(returncode=0)
|
||||
response = self.app.put('/ogrepository/v1/images/rename', data=json.dumps({"ID_img":"test_image_id", "image_new_name":"new_name"}), content_type='application/json')
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.assertIn('Image renamed successfully', json.loads(response.data)['output'])
|
||||
|
||||
|
||||
@patch('repo_api.get_image_params')
|
||||
@patch('repo_api.subprocess.run')
|
||||
def test_rename_image_error500(self, mock_subprocess, mock_get_image_params):
|
||||
""" Método de prueba del endpoint "Renombrar una Imagen"
|
||||
(en caso de error "500").
|
||||
"""
|
||||
print("Testing endpoint 'Renombrar una Imagen' (error 500)...")
|
||||
mock_get_image_params.return_value = {'name': 'test4unittest', 'extension': 'img'}
|
||||
mock_subprocess.side_effect = Exception("Error al renombrar la imagen")
|
||||
response = self.app.put('/ogrepository/v1/images/rename', data=json.dumps({"ID_img":"test_image_id", "image_new_name":"new_name"}), content_type='application/json')
|
||||
self.assertEqual(response.status_code, 500)
|
||||
self.assertIn('Error al renombrar la imagen', response.data.decode())
|
||||
|
||||
|
||||
@patch('repo_api.get_image_params')
|
||||
def test_rename_image_error400_no_image(self, mock_get_image_params):
|
||||
""" Método de prueba del endpoint "Renombrar una Imagen"
|
||||
(en caso de error "400", por imagen inexistente).
|
||||
"""
|
||||
print("Testing endpoint 'Renombrar una Imagen' (error 400, no image)...")
|
||||
mock_get_image_params.return_value = None
|
||||
response = self.app.put('/ogrepository/v1/images/rename', data=json.dumps({"ID_img":"test_image_id", "image_new_name":"new_name"}), content_type='application/json')
|
||||
self.assertEqual(response.status_code, 400)
|
||||
self.assertIn('Image not found', json.loads(response.data)['error'])
|
||||
|
||||
|
||||
@patch('repo_api.check_file_exists')
|
||||
@patch('repo_api.get_image_params')
|
||||
def test_rename_image_error400_name_incorrect(self, mock_get_image_params, mock_check_file_exists):
|
||||
""" Método de prueba del endpoint "Renombrar una Imagen"
|
||||
(en caso de error "400", por nombre incorrecto).
|
||||
"""
|
||||
print("Testing endpoint 'Renombrar una Imagen' (error 400, name incorrect)...")
|
||||
mock_get_image_params.return_value = {'name': 'test4unittest', 'extension': 'img'}
|
||||
mock_check_file_exists.return_value = True
|
||||
response = self.app.put('/ogrepository/v1/images/rename', data=json.dumps({"ID_img":"test_image_id", "image_new_name":"new_name"}), content_type='application/json')
|
||||
self.assertEqual(response.status_code, 400)
|
||||
self.assertIn('There is an image with the name to assign', json.loads(response.data)['exception'])
|
||||
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------------------------
|
||||
|
||||
|
|
|
@ -134,8 +134,8 @@ def create_torrent(file_path, torrent_file, datafullsum):
|
|||
repo_ip = get_IPlocal()
|
||||
tracker_url = f"http://{repo_ip}:6969/announce"
|
||||
|
||||
# Creamos una lista con el comando para crear el torrrent, y lo imprimimos con espacios:
|
||||
splitted_cmd = f"nice -n 0 ctorrent -t {file_path} -u {tracker_url} -s {torrent_file} -c {datafullsum} -l 4194304".split()
|
||||
# Creamos una litas para ejecutar el comando mktorrent para crear el archivo torrent
|
||||
splitted_cmd = f"nice -n 0 mktorrent -a {tracker_url} -c {datafullsum} -o {torrent_file} {file_path}".split()
|
||||
print(f"Sending command: {' '.join(splitted_cmd)}")
|
||||
|
||||
# Ejecutamos el comando en el sistema, e imprimimos el resultado:
|
||||
|
|
|
@ -106,11 +106,11 @@ def main():
|
|||
total_disk, used_disk, free_disk, percent_disk = get_disk_info()
|
||||
|
||||
# Obtenemos el estado de los servicios listados, que almacenamos en un diccionario:
|
||||
service_list = ['ssh', 'smbd', 'rsync']
|
||||
service_list = ['ssh', 'smbd', 'opentracker']
|
||||
services_status = {service: get_service_status(service) for service in service_list}
|
||||
|
||||
# Obtenemos el estado de los procesos listados, que almacenamos en un diccionario:
|
||||
process_list = ['udp-sender', 'uftp', 'bttrack', 'btlaunchmany.bittornado']
|
||||
process_list = ['udp-sender', 'uftp', 'aria2c']
|
||||
process_status = {process: get_process_status(process) for process in process_list}
|
||||
|
||||
# Creamos un diccionario con toda la información obtenida:
|
||||
|
|
|
@ -0,0 +1,149 @@
|
|||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
"""
|
||||
Este script renombra la imagen especificada como primer parámetro (y todos sus archivos asociados), asignando el nombre especificado como segundo parámetro.
|
||||
|
||||
Una vez renombrados los archivos, llama al script "updateRepoInfo.py", para actualizar la información del repositorio.
|
||||
|
||||
Parámetros
|
||||
------------
|
||||
sys.argv[1] - Nombre de la imagen a renombrar (sin extensión y sin ruta).
|
||||
- Ejemplo1: Ubuntu24
|
||||
- Ejemplo2: Windows10
|
||||
|
||||
sys.argv[2] - Nuevo nombre a asignar a la imagen (sin extensión y sin ruta).
|
||||
- Ejemplo1: Ubuntu24_BKP
|
||||
- Ejemplo2: Windows10_BKP
|
||||
|
||||
Sintaxis
|
||||
----------
|
||||
./renameImage.py image_to_rename image_new_name
|
||||
|
||||
Ejemplos
|
||||
---------
|
||||
./renameImage.py Ubuntu24 Ubuntu24_BKP
|
||||
./renameImage.py Windows10 Windows10_BKP
|
||||
"""
|
||||
|
||||
# --------------------------------------------------------------------------------------------
|
||||
# IMPORTS
|
||||
# --------------------------------------------------------------------------------------------
|
||||
|
||||
import os
|
||||
import sys
|
||||
import subprocess
|
||||
from systemd import journal
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------------------------
|
||||
# VARIABLES
|
||||
# --------------------------------------------------------------------------------------------
|
||||
|
||||
script_name = os.path.basename(__file__)
|
||||
repo_path = '/opt/opengnsys/ogrepository/images/' # No borrar la barra final
|
||||
update_repo_script = '/opt/opengnsys/ogrepository/bin/updateRepoInfo.py'
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------------------------
|
||||
# FUNCTIONS
|
||||
# --------------------------------------------------------------------------------------------
|
||||
|
||||
|
||||
def show_help():
|
||||
""" Imprime la ayuda, cuando se ejecuta el script con el parámetro "help".
|
||||
"""
|
||||
help_text = f"""
|
||||
Sintaxis: {script_name} image_to_rename image_new_name
|
||||
Ejemplo1: {script_name} Ubuntu24 Ubuntu24_BKP
|
||||
Ejemplo2: {script_name} Windows10 Windows10_BKP
|
||||
"""
|
||||
print(help_text)
|
||||
|
||||
|
||||
|
||||
def check_params():
|
||||
""" Comprueba que se haya enviado la cantidad correcta de parámetros, y en el formato correcto.
|
||||
Si no es así, muestra un mensaje de error, y sale del script.
|
||||
LLama a la función "show_help" cuando se ejecuta el script con el parámetro "help".
|
||||
"""
|
||||
# Si se ejecuta el script con el parámetro "help", se muestra la ayuda, y se sale del script:
|
||||
if len(sys.argv) == 2 and sys.argv[1] == "help":
|
||||
show_help()
|
||||
sys.exit(0)
|
||||
# Si se ejecuta el script con más o menos de 2 parámetros, se muestra un error y la ayuda, y se sale del script:
|
||||
elif len(sys.argv) != 3:
|
||||
print(f"{script_name} Error: Formato incorrecto: Se debe especificar 2 parámetros")
|
||||
show_help()
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
|
||||
def rename_image(image_original_name, image_new_name):
|
||||
""" Asigna el nuevo nombre especificado a la imagen y a todos los archivos asociados.
|
||||
Al archivo ".info.checked" también le cambia la extensión a ".info",
|
||||
para poder actualizar la información del repositorio posteriormente.
|
||||
"""
|
||||
try:
|
||||
journal.send("renameImage.py: Renaming image files...", PRIORITY=journal.LOG_INFO, SYSLOG_IDENTIFIER="ogrepo-api_DEBUG")
|
||||
|
||||
# Creamos una lista con las extensiones de los archivos de la imagen (menos "info.checked"):
|
||||
extensions = ['.img', '.img.full.sum', '.img.size', '.img.sum', '.img.torrent']
|
||||
|
||||
# Renombramos cada uno de los archivos (menos "info.checked"):
|
||||
for ext in extensions:
|
||||
os.rename(f"{repo_path}{image_original_name}{ext}", f"{repo_path}{image_new_name}{ext}")
|
||||
|
||||
# Renombramos separadamente el archivo "info.checked" (porque también le cambiamos la extensión a "info"):
|
||||
os.rename(f"{repo_path}{image_original_name}.img.info.checked", f"{repo_path}{image_new_name}.img.info")
|
||||
|
||||
except Exception as error:
|
||||
journal.send(f"renameImage.py: Rename Image exception: {error}", PRIORITY=journal.LOG_ERR, SYSLOG_IDENTIFIER="ogrepo-api_DEBUG")
|
||||
sys.exit(2)
|
||||
|
||||
|
||||
|
||||
def update_repo_info():
|
||||
""" Actualiza la información del repositorio, ejecutando el script "updateRepoInfo.py".
|
||||
"""
|
||||
try:
|
||||
journal.send("renameImage.py: Running script 'updateRepoInfo.py'...", PRIORITY=journal.LOG_INFO, SYSLOG_IDENTIFIER="ogrepo-api_DEBUG")
|
||||
result = subprocess.run(['python3', update_repo_script], check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
||||
except subprocess.CalledProcessError as error:
|
||||
journal.send(f"renameImage.py: 'updateRepoInfo.py' error: {error}", PRIORITY=journal.LOG_ERR, SYSLOG_IDENTIFIER="ogrepo-api_DEBUG")
|
||||
sys.exit(3)
|
||||
except Exception as error:
|
||||
journal.send(f"renameImage.py: 'updateRepoInfo.py' exception: {error}", PRIORITY=journal.LOG_ERR, SYSLOG_IDENTIFIER="ogrepo-api_DEBUG")
|
||||
sys.exit(4)
|
||||
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------------------------
|
||||
# MAIN
|
||||
# --------------------------------------------------------------------------------------------
|
||||
|
||||
|
||||
def main():
|
||||
"""
|
||||
"""
|
||||
# Evaluamos si se ha enviado la cantidad correcta de parámetros, y en el formato correcto:
|
||||
check_params()
|
||||
|
||||
# Almacenamos el nombre original de la imagen, y el nuevo nombre a asignar (desde los parámetros):
|
||||
image_original_name = sys.argv[1]
|
||||
image_new_name = sys.argv[2]
|
||||
|
||||
# Renombramos la imagen y sus archivos asociados:
|
||||
rename_image(image_original_name, image_new_name)
|
||||
|
||||
# Actualizamos la información del repositorio, ejecutando el script "updateRepoInfo.py":
|
||||
update_repo_info()
|
||||
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------------------------
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
||||
# --------------------------------------------------------------------------------------------
|
|
@ -16,6 +16,8 @@ No recibe ningún parámetro.
|
|||
import os
|
||||
import sys
|
||||
import subprocess
|
||||
import psutil
|
||||
import re
|
||||
from systemd import journal
|
||||
|
||||
|
||||
|
@ -31,29 +33,73 @@ repo_path = '/opt/opengnsys/ogrepository/images' # En este caso, no lleva barra
|
|||
# --------------------------------------------------------------------------------------------
|
||||
|
||||
|
||||
def run_bittornado(repo_path):
|
||||
""" Ejecuta el comando "btlaunchmany.bittornado", con sus parámetros correspondientes.
|
||||
Además, captura el resultado y los posibles errores, y los imprime.
|
||||
"""
|
||||
# Creamos una lista con el comando "btlaunchmany.bittornado" y sus parámetros, y lo imprimimos con espacios:
|
||||
splitted_cmd = f"btlaunchmany.bittornado {repo_path}".split()
|
||||
print(f"Sending command: {' '.join(splitted_cmd)}")
|
||||
journal.send(f"runTorrentSeeder.py: Running command: {' '.join(splitted_cmd)}", PRIORITY=journal.LOG_INFO, SYSLOG_IDENTIFIER="ogrepo-api_DEBUG")
|
||||
|
||||
# Ejecutamos el comando "btlaunchmany.bittornado" en el sistema, e imprimimos el resultado:
|
||||
# def run_bittornado(repo_path):
|
||||
# """ Ejecuta el comando "btlaunchmany.bittornado", con sus parámetros correspondientes.
|
||||
# Además, captura el resultado y los posibles errores, y los imprime.
|
||||
# """
|
||||
# # Creamos una lista con el comando "btlaunchmany.bittornado" y sus parámetros, y lo imprimimos con espacios:
|
||||
# splitted_cmd = f"btlaunchmany.bittornado {repo_path}".split()
|
||||
# print(f"Sending command: {' '.join(splitted_cmd)}")
|
||||
# journal.send(f"runTorrentSeeder.py: Running command: {' '.join(splitted_cmd)}", PRIORITY=journal.LOG_INFO, SYSLOG_IDENTIFIER="ogrepo-api_DEBUG")
|
||||
|
||||
# # Ejecutamos el comando "btlaunchmany.bittornado" en el sistema, e imprimimos el resultado:
|
||||
# try:
|
||||
# result = subprocess.run(splitted_cmd, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
||||
# journal.send(f"runTorrentSeeder.py: Command ReturnCode: {result.returncode}", PRIORITY=journal.LOG_INFO, SYSLOG_IDENTIFIER="ogrepo-api_DEBUG")
|
||||
# print(f"Bittornado ReturnCode: {result.returncode}")
|
||||
# except subprocess.CalledProcessError as error:
|
||||
# journal.send("runTorrentSeeder.py: Process finalized", PRIORITY=journal.LOG_WARNING, SYSLOG_IDENTIFIER="ogrepo-api_DEBUG")
|
||||
# print(f"Bittornado ReturnCode: {error.returncode}")
|
||||
# print(f"Bittornado Error Output: {error.stderr.decode()}")
|
||||
# except Exception as error:
|
||||
# journal.send(f"runTorrentSeeder.py: Command exception: {error}", PRIORITY=journal.LOG_ERR, SYSLOG_IDENTIFIER="ogrepo-api_DEBUG")
|
||||
# print(f"Unexpected bittornado error: {error}")
|
||||
|
||||
|
||||
|
||||
def run_aria2c_seeder(image_name):
|
||||
"""Lanza aria2c como seeder puro para una imagen concreta ya existente."""
|
||||
|
||||
repo_path = '/opt/opengnsys/ogrepository/images'
|
||||
torrent_file = os.path.join(repo_path, f"{image_name}.img.torrent")
|
||||
image_file = os.path.join(repo_path, f"{image_name}.img")
|
||||
|
||||
# Verificación básica
|
||||
if not os.path.exists(torrent_file):
|
||||
print(f"Torrent file not found: {torrent_file}")
|
||||
journal.send(f"Seeder error: Torrent file not found: {torrent_file}",
|
||||
PRIORITY=journal.LOG_ERR, SYSLOG_IDENTIFIER="ogrepo-api")
|
||||
return
|
||||
|
||||
if not os.path.exists(image_file):
|
||||
print(f"Image file not found: {image_file}")
|
||||
journal.send(f"Seeder error: Image file not found: {image_file}",
|
||||
PRIORITY=journal.LOG_ERR, SYSLOG_IDENTIFIER="ogrepo-api")
|
||||
return
|
||||
|
||||
# Comando aria2c como seeder puro
|
||||
cmd = [
|
||||
'aria2c',
|
||||
'--enable-peer-exchange=true',
|
||||
'--bt-seed-unverified=true',
|
||||
'--check-integrity=true',
|
||||
'--seed-ratio=0.0',
|
||||
'--dir=' + repo_path,
|
||||
torrent_file
|
||||
]
|
||||
|
||||
journal.send(f"Launching aria2c seeder for {image_name}",
|
||||
PRIORITY=journal.LOG_INFO, SYSLOG_IDENTIFIER="ogrepo-api")
|
||||
journal.send(f"Command: {' '.join(cmd)}",
|
||||
PRIORITY=journal.LOG_INFO, SYSLOG_IDENTIFIER="ogrepo-api")
|
||||
print("Running command:", ' '.join(cmd))
|
||||
try:
|
||||
result = subprocess.run(splitted_cmd, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
||||
journal.send(f"runTorrentSeeder.py: Command ReturnCode: {result.returncode}", PRIORITY=journal.LOG_INFO, SYSLOG_IDENTIFIER="ogrepo-api_DEBUG")
|
||||
print(f"Bittornado ReturnCode: {result.returncode}")
|
||||
except subprocess.CalledProcessError as error:
|
||||
journal.send("runTorrentSeeder.py: Process finalized", PRIORITY=journal.LOG_WARNING, SYSLOG_IDENTIFIER="ogrepo-api_DEBUG")
|
||||
print(f"Bittornado ReturnCode: {error.returncode}")
|
||||
print(f"Bittornado Error Output: {error.stderr.decode()}")
|
||||
except Exception as error:
|
||||
journal.send(f"runTorrentSeeder.py: Command exception: {error}", PRIORITY=journal.LOG_ERR, SYSLOG_IDENTIFIER="ogrepo-api_DEBUG")
|
||||
print(f"Unexpected bittornado error: {error}")
|
||||
|
||||
|
||||
subprocess.run(cmd, check=True)
|
||||
except subprocess.CalledProcessError as e:
|
||||
journal.send(f"aria2c seeder failed: {e}",
|
||||
PRIORITY=journal.LOG_ERR, SYSLOG_IDENTIFIER="ogrepo-api")
|
||||
print(f"Seeder process exited with code {e.returncode}")
|
||||
|
||||
# --------------------------------------------------------------------------------------------
|
||||
# MAIN
|
||||
|
@ -64,16 +110,40 @@ def main():
|
|||
"""
|
||||
"""
|
||||
# Finalizamos el proceso "btlaunchmany.bittornado" (en caso de que estuviera corriendo):
|
||||
try:
|
||||
journal.send("runTorrentSeeder.py: Killing process 'btlaunchmany.bittornado'...", PRIORITY=journal.LOG_INFO, SYSLOG_IDENTIFIER="ogrepo-api_DEBUG")
|
||||
subprocess.run(f"pkill btlaunchmany".split(), check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
||||
except Exception as error_description:
|
||||
journal.send("runTorrentSeeder.py: No 'btlaunchmany.bittornado' process running", PRIORITY=journal.LOG_INFO, SYSLOG_IDENTIFIER="ogrepo-api_DEBUG")
|
||||
print(f"No btlaunchmany.bittornado process running? Returned error: {error_description}")
|
||||
if len(sys.argv) != 2:
|
||||
print("Usage: runTorrentSeeder.py <image_name>")
|
||||
journal.send("runTorrentSeeder.py: Invalid number of arguments. Expected 1 argument: <image_name>",
|
||||
PRIORITY=journal.LOG_ERR, SYSLOG_IDENTIFIER="ogrepo-api_DEBUG")
|
||||
sys.exit(1)
|
||||
|
||||
image_name = sys.argv[1]
|
||||
torrent_file = os.path.join(repo_path, f"{image_name}.img.torrent")
|
||||
found = False
|
||||
# Matamos los procesos de aria2c que sirvan la imagen en concreto. Chequeamos todos los procesos
|
||||
|
||||
# Ejecutamos el comando "btlaunchmany.bittornado" (para hacer seed de los torrents):
|
||||
run_bittornado(repo_path)
|
||||
journal.send(f"runTorrentSeeder.py: looking for aria2c processes for {image_name}.torrent",
|
||||
PRIORITY=journal.LOG_INFO, SYSLOG_IDENTIFIER="ogrepo-api_DEBUG")
|
||||
for proc in psutil.process_iter(['pid','name','cmdline']):
|
||||
try:
|
||||
if proc.info['name'] != 'aria2c':
|
||||
continue
|
||||
|
||||
if any(arg.endswith(torrent_file) for arg in proc.info['cmdline']):
|
||||
proc.terminate()
|
||||
found = True
|
||||
print(f"Killed aria2c process with PID {proc.info['pid']} for {image_name}.torrent")
|
||||
journal.send(f"runTorrentSeeder.py: Killed aria2c process with PID {proc.info['pid']} for {image_name}.torrent",
|
||||
PRIORITY=journal.LOG_INFO, SYSLOG_IDENTIFIER="ogrepo-api_DEBUG")
|
||||
except (psutil.NoSuchProcess, psutil.AccessDenied):
|
||||
continue
|
||||
|
||||
if not found:
|
||||
print(f"No aria2c process found for {image_name}.torrent")
|
||||
journal.send(f"runTorrentSeeder.py: No aria2c process found for {image_name}.torrent",
|
||||
PRIORITY=journal.LOG_INFO, SYSLOG_IDENTIFIER="ogrepo-api_DEBUG")
|
||||
|
||||
# Lanzamos aria2c como seeder para la imagen proporcionada
|
||||
run_aria2c_seeder(image_name)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------------------------
|
||||
|
|
|
@ -1,3 +1,43 @@
|
|||
ogrepository (1.1.5) UNRELEASED; urgency=medium
|
||||
|
||||
* refs #2363 Fix breaking forgejo permissions
|
||||
|
||||
-- OpenGnsys <opengnsys@opengnsys.com> Tue, 1 Jul 2025 16:05:12 +0000
|
||||
|
||||
ogrepository (1.1.4) UNRELEASED; urgency=medium
|
||||
|
||||
* refs #2363 Reduce number of required dependencies
|
||||
|
||||
-- OpenGnsys <opengnsys@opengnsys.com> Tue, 30 Jun 2025 15:50:11 +0000
|
||||
|
||||
ogrepository (1.1.3) UNRELEASED; urgency=medium
|
||||
|
||||
* refs #2317 Fix performance problems, remove stats
|
||||
* refs #2298 Add commmits endpoint
|
||||
|
||||
-- OpenGnsys <opengnsys@opengnsys.com> Tue, 30 Jun 2025 15:50:11 +0000
|
||||
|
||||
|
||||
ogrepository (1.1.2) UNRELEASED; urgency=medium
|
||||
|
||||
* Fix path handling when there are no repositories
|
||||
* Add another search path for installer module
|
||||
* Fix path handling
|
||||
* Add SSH key endpoint
|
||||
* Update dependencies
|
||||
|
||||
-- OpenGnsys <opengnsys@opengnsys.com> Tue, 30 Jun 2025 15:20:23 +0000
|
||||
|
||||
ogrepository (1.1.1) unstable; urgency=medium
|
||||
* OgGit - fix repo path handling
|
||||
|
||||
-- Tu Nombre <tuemail@example.com> Jue, 5 Jun 2025 08:43:58 +0000
|
||||
|
||||
ogrepository (1.1.0) unstable; urgency=medium
|
||||
* OgGit
|
||||
|
||||
-- Tu Nombre <tuemail@example.com> Tue, 11 Mar 2025 04:43:58 +0000
|
||||
|
||||
ogrepository (1.0.0+deb-packages20250311-1) unstable; urgency=medium
|
||||
|
||||
* First debian version
|
||||
|
|
|
@ -8,6 +8,7 @@ Build-Depends: debhelper-compat (= 12)
|
|||
Package: ogrepository
|
||||
Architecture: all
|
||||
Pre-Depends: debian-archive-keyring , debconf (>= 1.5.0),
|
||||
Depends: ${misc:Depends}, git, python3, python3-pip, python3-flask, python3-paramiko, python3-psutil, python3-flasgger, samba, gunicorn, wakeonlan , lzop , partclone , qemu-utils , udpcast
|
||||
Depends: ${misc:Depends}, git, python3, python3-pip, python3-flask, python3-paramiko, python3-psutil, python3-flasgger, samba, gunicorn, wakeonlan , lzop , partclone , qemu-utils , udpcast, uftp, mktorrent, aria2 , opengnsys-opentracker, opengnsys-forgejo, python3-git
|
||||
Description: Ogrepsoitory Package
|
||||
This package provides Ogrepsoitory service.
|
||||
This package provides Ogrepository service.
|
||||
|
||||
|
|
|
@ -1,10 +1,29 @@
|
|||
#!/bin/sh
|
||||
|
||||
set -e
|
||||
set -x
|
||||
set -x
|
||||
|
||||
. /usr/share/debconf/confmodule
|
||||
|
||||
restore_config_if_modified() {
|
||||
local new="$1"
|
||||
local backup="$1.bak.upgrade_package"
|
||||
|
||||
if [ -f "$backup" ]; then
|
||||
if ! cmp -s "$new" "$backup"; then
|
||||
echo ">>> Archivo modificado por el usuario detectado en $new"
|
||||
echo " - Guardando archivo nuevo como ${new}.new"
|
||||
mv -f "$new" "${new}.new"
|
||||
echo " - Restaurando archivo anterior desde backup"
|
||||
mv -f "$backup" "$new"
|
||||
else
|
||||
echo ">>> El archivo $new no ha cambiado desde la última versión, eliminando backup"
|
||||
rm -f "$backup"
|
||||
fi
|
||||
fi
|
||||
}
|
||||
|
||||
|
||||
# Cargar variables de configuración
|
||||
db_get opengnsys/ogrepository_ogrepoIp
|
||||
OGREPO_IP="$RET"
|
||||
|
@ -19,10 +38,20 @@ SAMBA_PASS="$RET"
|
|||
USER="opengnsys"
|
||||
|
||||
|
||||
# Provisionar base de datos si es necesario en caso de instalación.
|
||||
# Provisionar base de datos si es necesario en caso de instalación.
|
||||
|
||||
|
||||
# Detectar si es una instalación nueva o una actualización
|
||||
# if [ "$1" = "configure" ] && [ -z "$2" ]; then
|
||||
# systemd-run --no-block /bin/bash -c "
|
||||
# sleep 10;
|
||||
# apt update -y;
|
||||
# for pkg in bittorrent bittornado ctorrent; do
|
||||
# if ! dpkg -l | grep -qw \"\$pkg\"; then
|
||||
# apt install -y \"\$pkg\"
|
||||
# fi
|
||||
# done
|
||||
# "
|
||||
if [ "$1" = "configure" ] && [ -z "$2" ]; then
|
||||
systemd-run --no-block /bin/bash -c "
|
||||
sleep 10;
|
||||
|
@ -33,7 +62,7 @@ for pkg in bittorrent bittornado ctorrent; do
|
|||
fi
|
||||
done
|
||||
"
|
||||
|
||||
|
||||
sed -i "s/%%OGREPOSITORY_USER%%/$SAMBA_USER/g" /etc/systemd/system/ogrepo-api.service
|
||||
sed -i "s/%%OGREPOSITORY_USER%%/$SAMBA_USER/g" /etc/samba/ogrepo-smb.conf
|
||||
|
||||
|
@ -45,30 +74,72 @@ done
|
|||
# Copy ssh keys
|
||||
cp /opt/opengnsys/ogrepository/etc/opengnsys $OPENGNSYS_HOME/.ssh/id_ed25519
|
||||
cp /opt/opengnsys/ogrepository/etc/opengnsys.pub $OPENGNSYS_HOME/.ssh/id_ed25519.pub
|
||||
# Change permissions
|
||||
chmod 700 $OPENGNSYS_HOME/.ssh
|
||||
chmod 600 $OPENGNSYS_HOME/.ssh/id_ed25519
|
||||
chmod 644 $OPENGNSYS_HOME/.ssh/id_ed25519.pub
|
||||
# Genera authorized_keys
|
||||
cat $OPENGNSYS_HOME/.ssh/id_ed25519.pub >> $OPENGNSYS_HOME/.ssh/authorized_keys
|
||||
chmod 600 $OPENGNSYS_HOME/.ssh/authorized_keys
|
||||
chown -R opengnsys:opengnsys $OPENGNSYS_HOME/.ssh
|
||||
|
||||
if [ -f /etc/samba/smb.conf ]; then
|
||||
dpkg-divert --package ogrepository --add --rename --divert /etc/samba/smb.conf.orig /etc/samba/smb.conf
|
||||
cp /etc/samba/smb.conf.orig /etc/samba/smb.conf
|
||||
if ! grep -q "include = /etc/samba/ogrepo-smb.conf" /etc/samba/smb.conf; then
|
||||
echo "include = /etc/samba/ogrepo-smb.conf" >> /etc/samba/smb.conf
|
||||
fi
|
||||
(echo "$SAMBA_PASS"; echo "$SAMBA_PASS") | smbpasswd -a $SAMBA_USER
|
||||
fi
|
||||
# Incluir el archivo de configuración de samba si no está incluido ya
|
||||
if ! grep -q "include = /etc/samba/ogrepo-smb.conf" /etc/samba/smb.conf; then
|
||||
echo "include = /etc/samba/ogrepo-smb.conf" >> /etc/samba/smb.conf
|
||||
fi
|
||||
|
||||
(echo "$SAMBA_PASS"; echo "$SAMBA_PASS") | smbpasswd -a $SAMBA_USER
|
||||
|
||||
# Configure Repo
|
||||
systemctl enable ogrepo-api
|
||||
# Configure Repo
|
||||
|
||||
cp /opt/opengnsys/ogrepository/etc/ogAdmRepo.cfg.tmpl /opt/opengnsys/ogrepository/etc/ogAdmRepo.cfg
|
||||
sed -i "s/SERVERIP/$OGREPO_IP/g" /opt/opengnsys/ogrepository/etc/ogAdmRepo.cfg
|
||||
sed -i "s/OGCOREIP/$OGCORE_IP/g" /opt/opengnsys/ogrepository/etc/ogAdmRepo.cfg
|
||||
|
||||
# Copiar sudoers file ogrepository/etc/opengnsys-repository
|
||||
cp /opt/opengnsys/ogrepository/etc/opengnsys-repository /etc/sudoers.d/opengnsys
|
||||
elif [ "$1" = "configure" ] && [ -n "$2" ]; then
|
||||
echo "Actualización desde la versión $2"
|
||||
# Recopy static files without configuration
|
||||
cp /opt/opengnsys/ogrepository/etc/opengnsys-repository /etc/sudoers.d/opengnsys-repository
|
||||
OPENGNSYS_HOME=$(getent passwd opengnsys | cut -d: -f6)
|
||||
# Create .ssh directory
|
||||
mkdir -p $OPENGNSYS_HOME/.ssh
|
||||
# Copy ssh keys
|
||||
cp /opt/opengnsys/ogrepository/etc/opengnsys $OPENGNSYS_HOME/.ssh/id_ed25519
|
||||
cp /opt/opengnsys/ogrepository/etc/opengnsys.pub $OPENGNSYS_HOME/.ssh/id_ed25519.pub
|
||||
cat $OPENGNSYS_HOME/.ssh/id_ed25519.pub >> $OPENGNSYS_HOME/.ssh/authorized_keys
|
||||
|
||||
restore_config_if_modified "/opt/opengnsys/ogrepository/etc/ogAdmRepo.cfg"
|
||||
restore_config_if_modified "/opt/opengnsys/ogrepository/etc/repoinfo.json"
|
||||
restore_config_if_modified "/opt/opengnsys/ogrepository/etc/trashinfo.json"
|
||||
restore_config_if_modified "/etc/samba/smb.conf"
|
||||
restore_config_if_modified "/etc/samba/ogrepo-smb.conf"
|
||||
restore_config_if_modified "/etc/sudoers.d/opengnsys-repository"
|
||||
|
||||
|
||||
fi
|
||||
|
||||
# Cambiar la propiedad de los archivos al usuario especificado
|
||||
chown opengnsys:www-data /opt/opengnsys/
|
||||
chown -R opengnsys:www-data /opt/opengnsys/ogrepository
|
||||
chmod 755 /opt/opengnsys
|
||||
chmod 755 /opt/opengnsys/ogrepository/bin/*
|
||||
|
||||
# oggit -- these are from opengnsys-forgejo, and we're overwriting their
|
||||
# permissions above.
|
||||
#
|
||||
# Check if the paths exist just in case the opengnsys-forgejo package
|
||||
# stops being a dependency.
|
||||
if [ -d "/opt/opengnsys/ogrepository/var/lib/forgejo/" ] ; then
|
||||
chown -R oggit:oggit /opt/opengnsys/ogrepository/var/lib/forgejo/
|
||||
fi
|
||||
|
||||
if [ -d "/opt/opengnsys/ogrepository/oggit/" ] ; then
|
||||
chown -R oggit:oggit /opt/opengnsys/ogrepository/oggit/
|
||||
fi
|
||||
|
||||
# Install http server stuff
|
||||
# Reiniciar servicios si es necesario
|
||||
|
|
|
@ -2,19 +2,13 @@
|
|||
|
||||
set -e
|
||||
|
||||
|
||||
NGINX_FILE="/etc/nginx/sites-enabled/oggui.conf"
|
||||
UNIT_FILE="/etc/systemd/system/oggui.service"
|
||||
UNIT_FILE="/etc/systemd/system/ogrepo-api.service"
|
||||
|
||||
|
||||
case "$1" in
|
||||
remove)
|
||||
echo "El paquete se está desinstalando..."
|
||||
# Aquí puedes hacer limpieza de archivos o servicios
|
||||
if [ -L "$NGINX_FILE" ]; then
|
||||
rm -f "$NGINX_FILE"
|
||||
systemctl restart nginx
|
||||
fi
|
||||
if [ -L "$UNIT_FILE" ]; then
|
||||
rm -f "$UNIT_FILE"
|
||||
systemctl daemon-reload
|
||||
|
|
|
@ -2,8 +2,18 @@
|
|||
|
||||
set -e
|
||||
|
||||
KEY_FILE="/usr/share/keyrings/debian-archive-buster-stable.gpg"
|
||||
REPO_FILE="/etc/apt/sources.list.d/buster.list"
|
||||
backup_file_if_exists() {
|
||||
local original="$1"
|
||||
local backup="$1.bak.upgrade_package"
|
||||
|
||||
if [ -e "$original" ]; then
|
||||
echo " - Guardando backup de $original en $backup"
|
||||
cp -a "$original" "$backup"
|
||||
fi
|
||||
}
|
||||
|
||||
# KEY_FILE="/usr/share/keyrings/debian-archive-buster-stable.gpg"
|
||||
# REPO_FILE="/etc/apt/sources.list.d/buster.list"
|
||||
|
||||
# Asegurarse de que el usuario exista
|
||||
USER="opengnsys"
|
||||
|
@ -20,10 +30,17 @@ echo "Añadiendo el repositorio de Debian Buster en $REPO_FILE..."
|
|||
mkdir -p "$(dirname "$REPO_FILE")"
|
||||
|
||||
# Crear el archivo de repositorio si no existe
|
||||
if [ ! -f "$REPO_FILE" ]; then
|
||||
echo "deb [signed-by=$KEY_FILE] http://ftp.de.debian.org/debian buster main" > "$REPO_FILE"
|
||||
else
|
||||
echo "El repositorio ya está configurado en $REPO_FILE"
|
||||
fi
|
||||
# if [ ! -f "$REPO_FILE" ]; then
|
||||
# echo "deb [signed-by=$KEY_FILE] http://ftp.de.debian.org/debian buster main" > "$REPO_FILE"
|
||||
# else
|
||||
# echo "El repositorio ya está configurado en $REPO_FILE"
|
||||
# fi
|
||||
|
||||
backup_file_if_exists "/opt/opengnsys/ogrepository/etc/ogAdmRepo.cfg"
|
||||
backup_file_if_exists "/opt/opengnsys/ogrepository/etc/repoinfo.json"
|
||||
backup_file_if_exists "/opt/opengnsys/ogrepository/etc/trashinfo.json"
|
||||
backup_file_if_exists "/etc/samba/smb.conf"
|
||||
backup_file_if_exists "/etc/samba/ogrepo-smb.conf"
|
||||
backup_file_if_exists "/etc/sudoers.d/ogrepository"
|
||||
|
||||
exit 0
|
||||
|
|
|
@ -44,11 +44,18 @@ case "$1" in
|
|||
rm -f /var/lib/dpkg/info/ogrepository.post-invoke
|
||||
fi
|
||||
|
||||
# Remove sudoers file
|
||||
if [ -f /etc/sudoers.d/opengnsys-repository ]; then
|
||||
echo "Removing sudoers file..."
|
||||
rm -f /etc/sudoers.d/opengnsys-repository
|
||||
fi
|
||||
|
||||
echo "Limpieza completada."
|
||||
;;
|
||||
|
||||
upgrade|deconfigure)
|
||||
# No hacer nada en actualización o desconfiguración
|
||||
|
||||
;;
|
||||
|
||||
*)
|
||||
|
|
|
@ -0,0 +1,31 @@
|
|||
# Variables para facilitar la lectura
|
||||
Cmnd_Alias MOUNT_RECOVERY = \
|
||||
/usr/bin/mkdir -p /mnt/recovery, \
|
||||
/usr/bin/mount /dev/* /mnt/recovery, \
|
||||
/usr/bin/mount --bind /dev /mnt/recovery/dev, \
|
||||
/usr/bin/mount --bind /proc /mnt/recovery/proc, \
|
||||
/usr/bin/mount --bind /sys /mnt/recovery/sys, \
|
||||
/usr/bin/umount /mnt/recovery/dev, \
|
||||
/usr/bin/umount /mnt/recovery/proc, \
|
||||
/usr/bin/umount /mnt/recovery/sys, \
|
||||
/usr/bin/umount -l /mnt/recovery
|
||||
|
||||
Cmnd_Alias CHROOT_GRUB = \
|
||||
/usr/sbin/chroot /mnt/recovery /usr/sbin/grub-install --target=i386-pc *, \
|
||||
/usr/sbin/chroot /mnt/recovery /usr/sbin/grub-mkconfig -o /boot/grub/grub.cfg
|
||||
|
||||
Cmnd_Alias LOOP_KPARTX = \
|
||||
/usr/sbin/losetup -d *, \
|
||||
/usr/sbin/kpartx -av /opt/opengnsys/ogrepository/images_virtual/*, \
|
||||
/usr/sbin/kpartx -d /opt/opengnsys/ogrepository/images_virtual/*, \
|
||||
/usr/sbin/blkid /dev/mapper/*
|
||||
|
||||
Cmnd_Alias KILL_BT = \
|
||||
/usr/bin/pkill -9 btlaunchmany, \
|
||||
/usr/bin/pkill -9 bttrack, \
|
||||
/usr/bin/kill -9 *
|
||||
|
||||
Cmnd_Alias PYTHON_OGREPO = /usr/bin/python3 /opt/opengnsys/ogrepository/bin/*
|
||||
|
||||
# Permitir al usuario opengnsys ejecutar estos comandos sin contraseña
|
||||
opengnsys ALL=(root) NOPASSWD: MOUNT_RECOVERY, CHROOT_GRUB, LOOP_KPARTX, KILL_BT, PYTHON_OGREPO
|
|
@ -3,8 +3,8 @@ Description=Gunicorn instance to serve repo_api
|
|||
After=network.target
|
||||
|
||||
[Service]
|
||||
User=%%OGREPOSITORY_USER%%
|
||||
Group=%%OGREPOSITORY_USER%%
|
||||
User=opengnsys
|
||||
Group=opengnsys
|
||||
WorkingDirectory=/opt/opengnsys/ogrepository/api
|
||||
ExecStart=/usr/bin/gunicorn -w 4 -b 0.0.0.0:8006 repo_api:app
|
||||
|
||||
|
|
Loading…
Reference in New Issue