Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add redis ping #53

Merged
merged 18 commits into from
Jul 11, 2023
Merged
Show file tree
Hide file tree
Changes from 9 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 9 additions & 2 deletions chirps/target/providers/redis.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
from logging import getLogger

from django.db import models
from redis import Redis
from target.models import BaseTarget

logger = getLogger(__name__)
Expand All @@ -28,5 +29,11 @@ def search(self, query: str, max_results: int) -> str:

def test_connection(self) -> bool:
"""Ensure that the Redis target can be connected to."""
logger.error('RedisTarget search not implemented')
raise NotImplementedError
client = Redis(
host=self.host,
port=self.port,
db=self.database_name,
password=self.password,
username=self.username,
)
return client.ping()
97 changes: 60 additions & 37 deletions chirps/target/templates/target/dashboard.html
Original file line number Diff line number Diff line change
Expand Up @@ -9,50 +9,73 @@ <h1 class="text-success">Targets</h1>
</div>
<div class="ml-auto mr-0 my-auto">
<div class="dropdown"></div>
<button class="btn btn-primary dropdown-toggle" data-bs-toggle="dropdown">Create</button>
<div class="dropdown-menu">
{% for target in available_targets %}
<a class="dropdown-item" href="{% url 'target_create' target.model.html_name %}">{{target.model.html_name}}</a>
{% endfor %}
</div>
<button class="btn btn-primary dropdown-toggle" data-bs-toggle="dropdown">Create</button>
<div class="dropdown-menu">
{% for target in available_targets %}
<a class="dropdown-item"
href="{% url 'target_create' target.model.html_name %}">{{target.model.html_name}}</a>
{% endfor %}
</div>
</div>
</div>
<hr>
</div>
<hr>

{% for target in user_targets %}
{% for target in user_targets %}

<div class="card my-4">
<div class="d-flex card-header">
<img width=48 class="rounded float-end my-auto ml-0 mr-3" src="{{target.logo_url}}">
<h5 class="my-auto ml-0 mr-auto">{{ target.name }}</h5>
</div>
<!-- <h5 class="card-header"><img width=48 class="rounded float-end" src="{{target.logo_url}}">{{ target.name }}</h5> -->
<div class="card-body">
<p class="card-text">
<div class="card my-4">
<div class="d-flex card-header">
<img width=48 class="rounded float-end my-auto ml-0 mr-3" src="{{target.logo_url}}">
<h5 class="my-auto ml-0 mr-auto">{{ target.name }}</h5>
</div>
<!-- <h5 class="card-header"><img width=48 class="rounded float-end" src="{{target.logo_url}}">{{ target.name }}</h5> -->
<div class="card-body">
<p class="card-text">

{% if target.html_name == 'Mantium' %}
Application ID: {{ target.app_id }}
{% elif target.html_name == 'Redis' %}
Host: {{ target.host }}<br/>
Port: {{ target.port }}<br/>
Database Name: {{ target.database_name }}<br/>
Username: {{ target.username }}
{% endif %}
{% if target.html_name == 'Pinecone' %}
API Key: {{ target.decrypted_api_key }}<br/>
Environment: {{ target.environment }}<br/>
Index Name: {{ target.index_name }}<br/>
Project Name: {{ target.project_name }}
{% endif %}
</p>
<div class="d-flex">
<a href="{% url 'target_delete' target.id %}" class="btn btn-danger ml-auto mr-0">Delete</a>
<a href="#" class="btn btn-primary ml-2 mr-0 disabled">Edit</a>
</div>
</div>
{% if target.html_name == 'Mantium' %}
Application ID: {{ target.app_id }}
{% elif target.html_name == 'Redis' %}
Host: {{ target.host }}<br />
Port: {{ target.port }}<br />
Database Name: {{ target.database_name }}<br />
Username: {{ target.username }}
{% endif %}
{% if target.html_name == 'Pinecone' %}
API Key: {{ target.decrypted_api_key }}<br />
Environment: {{ target.environment }}<br />
Index Name: {{ target.index_name }}<br />
Project Name: {{ target.project_name }}
{% endif %}
</p>
<div class="d-flex">
<a href="{% url 'target_delete' target.id %}" class="btn btn-danger ml-auto mr-0">Delete</a>
<a href="#" class="btn btn-primary ml-2 mr-0 disabled">Edit</a>
{% if target.html_name == 'Redis' %}
<button data-target-id="{{ target.id }}" class="btn btn-info ml-2 mr-0 ping-btn">Ping</button>
{% endif %}
</div>
</div>
</div>

{% endfor %}
{% endfor %}
</div>

<script>
document.addEventListener('DOMContentLoaded', function () {
const pingButtons = document.querySelectorAll('.ping-btn');
pingButtons.forEach(btn => {
btn.addEventListener('click', async function () {
const targetId = btn.getAttribute('data-target-id');
const response = await fetch(`/target/ping/${targetId}/`, { headers: { 'X-Requested-With': 'XMLHttpRequest' } });
const result = await response.json();
if (result.success) {
alert('Ping successful');
} else {
alert('Ping failed: ' + (result.error || 'Unknown error'));
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Instead of using alerts, let's class it up and use Bootstrap's toaster notifications!

https://getbootstrap.com/docs/5.3/components/toasts/

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Screenshot 2023-07-11 at 11 36 42 AM

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hell yeah! Nice work 👍👍

}
});
});
});
</script>

{% endblock %}
1 change: 1 addition & 0 deletions chirps/target/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
urlpatterns = [
path('', views.dashboard, name='target_dashboard'),
path('create/<str:html_name>', views.create, name='target_create'),
path('ping/<int:target_id>/', views.ping, name='target_ping'),
path('delete/<int:target_id>', views.delete, name='target_delete'),
path('decrypted_keys/', views.decrypted_keys, name='decrypted_keys'),
]
21 changes: 20 additions & 1 deletion chirps/target/views.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,15 @@
"""View handlers for targets."""
import json

from django.contrib.auth.decorators import login_required
from django.http import JsonResponse
from django.http import HttpResponseBadRequest, JsonResponse
from django.shortcuts import get_object_or_404, redirect, render
from redis import exceptions

from .forms import target_from_html_name, targets
from .models import BaseTarget
from .providers.pinecone import PineconeTarget
from .providers.redis import RedisTarget


def decrypted_keys(request):
Expand Down Expand Up @@ -65,6 +69,21 @@ def create(request, html_name):
return render(request, 'target/create.html', {'form': form, 'target': target})


@login_required
def ping(request, target_id):
"""Ping a RedisTarget database using the test_connection() function."""
target = get_object_or_404(BaseTarget, pk=target_id)
if isinstance(target, RedisTarget):
try:
result = target.test_connection()
return JsonResponse({'success': result})
except exceptions.ConnectionError:
return HttpResponseBadRequest(
json.dumps({'success': False, 'error': 'Unable to connect to Redis'}), content_type='application/json'
)
return HttpResponseBadRequest(json.dumps({'success': False, 'error': 'Not a RedisTarget'}))


@login_required
def delete(request, target_id): # pylint: disable=unused-argument
"""Delete a target from the database."""
Expand Down