Okay, let's outline the structure and provide key code snippets for a Django application that handles HPC account requests, sysadmin approval, Slurm integration, and an audit trail.
Project Structure:
hpc_signup_project/
├── manage.py
├── hpc_signup_project/
│ ├── __init__.py
│ ├── settings.py
│ ├── urls.py
│ ├── wsgi.py
│ └── asgi.py
└── hpc_signup/
├── __init__.py
├── admin.py
├── apps.py
├── forms.py
├── models.py
├── templates/
│ └── hpc_signup/
│ ├── signup.html
│ ├── signup_success.html
│ ├── admin/
│ │ ├── request_list.html
│ │ ├── request_detail.html
│ │ └── audit_log.html
├── urls.py
└── views.py
└── tasks.py # Optional, but recommended for Slurm integration (e.g., using Celery)
Setup Steps:
-
Create Project and App:
django-admin startproject hpc_signup_project
cd hpc_signup_project
python manage.py startapp hpc_signup
-
Add hpc_signup to INSTALLED_APPS in hpc_signup_project/settings.py:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'hpc_signup', # Add your app
# Optional: 'django_celery_results', 'django_celery_beat' if using Celery
]
-
Configure Database (default SQLite is fine for this example, but use a production DB for real deployment).
-
Create Superuser for accessing the admin area:
python manage.py createsuperuser
-
Run Migrations:
python manage.py migrate
Code Implementation:
hpc_signup/models.py
from django.db import models
from django.conf import settings
from django.utils import timezone
class AccountRequest(models.Model):
STATUS_CHOICES = (
('Pending', 'Pending'),
('Approved', 'Approved'),
('Rejected', 'Rejected'),
('Processing', 'Processing'), # Status while Slurm command runs
('Completed', 'Completed'), # Slurm account created successfully
('Failed', 'Failed'), # Slurm account creation failed
)
username = models.CharField(max_length=50, unique=True, help_text="Desired HPC username")
email = models.EmailField(help_text="Your email address")
research_group = models.CharField(max_length=100, help_text="Your research group or PI name")
request_date = models.DateTimeField(auto_now_add=True)
status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='Pending')
approval_date = models.DateTimeField(null=True, blank=True)
approved_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True)
admin_notes = models.TextField(null=True, blank=True)
slurm_output = models.TextField(null=True, blank=True) # To store output/errors from Slurm command
def __str__(self):
return f"Request for {self.username} ({self.status})"
class AuditLog(models.Model):
request = models.ForeignKey(AccountRequest, on_delete=models.CASCADE, related_name='audit_logs')
action = models.CharField(max_length=100) # e.g., 'Created', 'Status Change', 'Approved', 'Rejected', 'Slurm Command Executed'
details = models.TextField() # e.g., "Status changed from Pending to Approved by admin_user", "Slurm command failed: ..."
timestamp = models.DateTimeField(auto_now_add=True)
performed_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True)
def __str__(self):
return f"Audit: {self.action} for {self.request.username} at {self.timestamp.strftime('%Y-%m-%d %H:%M')}"
class Meta:
ordering = ['-timestamp']
Run python manage.py makemigrations hpc_signup and python manage.py migrate again after adding models.
hpc_signup/forms.py
from django import forms
from .models import AccountRequest
class AccountRequestForm(forms.ModelForm):
class Meta:
model = AccountRequest
fields = ['username', 'email', 'research_group']
widgets = {
'username': forms.TextInput(attrs={'placeholder': 'e.g., jdoe'}),
'email': forms.EmailInput(attrs={'placeholder': 'e.g., your.name@example.com'}),
'research_group': forms.TextInput(attrs={'placeholder': 'e.g., Smith Lab'}),
}
# Optional: Add custom validation, e.g., check username format
def clean_username(self):
username = self.cleaned_data['username']
# Basic validation: no spaces, no special characters (adjust as needed for your Slurm config)
if not username.isalnum():
raise forms.ValidationError("Username should contain only letters and numbers.")
# Check if username already exists in approved/completed requests? More complex.
# For simplicity, relying on the unique=True in model and Slurm command failure detection.
return username
hpc_signup/views.py
from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.decorators import login_required, user_passes_test
from django.utils import timezone
from django.urls import reverse
from django.contrib import messages # Optional for user feedback
from .forms import AccountRequestForm
from .models import AccountRequest, AuditLog
# Assuming Slurm integration is handled by a task function (recommended)
# from .tasks import create_slurm_account_task
# --- Public Views ---
def signup_view(request):
if request.method == 'POST':
form = AccountRequestForm(request.POST)
if form.is_valid():
request_obj = form.save(commit=False)
# Ensure initial status is pending
request_obj.status = 'Pending'
request_obj.save()
# Add audit log for creation
AuditLog.objects.create(
request=request_obj,
action='Created',
details=f"Account request created by {request_obj.email}"
)
return redirect('signup_success')
else:
form = AccountRequestForm()
return render(request, 'hpc_signup/signup.html', {'form': form})
def signup_success_view(request):
return render(request, 'hpc_signup/signup_success.html')
# --- Admin Views (Require Login and Staff Status) ---
# Helper to check if user is staff (sysadmin)
def is_sysadmin(user):
return user.is_staff # Or use a custom permission check
@login_required
@user_passes_test(is_sysadmin)
def admin_request_list_view(request):
requests = AccountRequest.objects.all().order_by('-request_date')
return render(request, 'hpc_signup/admin/request_list.html', {'requests': requests})
@login_required
@user_passes_test(is_sysadmin)
def admin_request_detail_view(request, pk):
request_obj = get_object_or_404(AccountRequest, pk=pk)
if request.method == 'POST':
action = request.POST.get('action') # 'approve' or 'reject'
admin_notes = request.POST.get('admin_notes') # Get notes from form
# Only process pending requests to avoid accidental re-processing
if request_obj.status == 'Pending':
if action == 'approve':
request_obj.status = 'Processing' # Set to Processing before task
request_obj.approved_by = request.user
request_obj.approval_date = timezone.now()
request_obj.admin_notes = admin_notes
request_obj.save()
# Add audit log for approval
AuditLog.objects.create(
request=request_obj,
action='Approved',
details=f"Request approved by {request.user.username}. Status set to Processing.",
performed_by=request.user
)
# --- Trigger Slurm Account Creation ---
# RECOMMENDED: Use a task queue like Celery for this
# from .tasks import create_slurm_account_task
# create_slurm_account_task.delay(request_obj.id)
# For simple example, call a synchronous function (BLOCKING!)
try:
slurm_success, slurm_output = run_slurm_command(request_obj)
request_obj.slurm_output = slurm_output
if slurm_success:
request_obj.status = 'Completed'
audit_details = f"Slurm account created successfully by {request.user.username}."
else:
request_obj.status = 'Failed'
audit_details = f"Slurm account creation failed by {request.user.username}. Output:\n{slurm_output}"
request_obj.save()
AuditLog.objects.create(
request=request_obj,
action='Slurm Command Executed',
details=audit_details,
performed_by=request.user
)
messages.success(request, f"Request {request_obj.pk} processed. Status: {request_obj.status}.")
except Exception as e:
# Handle exceptions during synchronous call
request_obj.status = 'Failed'
request_obj.slurm_output = f"Exception during processing: {e}"
request_obj.save()
AuditLog.objects.create(
request=request_obj,
action='Processing Failed',
details=f"Processing failed due to exception: {e}",
performed_by=request.user
)
messages.error(request, f"Request {request_obj.pk} processing failed due to an exception.")
elif action == 'reject':
request_obj.status = 'Rejected'
request_obj.approved_by = request.user
request_obj.approval_date = timezone.now()
request_obj.admin_notes = admin_notes
request_obj.save()
# Add audit log for rejection
AuditLog.objects.create(
request=request_obj,
action='Rejected',
details=f"Request rejected by {request.user.username}.",
performed_by=request.user
)
messages.warning(request, f"Request {request_obj.pk} rejected.")
# Redirect back to list or detail page
return redirect('admin_request_detail', pk=request_obj.pk)
# GET request: display details and a form for notes/action
return render(request, 'hpc_signup/admin/request_detail.html', {'request': request_obj})
@login_required
@user_passes_test(is_sysadmin)
def admin_audit_log_view(request):
# Fetch logs, maybe filter or paginate for large numbers
logs = AuditLog.objects.all().order_by('-timestamp')
return render(request, 'hpc_signup/admin/audit_log.html', {'logs': logs})
# --- Slurm Integration Placeholder ---
# **IMPORTANT**: This is a SYNCHRONOUS placeholder.
# In a real application, this MUST be run asynchronously (Celery, etc.)
# as it will block the web server.
# This function needs to interact with your actual Slurm environment.
import subprocess
def run_slurm_command(request_obj):
"""
Placeholder function to run a Slurm command.
Replace with actual Slurm API calls or subprocess commands.
Args:
request_obj: The AccountRequest instance.
Returns:
tuple: (success: bool, output: str)
"""
username = request_obj.username
# email = request_obj.email # Email might not be needed for sacctmgr create
group = request_obj.research_group # Map this to a valid Slurm account/qos/group if needed
# Example: sacctmgr command (adjust syntax for your Slurm version and setup)
# sacctmgr create user <username> Account=<group> DefAcct=<group>
# This assumes your group maps directly to a Slurm Account.
# You might need to look up group-to-account mappings.
# BE CAREFUL WITH SHELL=TRUE AND USER INPUT
# Using a list is safer to prevent command injection
command = ["sacctmgr", "create", "user", username, f"Account={group}", f"DefAcct={group}"]
# If you need sudo: command = ["sudo", "sacctmgr", ...] - Configure sudoers appropriately!
# Consider using a Slurm API library if available/preferred.
try:
# Using capture_output=True and text=True (Python 3.5+)
# Or check_output (older Python)
result = subprocess.run(command, capture_output=True, text=True, check=False) # check=False to handle non-zero exit codes
output = result.stdout + result.stderr
success = result.returncode == 0
# Basic check for common errors in output if returncode is 0 but it failed
if success and ("Could not create user" in output or "already exists" in output):
success = False
return success, output
except FileNotFoundError:
return False, f"Error: sacctmgr command not found. Is Slurm installed and in PATH? (Attempted: {' '.join(command)})"
except Exception as e:
return False, f"An unexpected error occurred while running Slurm command: {e} (Command: {' '.join(command)})"
# --- Celery Task (tasks.py) - Recommended for Async Slurm ---
# If you set up Celery:
# (Requires celery, django-celery-results or django-celery-beat)
# Add 'celery_results' or 'celery_beat' to INSTALLED_APPS
# Configure CELERY_BROKER_URL in settings.py
# from celery import shared_task
# from .models import AccountRequest, AuditLog
# from django.contrib.auth import get_user_model
# from django.utils import timezone
# import subprocess # or your Slurm interaction code
# User = get_user_model()
# @shared_task
# def create_slurm_account_task(request_id, performed_by_id=None):
# """
# Celery task to create a Slurm account.
# """
# try:
# request_obj = AccountRequest.objects.get(id=request_id)
# performed_by = User.objects.get(id=performed_by_id) if performed_by_id else None
# # Ensure it's still in a state ready for processing (e.g., 'Processing')
# if request_obj.status not in ['Processing', 'Approved']: # Allow 'Approved' just in case state wasn't set to Processing
# # Log this unusual state, but don't proceed with Slurm
# AuditLog.objects.create(
# request=request_obj,
# action='Task Ignored',
# details=f"Slurm task received for request in status '{request_obj.status}'. Task ignored.",
# performed_by=performed_by
# )
# return
# request_obj.status = 'Processing' # Re-affirm status
# request_obj.save()
# # --- Your actual Slurm command execution logic goes here ---
# # Use the run_slurm_command function or your Slurm API code
# success, output = run_slurm_command(request_obj) # Replace with your Slurm execution code
# request_obj.slurm_output = output
# if success:
# request_obj.status = 'Completed'
# audit_details = "Slurm account creation task completed successfully."
# else:
# request_obj.status = 'Failed'
# audit_details = f"Slurm account creation task failed. Output:\n{output}"
# request_obj.save()
# AuditLog.objects.create(
# request=request_obj,
# action='Slurm Command Executed',
# details=audit_details,
# performed_by=performed_by # Log who triggered it
# )
# except AccountRequest.DoesNotExist:
# # Log that the request object wasn't found
# print(f"Celery task failed: AccountRequest with id {request_id} not found.")
# # Optionally, log to a file or monitoring system
# except Exception as e:
# # Log other unexpected errors in the task
# print(f"Celery task for request {request_id} failed with exception: {e}")
# # Try to update the request status to Failed if possible
# try:
# request_obj = AccountRequest.objects.get(id=request_id)
# request_obj.status = 'Failed'
# request_obj.slurm_output = f"Task Exception: {e}"
# request_obj.save()
# AuditLog.objects.create(
# request=request_obj,
# action='Task Failed',
# details=f"Slurm task failed with exception: {e}",
# performed_by=performed_by
# )
# except Exception:
# # If even the update fails, just log the original error
# pass # Log this critical failure externally if possible
# # If using Celery, update the admin_request_detail_view POST section:
# # ... inside the 'approve' action ...
# # request_obj.status = 'Approved' # or 'Processing', based on whether task triggers immediately
# # request_obj.approved_by = request.user
# # request_obj.approval_date = timezone.now()
# # request_obj.admin_notes = admin_notes
# # request_obj.save()
# # # Add audit log for approval decision
# # AuditLog.objects.create(...) # Log the approval decision
# # # Call the async task
# # create_slurm_account_task.delay(request_obj.id, request.user.id)
# # messages.success(request, f"Request {request_obj.pk} approved. Slurm creation task submitted.")
# # ...
hpc_signup/urls.py
from django.urls import path
from . import views
urlpatterns = [
# Public URLs
path('signup/', views.signup_view, name='signup'),
path('signup/success/', views.signup_success_view, name='signup_success'),
# Admin URLs
path('admin/requests/', views.admin_request_list_view, name='admin_request_list'),
path('admin/requests/<int:pk>/', views.admin_request_detail_view, name='admin_request_detail'),
path('admin/audit/', views.admin_audit_log_view, name='admin_audit_log'),
]
hpc_signup_project/urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('hpc_signup.urls')), # Include your app's urls
# Optional: Add auth urls for login/logout if not using default admin login
# path('accounts/', include('django.contrib.auth.urls')),
]
Note: The admin views above rely on the default Django admin login. If you need a separate login page for the admin area, you'll need to set up django.contrib.auth.urls and potentially redirect users.
hpc_signup/templates/hpc_signup/signup.html
{% extends 'base.html' %} {# Assuming you have a base template #}
{% block title %}HPC Account Sign-up{% endblock %}
{% block content %}
<h1>HPC Account Sign-up Request</h1>
<p>Please fill out the form below to request an HPC account.</p>
<form method="post">
{% csrf_token %}
{{ form.as_p }} {# Renders form fields as paragraphs #}
<button type="submit">Submit Request</button>
</form>
{% if messages %}
<ul class="messages">
{% for message in messages %}
<li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
{% endblock %}
hpc_signup/templates/hpc_signup/signup_success.html
{% extends 'base.html' %}
{% block title %}Request Submitted{% endblock %}
{% block content %}
<h1>Request Submitted Successfully</h1>
<p>Your HPC account request has been submitted. You will be notified via email once it has been reviewed and processed.</p>
<p><a href="{% url 'signup' %}">Submit another request</a></p>
{% endblock %}
hpc_signup/templates/hpc_signup/admin/request_list.html
{% extends 'admin/base_site.html' %} {# Use the Django admin base template for integration #}
{% load static %}
{% block title %}HPC Requests - Admin{% endblock %}
{% block branding %}
<h1 id="site-name"><a href="{% url 'admin:index' %}">HPC Admin</a></h1>
{% endblock %}
{% block nav-global %}{% endblock %}
{% block content %}
<h2>HPC Account Requests</h2>
{% if messages %}
<ul class="messagelist">
{% for message in messages %}
<li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
<table>
<thead>
<tr>
<th>Username</th>
<th>Email</th>
<th>Research Group</th>
<th>Status</th>
<th>Request Date</th>
<th>Approved By</th>
<th>Approval Date</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{% for req in requests %}
<tr>
<td>{{ req.username }}</td>
<td>{{ req.email }}</td>
<td>{{ req.research_group }}</td>
<td>{{ req.status }}</td>
<td>{{ req.request_date|date:"Y-m-d H:i" }}</td>
<td>{{ req.approved_by.username|default:"-" }}</td>
<td>{{ req.approval_date|date:"Y-m-d H:i"|default:"-" }}</td>
<td>
<a href="{% url 'admin_request_detail' req.pk %}">View/Process</a>
</td>
</tr>
{% empty %}
<tr>
<td colspan="8">No account requests found.</td>
</tr>
{% endfor %}
</tbody>
</table>
<p><a href="{% url 'admin_audit_log' %}">View Audit Log</a></p>
{% endblock %}
Note: Using admin/base_site.html helps integrate with the standard Django admin look and feel. You might need to override more blocks depending on your admin customizations.
hpc_signup/templates/hpc_signup/admin/request_detail.html
{% extends 'admin/base_site.html' %}
{% load static %}
{% block title %}Request {{ request.pk }} - Admin{% endblock %}
{% block branding %}
<h1 id="site-name"><a href="{% url 'admin:index' %}">HPC Admin</a></h1>
{% endblock %}
{% block nav-global %}{% endblock %}
{% block content %}
<h2>Request Details: {{ request.username }}</h2>
{% if messages %}
<ul class="messagelist">
{% for message in messages %}
<li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
<p><strong>Username:</strong> {{ request.username }}</p>
<p><strong>Email:</strong> {{ request.email }}</p>
<p><strong>Research Group:</strong> {{ request.research_group }}</p>
<p><strong>Status:</strong> {{ request.status }}</p>
<p><strong>Request Date:</strong> {{ request.request_date|date:"Y-m-d H:i" }}</p>
<p><strong>Approved By:</strong> {{ request.approved_by.username|default:"-" }}</p>
<p><strong>Approval Date:</strong> {{ request.approval_date|date:"Y-m-d H:i"|default:"-" }}</p>
{% if request.slurm_output %}
<p><strong>Slurm Output:</strong></p>
<pre>{{ request.slurm_output }}</pre>
{% endif %}
<h3>Actions</h3>
{% if request.status == 'Pending' %}
<form method="post" style="display:inline;">
{% csrf_token %}
<input type="hidden" name="action" value="approve">
<p><strong>Admin Notes:</strong><br><textarea name="admin_notes" rows="4" cols="50"></textarea></p>
<button type="submit">Approve & Create Account</button>
</form>
<form method="post" style="display:inline; margin-left: 20px;">
{% csrf_token %}
<input type="hidden" name="action" value="reject">
<p><strong>Admin Notes:</strong><br><textarea name="admin_notes" rows="4" cols="50"></textarea></p>
<button type="submit" onclick="return confirm('Are you sure you want to reject this request?');">Reject Request</button>
</form>
{% else %}
<p>This request has already been processed.</p>
{% if request.admin_notes %}
<p><strong>Admin Notes:</strong><br><pre>{{ request.admin_notes }}</pre></p>
{% endif %}
{% endif %}
<h3>Audit Trail</h3>
{% if request.audit_logs.exists %}
<table>
<thead>
<tr>
<th>Timestamp</th>
<th>Action</th>
<th>Details</th>
<th>Performed By</th>
</tr>
</thead>
<tbody>
{% for log in request.audit_logs.all %}
<tr>
<td>{{ log.timestamp|date:"Y-m-d H:i" }}</td>
<td>{{ log.action }}</td>
<td>{{ log.details }}</td>
<td>{{ log.performed_by.username|default:"System" }}</td>
</tr>
{% endfor %}
</tbody>
</table>
{% else %}
<p>No audit entries for this request.</p>
{% endif %}
<p><a href="{% url 'admin_request_list' %}">Back to Request List</a></p>
{% endblock %}
hpc_signup/templates/hpc_signup/admin/audit_log.html
{% extends 'admin/base_site.html' %}
{% load static %}
{% block title %}Audit Log - Admin{% endblock %}
{% block branding %}
<h1 id="site-name"><a href="{% url 'admin:index' %}">HPC Admin</a></h1>
{% endblock %}
{% block nav-global %}{% endblock %}
{% block content %}
<h2>HPC Account Request Audit Log</h2>
<table>
<thead>
<tr>
<th>Timestamp</th>
<th>Request (Username)</th>
<th>Action</th>
<th>Details</th>
<th>Performed By</th>
</tr>
</thead>
<tbody>
{% for log in logs %}
<tr>
<td>{{ log.timestamp|date:"Y-m-d H:i" }}</td>
<td><a href="{% url 'admin_request_detail' log.request.pk %}">{{ log.request.username }}</a></td>
<td>{{ log.action }}</td>
<td>{{ log.details|linebreaksbr }}</td> {# Display details with line breaks #}
<td>{{ log.performed_by.username|default:"System" }}</td>
</tr>
{% empty %}
<tr>
<td colspan="5">No audit log entries found.</td>
</tr>
{% endfor %}
</tbody>
</table>
<p><a href="{% url 'admin_request_list' %}">Back to Request List</a></p>
{% endblock %}
hpc_signup/admin.py (Optional, for standard Django admin)
from django.contrib import admin
from .models import AccountRequest, AuditLog
@admin.register(AccountRequest)
class AccountRequestAdmin(admin.ModelAdmin):
list_display = ('username', 'email', 'research_group', 'status', 'request_date', 'approved_by', 'approval_date')
list_filter = ('status', 'request_date', 'approval_date', 'research_group')
search_fields = ('username', 'email', 'research_group')
readonly_fields = ('request_date', 'approval_date', 'approved_by', 'slurm_output') # Make these non-editable in default admin
# You might disable adding/changing in the default admin if you only use the custom views for processing
# def has_add_permission(self, request): return False
# def has_change_permission(self, request, obj=None):
# # Allow changing only for pending requests? Or disable entirely?
# if obj is not None and obj.status != 'Pending':
# return False
# return super().has_change_permission(request, obj)
@admin.register(AuditLog)
class AuditLogAdmin(admin.ModelAdmin):
list_display = ('timestamp', 'request', 'action', 'performed_by')
list_filter = ('action', 'timestamp', 'performed_by')
search_fields = ('request__username', 'action', 'details')
readonly_fields = ('request', 'action', 'details', 'timestamp', 'performed_by') # All fields read-only
# Disable adding/changing/deleting audit logs via the admin
def has_add_permission(self, request): return False
def has_change_permission(self, request, obj=None): return False
def has_delete_permission(self, request, obj=None): return False
Access the standard Django admin at /admin/. Your custom admin views are accessed via the URLs defined in hpc_signup/urls.py like /admin/requests/.
Considerations and Next Steps:
-
Security:
- Ensure your server environment executing the Slurm commands is secure.
- Use
subprocess.run with a list of arguments, not shell=True, and sanitize any user-provided inputs passed to the command.
- Configure
sudo appropriately if the Django user needs elevated privileges to run sacctmgr.
- Protect your admin URLs (
@login_required, @user_passes_test).
- Protect against CSRF (Django forms handle this by default with
{% csrf_token %}).
-
Slurm Integration:
- The
run_slurm_command is a critical placeholder. You need to replace it with code that actually runs on your HPC login/management node or interacts with a Slurm API endpoint.
- Asynchronous Tasks: Running
subprocess.run directly in a Django view is blocking. This means your web server will wait for the Slurm command to finish, which can take seconds or minutes, leading to timeouts or a frozen UI. Strongly recommend using a task queue like Celery (as sketched in the comments in views.py and tasks.py) to run the Slurm command in the background. The view would trigger the task, and the task would update the AccountRequest status when done.
- Permissions: The user running the Django application process needs appropriate permissions to execute
sacctmgr or whatever Slurm command/API call is used. sacctmgr typically requires root or special Slurm administrative privileges. Using sudo correctly configured for specific commands is a common approach.
- Error Handling: The Slurm command can fail (user exists, invalid group, network issues, etc.). The
run_slurm_command (or your task) must capture stderr and the exit code and update the request status to 'Failed' with details in slurm_output.
-
User Notifications:
- Users expect to be notified when their request is approved, rejected, or completed. You'll need to integrate Django's email sending capabilities or an external service to send emails triggered by the status changes (e.g., in the view after approval/rejection, or in the Celery task after completion/failure).
-
Authentication and Authorization:
- The uses . You might want a more granular permission system (e.g., using Django's built-in permissions framework) if you have different levels of administrators.
This provides a solid foundation for your Django-based HPC account request interface. Remember to implement the Slurm integration carefully, especially regarding security and asynchronous execution.