Skip to content

Commit

Permalink
Php core app changes (#40)
Browse files Browse the repository at this point in the history
* Make the app run via docker compose

* Add basic DB monitoring

* Refactoring
  • Loading branch information
prathamesh-sonpatki authored Dec 27, 2024
1 parent 442304c commit 2307d0e
Show file tree
Hide file tree
Showing 8 changed files with 472 additions and 124 deletions.
7 changes: 6 additions & 1 deletion php/core/7.3/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@ RUN apt-get update && apt-get install -y \
git \
unzip \
libzip-dev \
&& docker-php-ext-install zip
default-mysql-client \
&& docker-php-ext-install zip pdo pdo_mysql \
&& docker-php-ext-enable pdo_mysql

# Install Composer
RUN curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer
Expand All @@ -16,6 +18,9 @@ WORKDIR /var/www/html
# Copy composer files first
COPY composer.json ./

# Copy the last9 directory
# COPY last9/ ./last9/

# Debug: List contents after copying composer.json
RUN ls -la && \
# Run composer install with verbose output
Expand Down
4 changes: 2 additions & 2 deletions php/core/7.3/composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
},
"autoload": {
"psr-4": {
"App\\": "src/"
"Last9\\": "last9/"
}
}
}
}
23 changes: 22 additions & 1 deletion php/core/7.3/docker-compose.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,25 @@ services:
- OTEL_EXPORTER_OTLP_ENDPOINT=${LAST_OTEL_EXPORTER_OTLP_ENDPOINT}
- OTEL_SERVICE_NAME=my-demo-service
- OTEL_DEPLOYMENT_ENVIRONMENT=production
- OTEL_LOG_LEVEL=debug
- OTEL_LOG_LEVEL=debug
- DB_HOST=db
- DB_USER=diceuser
- DB_PASSWORD=dicepass
- DB_NAME=dicedb
depends_on:
- db

db:
image: mariadb:10.5
environment:
MYSQL_ROOT_PASSWORD: rootpass
MYSQL_DATABASE: dicedb
MYSQL_USER: diceuser
MYSQL_PASSWORD: dicepass
volumes:
- db_data:/var/lib/mysql
ports:
- "3306:3306"

volumes:
db_data:
110 changes: 84 additions & 26 deletions php/core/7.3/index.php
Original file line number Diff line number Diff line change
@@ -1,34 +1,92 @@
<?php
require __DIR__ . '/vendor/autoload.php';
require __DIR__ . '/instrumentation.php';
require __DIR__ . '/last9/instrumentation.php';

// Simple router
$uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
// Use our DB class instead of PDO directly
$pdo = \Last9\DB::connect(
"mysql:host=" . getenv('DB_HOST') . ";dbname=" . getenv('DB_NAME'),
getenv('DB_USER'),
getenv('DB_PASSWORD')
);

// Create table if not exists
try {
$pdo->exec("CREATE TABLE IF NOT EXISTS dice_rolls (
id INT AUTO_INCREMENT PRIMARY KEY,
roll_value INT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)");
} catch (\Exception $e) {
error_log("Error creating table: " . $e->getMessage());
}

// Get HTTP method and create operation name
$method = $_SERVER['REQUEST_METHOD'];
$operationName = $method . ' ' . $uri;
// Initialize instrumented HTTP client
$http = new \Last9\InstrumentedHttpClient([
'timeout' => 5,
'connect_timeout' => 2,
'verify' => false // Added to handle HTTPS issues
]);

$uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);

// Route handling
switch ($uri) {
case '/':
echo "Hello World!";
// Instrument the HTTP request with path-based operation name
instrumentHTTPRequest($operationName, []);
break;
try {
switch ($uri) {
case '/':
echo "Hello World!";
break;

case '/rolldice':
$result = random_int(1, 6);

// Instrument the HTTP request with path-based operation name
instrumentHTTPRequest($operationName, ['result' => strval($result)]);

echo "Rolled dice result: $result";
break;
case '/rolldice':
$result = random_int(1, 6);

// Insert new roll
$stmt = $pdo->prepare("INSERTT INTO dice_rolls (roll_value) VALUES (?)");
$stmt->execute([$result]);

// Get last 5 rolls with error logging
try {
$stmt = $pdo->prepare("SELECT roll_value, created_at FROM dice_rolls ORDER BY created_at DESC LIMIT 5");
$stmt->execute();
$previousRolls = $stmt->fetchAll(\PDO::FETCH_ASSOC);
// error_log("Previous rolls: " . print_r($previousRolls, true));
} catch (\Exception $e) {
error_log("Error fetching previous rolls: " . $e->getMessage());
$previousRolls = [];
}

// Make external API call with error handling
try {
$response = $http->request('GET', "http://numbersapi.com/{$result}/math", [
'headers' => [
'Accept' => 'text/plain',
'User-Agent' => 'PHP/1.0'
],
'verify' => false, // Disable SSL verification for testing
'timeout' => 30
]);
$numberFact = $response->getBody();
error_log("Number fact API response: " . $numberFact);
} catch (\Exception $e) {
error_log("Error fetching number fact: " . $e->getMessage() . "\n" . $e->getTraceAsString());
$numberFact = "Could not fetch fact due to: " . $e->getMessage();
}

$response = [
'current_roll' => $result,
'fact' => "test",
'previous_rolls' => $previousRolls
];

// error_log("Sending response: " . print_r($response, true));
echo json_encode($response, JSON_PRETTY_PRINT);
break;

default:
header("HTTP/1.0 404 Not Found");
instrumentHTTPRequest($operationName, ['result' => strval($result)]);
echo "404 Not Found";
break;
default:
http_response_code(404);
echo "404 Not Found";
break;
}
} catch (Exception $e) {
error_log("Main error: " . $e->getMessage());
http_response_code(500);
echo "Error: " . $e->getMessage();
}
94 changes: 0 additions & 94 deletions php/core/7.3/instrumentation.php

This file was deleted.

44 changes: 44 additions & 0 deletions php/core/7.3/last9/instrumentHttpClient.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
<?php
namespace Last9;

use GuzzleHttp\Client;

class InstrumentedHttpClient {
private $client;

public function __construct(array $config = []) {
$this->client = new Client($config);
}

public function request($method, $uri, array $options = []) {
$spanData = \Last9\createSpan(
'http.client',
\Last9\Instrumentation::getRootSpanId(),
[
['key' => 'http.method', 'value' => ['stringValue' => $method]],
['key' => 'http.url', 'value' => ['stringValue' => $uri]],
['key' => 'http.flavor', 'value' => ['stringValue' => '1.1']],
['key' => 'network.protocol.name', 'value' => ['stringValue' => 'http']],
['key' => 'network.protocol.version', 'value' => ['stringValue' => '1.1']]
]
);

try {
$response = $this->client->request($method, $uri, $options);
\Last9\endSpan($spanData,
['code' => 1],
[
['key' => 'http.status_code', 'value' => ['intValue' => $response->getStatusCode()]],
['key' => 'http.response.body.size', 'value' => ['intValue' => strlen($response->getBody())]]
]
);
return $response;
} catch (\Exception $e) {
\Last9\endSpan($spanData,
['code' => 2, 'message' => $e->getMessage()],
[['key' => 'error.message', 'value' => ['stringValue' => $e->getMessage()]]]
);
throw $e;
}
}
}
Loading

0 comments on commit 2307d0e

Please sign in to comment.