ajoute la liaison Laravel-OpenStack et le modèle Heat du lab 08
Un gabarit Heat généré depuis chaque lab.yaml, une stack par session de lab (création à l'admission, suppression à l'expiration via des jobs Redis et un worker systemd dédié). Passage du compte de service à une authentification par mot de passe : Heat refuse de créer un trust à partir d'un jeton d'application credential (voir ADR 0002). Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
parent
8742bde807
commit
67a754f733
34 changed files with 1095 additions and 91 deletions
31
portail/app/Console/Commands/ExpirerSessionsLab.php
Normal file
31
portail/app/Console/Commands/ExpirerSessionsLab.php
Normal file
|
|
@ -0,0 +1,31 @@
|
|||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Jobs\SupprimerStackLab;
|
||||
use App\Models\LabSession;
|
||||
use Illuminate\Console\Command;
|
||||
|
||||
/**
|
||||
* Expiration automatique des sessions de lab (étape 10). Planifiée dans
|
||||
* routes/console.php, lancée chaque minute par le cron système (Ansible).
|
||||
*/
|
||||
class ExpirerSessionsLab extends Command
|
||||
{
|
||||
protected $signature = 'labs:expirer-sessions';
|
||||
|
||||
protected $description = "Dispatche SupprimerStackLab pour les sessions de lab dont l'expiration est passée";
|
||||
|
||||
public function handle(): void
|
||||
{
|
||||
$sessions = LabSession::whereIn('etat', [LabSession::ADMIS, LabSession::ACTIF])
|
||||
->where('expire_a', '<', now())
|
||||
->get();
|
||||
|
||||
foreach ($sessions as $session) {
|
||||
SupprimerStackLab::dispatch($session);
|
||||
}
|
||||
|
||||
$this->info("{$sessions->count()} session(s) de lab expirée(s), suppression lancée.");
|
||||
}
|
||||
}
|
||||
|
|
@ -3,6 +3,7 @@
|
|||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Models\LabSession;
|
||||
use App\Models\LabSessionMachine;
|
||||
use App\Models\Seance;
|
||||
use App\Services\OpenStack\JetonConsole;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
|
|
@ -11,34 +12,33 @@ use Illuminate\Support\Facades\Auth;
|
|||
/**
|
||||
* Émet des jetons de console série à usage court (étape 9) : le navigateur
|
||||
* ne reçoit jamais l'adresse de nova-serialproxy, seulement un jeton Redis
|
||||
* valable 5 minutes. L'élève peut écrire dans sa propre VM ; le prof ne
|
||||
* peut que regarder celle d'un élève de sa classe.
|
||||
* valable 5 minutes. L'élève peut écrire dans ses propres VM ; le prof ne
|
||||
* peut que regarder celles d'un élève de sa classe (étape 10 : une session
|
||||
* de lab a plusieurs machines, voir LabSessionMachine).
|
||||
*/
|
||||
class ConsoleController extends Controller
|
||||
{
|
||||
public function __construct(private readonly JetonConsole $jetons) {}
|
||||
|
||||
public function pourEleve(LabSession $labSession): JsonResponse
|
||||
public function pourEleve(LabSession $labSession, LabSessionMachine $labSessionMachine): JsonResponse
|
||||
{
|
||||
$eleve = Auth::guard('eleve')->user();
|
||||
abort_if($labSession->eleve_id !== $eleve->id, 403);
|
||||
abort_if($labSession->etat !== LabSession::ADMIS, 403, 'En attente d\'admission.');
|
||||
abort_if($labSession->stack_id === null, 404, 'Aucune VM associée à cette session.');
|
||||
abort_if($labSessionMachine->lab_session_id !== $labSession->id, 404);
|
||||
|
||||
return response()->json([
|
||||
'jeton' => $this->jetons->pourEcriture($labSession->stack_id),
|
||||
'jeton' => $this->jetons->pourEcriture($labSessionMachine->instance_id),
|
||||
]);
|
||||
}
|
||||
|
||||
public function pourProf(Seance $seance, LabSession $labSession): JsonResponse
|
||||
public function pourProf(Seance $seance, LabSession $labSession, LabSessionMachine $labSessionMachine): JsonResponse
|
||||
{
|
||||
abort_if($seance->classe->user_id !== Auth::guard('web')->id(), 403);
|
||||
abort_if($labSession->seance_id !== $seance->id, 404);
|
||||
abort_if($labSession->etat !== LabSession::ADMIS, 403, 'Élève pas encore admis.');
|
||||
abort_if($labSession->stack_id === null, 404, 'Aucune VM associée à cette session.');
|
||||
abort_if($labSessionMachine->lab_session_id !== $labSession->id, 404);
|
||||
|
||||
return response()->json([
|
||||
'jeton' => $this->jetons->pourLecture($labSession->stack_id),
|
||||
'jeton' => $this->jetons->pourLecture($labSessionMachine->instance_id),
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@
|
|||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Jobs\CreerStackLab;
|
||||
use App\Models\Classe;
|
||||
use App\Models\LabSession;
|
||||
use App\Models\Seance;
|
||||
|
|
@ -34,7 +35,7 @@ class SeanceController extends Controller
|
|||
abort_if($seance->classe->user_id !== Auth::guard('web')->id(), 403);
|
||||
|
||||
return view('seances.attente', [
|
||||
'seance' => $seance->load(['classe', 'lab', 'labSessions.eleve']),
|
||||
'seance' => $seance->load(['classe', 'lab', 'labSessions.eleve', 'labSessions.machines']),
|
||||
]);
|
||||
}
|
||||
|
||||
|
|
@ -45,16 +46,27 @@ class SeanceController extends Controller
|
|||
|
||||
return view('seances.console-prof', [
|
||||
'seance' => $seance->load('lab'),
|
||||
'labSession' => $labSession->load('eleve'),
|
||||
'labSession' => $labSession->load(['eleve', 'machines']),
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Admettre un élève, c'est lancer son lab : la stack Heat se construit
|
||||
* en tâche de fond (étape 10), le terminal apparaît une fois prête.
|
||||
*/
|
||||
public function admettre(Seance $seance, LabSession $labSession): RedirectResponse
|
||||
{
|
||||
abort_if($seance->classe->user_id !== Auth::guard('web')->id(), 403);
|
||||
abort_if($labSession->seance_id !== $seance->id, 404);
|
||||
|
||||
$labSession->update(['etat' => LabSession::ADMIS]);
|
||||
$dureeMinutes = $labSession->lab->duree_min ?? 45;
|
||||
|
||||
$labSession->update([
|
||||
'etat' => LabSession::ADMIS,
|
||||
'expire_a' => now()->addMinutes($dureeMinutes),
|
||||
]);
|
||||
|
||||
CreerStackLab::dispatch($labSession);
|
||||
|
||||
return redirect()->route('seances.attente', $seance);
|
||||
}
|
||||
|
|
|
|||
81
portail/app/Jobs/CreerStackLab.php
Normal file
81
portail/app/Jobs/CreerStackLab.php
Normal file
|
|
@ -0,0 +1,81 @@
|
|||
<?php
|
||||
|
||||
namespace App\Jobs;
|
||||
|
||||
use App\Models\LabSession;
|
||||
use App\Services\Labs\DefinitionLab;
|
||||
use App\Services\OpenStack\GenerateurTemplateHeat;
|
||||
use App\Services\OpenStack\HeatClient;
|
||||
use Illuminate\Bus\Queueable;
|
||||
use Illuminate\Contracts\Queue\ShouldQueue;
|
||||
use Illuminate\Foundation\Bus\Dispatchable;
|
||||
use Illuminate\Queue\InteractsWithQueue;
|
||||
use Illuminate\Queue\SerializesModels;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
/**
|
||||
* Lance la stack Heat d'un lab pour un élève admis (étape 10). Dispatché par
|
||||
* SeanceController::admettre — « admettre » un élève, c'est lancer son lab.
|
||||
*/
|
||||
class CreerStackLab implements ShouldQueue
|
||||
{
|
||||
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
|
||||
|
||||
public int $tries = 1;
|
||||
|
||||
public function __construct(private readonly LabSession $labSession) {}
|
||||
|
||||
public function handle(GenerateurTemplateHeat $generateur, HeatClient $heat): void
|
||||
{
|
||||
$lab = DefinitionLab::depuis($this->labSession->lab->identifiant);
|
||||
$nomStack = "lab-session-{$this->labSession->id}";
|
||||
|
||||
['template' => $template] = $generateur->genererDepuis($lab, $nomStack);
|
||||
|
||||
$stack = $heat->creerStack($nomStack, $template);
|
||||
|
||||
$this->labSession->forceFill([
|
||||
'heat_stack_id' => $stack['id'],
|
||||
'heat_stack_name' => $nomStack,
|
||||
])->save();
|
||||
|
||||
$etat = $this->attendreCompletion($heat, $nomStack, $stack['id']);
|
||||
|
||||
if ($etat['statut'] !== 'CREATE_COMPLETE') {
|
||||
Log::error("CreerStackLab : la stack {$nomStack} n'a pas abouti", $etat);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
foreach ($lab->machines as $machine) {
|
||||
$cle = GenerateurTemplateHeat::cle($machine['nom']);
|
||||
$this->labSession->machines()->create([
|
||||
'nom' => $machine['nom'],
|
||||
'instance_id' => $etat['sorties']["{$cle}_id"],
|
||||
]);
|
||||
}
|
||||
|
||||
$this->labSession->forceFill(['etat' => LabSession::ACTIF])->save();
|
||||
}
|
||||
|
||||
/**
|
||||
* Heat crée une stack de cette taille (réseaux + quelques VM) en
|
||||
* général en moins d'une minute : on attend jusqu'à 2 minutes.
|
||||
*
|
||||
* @return array{statut: string, raison: ?string, sorties: array<string, mixed>}
|
||||
*/
|
||||
private function attendreCompletion(HeatClient $heat, string $nom, string $id): array
|
||||
{
|
||||
for ($tentative = 0; $tentative < 60; $tentative++) {
|
||||
$etat = $heat->etatStack($nom, $id);
|
||||
|
||||
if (! str_ends_with($etat['statut'], '_IN_PROGRESS')) {
|
||||
return $etat;
|
||||
}
|
||||
|
||||
sleep(2);
|
||||
}
|
||||
|
||||
return $etat;
|
||||
}
|
||||
}
|
||||
37
portail/app/Jobs/SupprimerStackLab.php
Normal file
37
portail/app/Jobs/SupprimerStackLab.php
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
<?php
|
||||
|
||||
namespace App\Jobs;
|
||||
|
||||
use App\Models\LabSession;
|
||||
use App\Services\OpenStack\HeatClient;
|
||||
use Illuminate\Bus\Queueable;
|
||||
use Illuminate\Contracts\Queue\ShouldQueue;
|
||||
use Illuminate\Foundation\Bus\Dispatchable;
|
||||
use Illuminate\Queue\InteractsWithQueue;
|
||||
use Illuminate\Queue\SerializesModels;
|
||||
|
||||
/**
|
||||
* Supprime la stack Heat d'une session de lab (étape 10) : fin de séance ou
|
||||
* expiration automatique (voir routes/console.php, Schedule).
|
||||
*/
|
||||
class SupprimerStackLab implements ShouldQueue
|
||||
{
|
||||
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
|
||||
|
||||
public int $tries = 3;
|
||||
|
||||
public function __construct(private readonly LabSession $labSession) {}
|
||||
|
||||
public function handle(HeatClient $heat): void
|
||||
{
|
||||
if ($this->labSession->heat_stack_name !== null) {
|
||||
$heat->supprimerStack($this->labSession->heat_stack_name, $this->labSession->heat_stack_id);
|
||||
}
|
||||
|
||||
$nouvelEtat = $this->labSession->expire_a !== null && $this->labSession->expire_a->isPast()
|
||||
? LabSession::EXPIRE
|
||||
: LabSession::TERMINE;
|
||||
|
||||
$this->labSession->forceFill(['etat' => $nouvelEtat])->save();
|
||||
}
|
||||
}
|
||||
|
|
@ -5,6 +5,7 @@ namespace App\Models;
|
|||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
|
||||
class LabSession extends Model
|
||||
{
|
||||
|
|
@ -12,15 +13,17 @@ class LabSession extends Model
|
|||
|
||||
public const EN_ATTENTE = 'en_attente';
|
||||
|
||||
// Admis par le prof : CreerStackLab est dispatché, la stack Heat se construit.
|
||||
public const ADMIS = 'admis';
|
||||
|
||||
// Stack CREATE_COMPLETE : les VM existent, les terminaux peuvent s'ouvrir.
|
||||
public const ACTIF = 'actif';
|
||||
|
||||
public const TERMINE = 'termine';
|
||||
|
||||
public const EXPIRE = 'expire';
|
||||
|
||||
protected $fillable = ['seance_id', 'eleve_id', 'lab_id', 'stack_id', 'etat', 'expire_a'];
|
||||
protected $fillable = ['seance_id', 'eleve_id', 'lab_id', 'heat_stack_id', 'heat_stack_name', 'etat', 'expire_a'];
|
||||
|
||||
protected $casts = [
|
||||
'expire_a' => 'datetime',
|
||||
|
|
@ -40,4 +43,9 @@ class LabSession extends Model
|
|||
{
|
||||
return $this->belongsTo(Lab::class);
|
||||
}
|
||||
|
||||
public function machines(): HasMany
|
||||
{
|
||||
return $this->hasMany(LabSessionMachine::class);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
19
portail/app/Models/LabSessionMachine.php
Normal file
19
portail/app/Models/LabSessionMachine.php
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
class LabSessionMachine extends Model
|
||||
{
|
||||
use HasFactory;
|
||||
|
||||
protected $fillable = ['lab_session_id', 'nom', 'instance_id'];
|
||||
|
||||
public function labSession(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(LabSession::class);
|
||||
}
|
||||
}
|
||||
51
portail/app/Services/Labs/DefinitionLab.php
Normal file
51
portail/app/Services/Labs/DefinitionLab.php
Normal file
|
|
@ -0,0 +1,51 @@
|
|||
<?php
|
||||
|
||||
namespace App\Services\Labs;
|
||||
|
||||
use Illuminate\Support\Facades\File;
|
||||
use RuntimeException;
|
||||
use Symfony\Component\Yaml\Yaml;
|
||||
|
||||
/**
|
||||
* Lit le lab.yaml d'un lab (voir paillasse-contenus/README.md pour le
|
||||
* format), pour que GenerateurTemplateHeat puisse en faire une stack.
|
||||
*/
|
||||
class DefinitionLab
|
||||
{
|
||||
public readonly string $identifiant;
|
||||
|
||||
/** @var array<int, array{nom: string, cidr: string}> */
|
||||
public readonly array $reseaux;
|
||||
|
||||
/** @var array<int, array{nom: string, image: string, flavor: string, reseaux: array<int, string>, preparation: ?string}> */
|
||||
public readonly array $machines;
|
||||
|
||||
public static function depuis(string $identifiantLab): self
|
||||
{
|
||||
$chemin = config('labs.dossier')."/{$identifiantLab}/lab.yaml";
|
||||
|
||||
if (! File::exists($chemin)) {
|
||||
throw new RuntimeException("Lab introuvable : {$chemin}");
|
||||
}
|
||||
|
||||
$donnees = Yaml::parseFile($chemin);
|
||||
|
||||
return new self($donnees);
|
||||
}
|
||||
|
||||
private function __construct(array $donnees)
|
||||
{
|
||||
$this->identifiant = $donnees['id'];
|
||||
$this->reseaux = $donnees['reseaux'];
|
||||
$this->machines = array_map(
|
||||
fn (array $m) => [
|
||||
'nom' => $m['nom'],
|
||||
'image' => $m['image'],
|
||||
'flavor' => $m['flavor'],
|
||||
'reseaux' => $m['reseaux'],
|
||||
'preparation' => $m['preparation'] ?? null,
|
||||
],
|
||||
$donnees['machines'],
|
||||
);
|
||||
}
|
||||
}
|
||||
107
portail/app/Services/OpenStack/GenerateurTemplateHeat.php
Normal file
107
portail/app/Services/OpenStack/GenerateurTemplateHeat.php
Normal file
|
|
@ -0,0 +1,107 @@
|
|||
<?php
|
||||
|
||||
namespace App\Services\OpenStack;
|
||||
|
||||
use App\Services\Labs\DefinitionLab;
|
||||
|
||||
/**
|
||||
* Traduit un lab.yaml en modèle Heat (étape 10) : un réseau Neutron par
|
||||
* réseau du lab, sans DHCP et sans sécurité de port (les élèves configurent
|
||||
* eux-mêmes leurs adresses), et une VM par machine, avec une interface par
|
||||
* réseau déclaré, dans l'ordre (= ordre des interfaces ens3, ens4…).
|
||||
*
|
||||
* Jamais de routeur vers l'extérieur : les réseaux de lab sont isolés,
|
||||
* conformément à CLAUDE.md (anti-abus, pas d'accès Internet depuis les VM
|
||||
* élèves).
|
||||
*/
|
||||
class GenerateurTemplateHeat
|
||||
{
|
||||
/**
|
||||
* @return array{template: array, noms_machines: array<int, string>}
|
||||
*/
|
||||
public function genererDepuis(DefinitionLab $lab, string $prefixe): array
|
||||
{
|
||||
$resources = [];
|
||||
$outputs = [];
|
||||
|
||||
foreach ($lab->reseaux as $reseau) {
|
||||
$cleReseau = self::cle($reseau['nom']);
|
||||
|
||||
$resources["reseau_{$cleReseau}"] = [
|
||||
'type' => 'OS::Neutron::Net',
|
||||
'properties' => [
|
||||
'name' => "{$prefixe}-{$reseau['nom']}",
|
||||
'port_security_enabled' => false,
|
||||
],
|
||||
];
|
||||
|
||||
$resources["sousreseau_{$cleReseau}"] = [
|
||||
'type' => 'OS::Neutron::Subnet',
|
||||
'properties' => [
|
||||
'network' => ['get_resource' => "reseau_{$cleReseau}"],
|
||||
'cidr' => $reseau['cidr'],
|
||||
'enable_dhcp' => false,
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
$nomsMachines = [];
|
||||
|
||||
foreach ($lab->machines as $machine) {
|
||||
$cleMachine = self::cle($machine['nom']);
|
||||
$nomsMachines[] = $machine['nom'];
|
||||
$ports = [];
|
||||
|
||||
foreach ($machine['reseaux'] as $nomReseau) {
|
||||
$cleReseau = self::cle($nomReseau);
|
||||
$clePort = "port_{$cleMachine}_{$cleReseau}";
|
||||
|
||||
$resources[$clePort] = [
|
||||
'type' => 'OS::Neutron::Port',
|
||||
'properties' => [
|
||||
'network' => ['get_resource' => "reseau_{$cleReseau}"],
|
||||
'port_security_enabled' => false,
|
||||
'fixed_ips' => [],
|
||||
],
|
||||
];
|
||||
|
||||
$ports[] = ['port' => ['get_resource' => $clePort]];
|
||||
}
|
||||
|
||||
$resources["machine_{$cleMachine}"] = [
|
||||
'type' => 'OS::Nova::Server',
|
||||
'properties' => [
|
||||
'name' => "{$prefixe}-{$machine['nom']}",
|
||||
'image' => $machine['image'],
|
||||
'flavor' => $machine['flavor'],
|
||||
'networks' => $ports,
|
||||
],
|
||||
];
|
||||
|
||||
$outputs["{$cleMachine}_id"] = [
|
||||
'description' => "Id de l'instance {$machine['nom']}",
|
||||
'value' => ['get_resource' => "machine_{$cleMachine}"],
|
||||
];
|
||||
}
|
||||
|
||||
$template = [
|
||||
'heat_template_version' => '2021-04-16',
|
||||
'description' => "Lab {$lab->identifiant} ({$prefixe})",
|
||||
'resources' => $resources,
|
||||
'outputs' => $outputs,
|
||||
];
|
||||
|
||||
return ['template' => $template, 'noms_machines' => $nomsMachines];
|
||||
}
|
||||
|
||||
/**
|
||||
* Les noms de ressources Heat ne peuvent pas contenir les caractères du
|
||||
* nom du lab (ex: "pc-a" → "pc_a"). Utilisé aussi par CreerStackLab pour
|
||||
* retrouver, dans les sorties de la stack, quelle clé correspond à
|
||||
* quelle machine.
|
||||
*/
|
||||
public static function cle(string $nom): string
|
||||
{
|
||||
return str_replace('-', '_', $nom);
|
||||
}
|
||||
}
|
||||
77
portail/app/Services/OpenStack/HeatClient.php
Normal file
77
portail/app/Services/OpenStack/HeatClient.php
Normal file
|
|
@ -0,0 +1,77 @@
|
|||
<?php
|
||||
|
||||
namespace App\Services\OpenStack;
|
||||
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use RuntimeException;
|
||||
|
||||
/**
|
||||
* Juste ce qu'il faut pour créer, suivre et supprimer une stack Heat
|
||||
* (étape 10) — pas de client générique, le besoin réel de Syllabus est
|
||||
* étroit (un lab = une stack, pour la durée d'une session).
|
||||
*/
|
||||
class HeatClient
|
||||
{
|
||||
public function __construct(private readonly KeystoneAuth $auth) {}
|
||||
|
||||
/**
|
||||
* @return array{id: string}
|
||||
*/
|
||||
public function creerStack(string $nom, array $template): array
|
||||
{
|
||||
$reponse = $this->requete()->post($this->url('/stacks'), [
|
||||
'stack_name' => $nom,
|
||||
'disable_rollback' => true,
|
||||
'template' => $template,
|
||||
]);
|
||||
|
||||
if ($reponse->failed()) {
|
||||
throw new RuntimeException("Heat a refusé la création de la stack {$nom} : ".$reponse->body());
|
||||
}
|
||||
|
||||
return ['id' => $reponse->json('stack.id')];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{statut: string, raison: ?string, sorties: array<string, mixed>}
|
||||
*/
|
||||
public function etatStack(string $nom, string $id): array
|
||||
{
|
||||
$reponse = $this->requete()->get($this->url("/stacks/{$nom}/{$id}"));
|
||||
|
||||
if ($reponse->failed()) {
|
||||
throw new RuntimeException("Impossible de lire l'état de la stack {$nom} : ".$reponse->body());
|
||||
}
|
||||
|
||||
$sorties = [];
|
||||
foreach ($reponse->json('stack.outputs') ?? [] as $sortie) {
|
||||
$sorties[$sortie['output_key']] = $sortie['output_value'];
|
||||
}
|
||||
|
||||
return [
|
||||
'statut' => $reponse->json('stack.stack_status'),
|
||||
'raison' => $reponse->json('stack.stack_status_reason'),
|
||||
'sorties' => $sorties,
|
||||
];
|
||||
}
|
||||
|
||||
public function supprimerStack(string $nom, string $id): void
|
||||
{
|
||||
$reponse = $this->requete()->delete($this->url("/stacks/{$nom}/{$id}"));
|
||||
|
||||
// 404 : déjà supprimée (idempotent, pas une erreur pour nous).
|
||||
if ($reponse->failed() && $reponse->status() !== 404) {
|
||||
throw new RuntimeException("Heat a refusé la suppression de la stack {$nom} : ".$reponse->body());
|
||||
}
|
||||
}
|
||||
|
||||
private function requete()
|
||||
{
|
||||
return Http::withHeaders(['X-Auth-Token' => $this->auth->jeton()]);
|
||||
}
|
||||
|
||||
private function url(string $chemin): string
|
||||
{
|
||||
return config('openstack.heat_url').'/'.$this->auth->projetId().$chemin;
|
||||
}
|
||||
}
|
||||
66
portail/app/Services/OpenStack/KeystoneAuth.php
Normal file
66
portail/app/Services/OpenStack/KeystoneAuth.php
Normal file
|
|
@ -0,0 +1,66 @@
|
|||
<?php
|
||||
|
||||
namespace App\Services\OpenStack;
|
||||
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use RuntimeException;
|
||||
|
||||
/**
|
||||
* Authentification OpenStack partagée par NovaClient (étape 9) et HeatClient
|
||||
* (étape 10), pour le compte de service `paillasse-service` (étape 6).
|
||||
*
|
||||
* Par mot de passe, pas par application credential : voir config/openstack.php
|
||||
* pour pourquoi (Heat a besoin de créer un trust Keystone, ce qu'une
|
||||
* application credential ne peut jamais faire).
|
||||
*/
|
||||
class KeystoneAuth
|
||||
{
|
||||
public function jeton(): string
|
||||
{
|
||||
return $this->authentifier()['jeton'];
|
||||
}
|
||||
|
||||
public function projetId(): string
|
||||
{
|
||||
return $this->authentifier()['projet_id'];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{jeton: string, projet_id: string}
|
||||
*/
|
||||
private function authentifier(): array
|
||||
{
|
||||
return Cache::remember('openstack.authentification', now()->addMinutes(50), function () {
|
||||
$reponse = Http::post(config('openstack.auth_url').'/v3/auth/tokens', [
|
||||
'auth' => [
|
||||
'identity' => [
|
||||
'methods' => ['password'],
|
||||
'password' => [
|
||||
'user' => [
|
||||
'name' => config('openstack.username'),
|
||||
'domain' => ['id' => 'default'],
|
||||
'password' => config('openstack.password'),
|
||||
],
|
||||
],
|
||||
],
|
||||
'scope' => [
|
||||
'project' => [
|
||||
'name' => config('openstack.project_name'),
|
||||
'domain' => ['id' => 'default'],
|
||||
],
|
||||
],
|
||||
],
|
||||
]);
|
||||
|
||||
if ($reponse->failed()) {
|
||||
throw new RuntimeException('Authentification OpenStack refusée : '.$reponse->body());
|
||||
}
|
||||
|
||||
return [
|
||||
'jeton' => $reponse->header('X-Subject-Token'),
|
||||
'projet_id' => $reponse->json('token.project.id'),
|
||||
];
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
@ -2,21 +2,22 @@
|
|||
|
||||
namespace App\Services\OpenStack;
|
||||
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use RuntimeException;
|
||||
|
||||
/**
|
||||
* Juste ce qu'il faut pour demander à Nova l'adresse de la console série
|
||||
* d'une VM (étape 9). La liaison Laravel ↔ OpenStack complète (Heat, labs)
|
||||
* est l'étape 10 : on ne construit pas de client générique ici.
|
||||
* est l'étape 10 : voir HeatClient.
|
||||
*/
|
||||
class NovaClient
|
||||
{
|
||||
public function __construct(private readonly KeystoneAuth $auth) {}
|
||||
|
||||
public function consoleSerielle(string $instanceId): string
|
||||
{
|
||||
$reponse = Http::withHeaders([
|
||||
'X-Auth-Token' => $this->jetonKeystone(),
|
||||
'X-Auth-Token' => $this->auth->jeton(),
|
||||
'OpenStack-API-Version' => 'compute 2.99',
|
||||
])
|
||||
->post(config('openstack.nova_url')."/servers/{$instanceId}/remote-consoles", [
|
||||
|
|
@ -29,31 +30,4 @@ class NovaClient
|
|||
|
||||
return $reponse->json('remote_console.url');
|
||||
}
|
||||
|
||||
/**
|
||||
* Jeton Keystone mis en cache (un jeton v3 dure 1h côté Keystone, on le
|
||||
* garde un peu moins longtemps par prudence).
|
||||
*/
|
||||
private function jetonKeystone(): string
|
||||
{
|
||||
return Cache::remember('openstack.jeton_keystone', now()->addMinutes(50), function () {
|
||||
$reponse = Http::post(config('openstack.auth_url').'/v3/auth/tokens', [
|
||||
'auth' => [
|
||||
'identity' => [
|
||||
'methods' => ['application_credential'],
|
||||
'application_credential' => [
|
||||
'id' => config('openstack.application_credential_id'),
|
||||
'secret' => config('openstack.application_credential_secret'),
|
||||
],
|
||||
],
|
||||
],
|
||||
]);
|
||||
|
||||
if ($reponse->failed()) {
|
||||
throw new RuntimeException('Authentification OpenStack refusée : '.$reponse->body());
|
||||
}
|
||||
|
||||
return $reponse->header('X-Subject-Token');
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue