Create web interface for NTP server – install NodeJS, Express and MySQL (Part 1)

Posted by:

|

On:

|

The NTP server hardware has been properly assembled, connected, and configured to function correctly. The detail can be read at the following URL link:

https://cs-student.com/create-a-ntp-server-using-orange-pi-zero-2-and-gps-receiver/

Next, I plan to develop a web interface for adjusting the IP address and time, as well as for monitoring the received satellite information.

Let’s start !

(1) Install Node JS

Node.js is a JavaScript runtime that allows you to run JavaScript on the server side. In this project, Node.js will serve as the backend for your web application, handling requests, managing connections, and performing server-side logic.

Open the terminal on your Ubuntu system. Update the package index by running the following command:

sudo apt update
sudo apt install nodejs npm

If there are errors “Updates for this repository will not be applied”, the error messages indicate that the release files are not valid yet, which could be due to an incorrect system clock. Make sure your system clock is set correctly using command “date” , and try the update process again.

Verify the installation by checking the Node.js version:

node --version     --> v10.19.0
npm --version      --> 6.14.4

Run the following command to download and install nvm  (Node Version Manager):

curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.5/install.sh | bash

You should see the messages.

/usr/local/lib
└── express-generator@4.16.1
=> If you wish to uninstall them at a later point (or re-install them under your
=> `nvm` Nodes), you can remove them from the system Node as follows:

     $ nvm use system
     $ npm uninstall -g a_module

=> Close and reopen your terminal to start using nvm or run the following to use it now:

export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"  # This loads nvm
[ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion"  # This loads nvm bash_completion

After running the script, you need to load nvm in your terminal. You can do this by running:

export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"

To confirm that nvm is installed correctly, run:

nvm --version    ->0.39.5

Now you can install the latest version of Node.js:

nvm install node

Verify your Node.js installation:

node -v     ->v22.7.0
npm -v      ->10.8.2

(2) Install Express

Express is a web application framework for Node.js that simplifies the process of building web applications and APIs. In this project, Express will be used to create the web server, define routes, and handle HTTP requests from the client interface. It provides middleware support for handling requests, responses, and error management.

Once Node.js is installed, you can install Express.js using the Node Package Manager (npm). Open the terminal and run the following command to install Express.js globally:

sudo npm install -g express-generator

Create a new Express.js application:
First create a new folder under /home, say /dashboard with permission 777. Open the terminal and change the directory to /home/dashboard. Then run the following command:

express apps

You should see the messages.

warning: the default view engine will not be jade in future releases
warning: use `--view=jade' or `--help' for additional options
   create : apps/
   create : apps/public/
   create : apps/public/javascripts/
   create : apps/public/images/
   create : apps/public/stylesheets/
   create : apps/public/stylesheets/style.css
   create : apps/routes/
   create : apps/routes/index.js
   create : apps/routes/users.js
   create : apps/views/
   create : apps/views/error.jade
   create : apps/views/index.jade
   create : apps/views/layout.jade
   create : apps/app.js
   create : apps/package.json
   create : apps/bin/
   create : apps/bin/www

   change directory:
     $ cd apps

   install dependencies:
     $ npm install

   run the app:
     $ DEBUG=apps:* npm start

Following the instruction: change directory to apps and run “npm install”. Run the app by “npm start”. You can get the following message and enter the debug window of node. This debug window is very important and useful for JavaScript debugging.

> apps@0.0.0 start
> node ./bin/www

Open a web browser and type the following ip address of the NTP server with port number 3000:

http://192.168.2.180:3000/

You should see following messages in the browser. At the same time, you can see many useful messages at the node debug window.

Express
Welcome to Express

Great! Express has been successfully installed and run.

(3) Install MySQL2

MySQL is a relational database management system used to store and retrieve data. In this project, MySQL will be used to store configuration settings, logs, and user data related to the NTP server. This allows for persistent data storage and querying capabilities.

First install the latest version of MySQL Server on the Ubuntu system.

sudo apt install mysql-server

Navigate to your project directory /apps and then run:

npm install mysql2

Verify the installation of mysql2 by running the command. You should see a message indicating that the MySQL is installed successfully.

npm list mysql2

apps@0.0.0 /home/dashboard/apps
└── mysql2@3.11.0

 Verify the MySQL service is running by command. You should see a message indicating that the MySQL service is active and running.

sudo systemctl status mysql

● mysql.service - MySQL Community Server
     Loaded: loaded (/lib/systemd/system/mysql.service; enabled; vendor preset:>
     Active: active (running) since Mon 2024-09-02 00:47:22 HKT; 6min ago
   Main PID: 9220 (mysqld)
     Status: "Server is operational"
      Tasks: 37 (limit: 1119)
     Memory: 357.6M
     CGroup: /system.slice/mysql.service
             └─9220 /usr/sbin/mysqld

Sep 02 00:47:19 NTPserver systemd[1]: Starting MySQL Community Server...
Sep 02 00:47:22 NTPserver systemd[1]: Started MySQL Community Server.

Create username, password and database under MySQL2

First, log into the MySQL server from your terminal:

sudo mysql -u root -p

Enter password:xxxxxx
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 8
Server version: 8.0.39-0ubuntu0.20.04.1 (Ubuntu)

Copyright (c) 2000, 2024, Oracle and/or its affiliates.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql>

Once logged in, create a new database:

CREATE DATABASE ntpserver;

Create a new user and set a password:

CREATE USER 'felix'@'localhost' IDENTIFIED BY '123456';

Message: Query OK, 0 rows affected (0.07 sec)

Grant the new user permissions to the database for any host:

GRANT ALL PRIVILEGES ON ntpserver.* TO 'felix'@'%';

Make sure to flush the privileges to apply the changes:

FLUSH PRIVILEGES;

Message: Query OK, 0 rows affected (0.03 sec)

Exit the MySQL prompt by

EXIT;

Message: Bye

You can test the account ‘felix’ by the following command

sudo mysql -u felix -p

Enter password: 123456

Then you can enter MySQL command line

Anytime when you have leave the MYSQL command line, you can enter again by the following command

mysql

If you want to connect using the mysql2 package in a Node.js application, you can create a script “database.js” like the following and place that under directory /apps

const mysql = require('mysql2');

const connection = mysql.createConnection({
    host: 'localhost',
    user: 'felix',
    password: '123456',
    database: 'ntpserver'
});

connection.connect((err) => {
    if (err) {
        console.error('Error connecting: ' + err.stack);
        return;
    }
    console.log('MySQL Database is connected Successfully as id ' + connection.threadId);
});

function query(sql, params = []) {
  return new Promise((resolve, reject) => {
    connection.query(sql, params, (error, results, fields) => {
      if (error) {
        reject(error);
      } else {
        resolve(results);
      }
    });
  });
}

module.exports = connection;

Error for execute MySQL

sudo systemctl status mysql
mysql.service - MySQL Community Server
     Loaded: loaded (/lib/systemd/system/mysql.service; enabled; vendor preset: enabled)
     Active: failed (Result: exit-code) since Tue 2024-09-03 12:43:19 HKT; 9min ago
    Process: 3402 ExecStartPre=/usr/share/mysql/mysql-systemd-start pre (code=exited, status=0/SUCCESS)
    Process: 3410 ExecStart=/usr/sbin/mysqld (code=exited, status=1/FAILURE)
   Main PID: 3410 (code=exited, status=1/FAILURE)
     Status: "Server shutdown complete"
      Error: 2 (No such file or directory)

Sep 03 12:43:19 NTPserver systemd[1]: mysql.service: Scheduled restart job, restart counter is at 5.
Sep 03 12:43:19 NTPserver systemd[1]: Stopped MySQL Community Server.
Sep 03 12:43:19 NTPserver systemd[1]: mysql.service: Start request repeated too quickly.
Sep 03 12:43:19 NTPserver systemd[1]: mysql.service: Failed with result 'exit-code'.
Sep 03 12:43:19 NTPserver systemd[1]: Failed to start MySQL Community Server.

The output indicates that MySQL is failing to start because it cannot open the error log file located at /var/log/mysql/error.log. The log file maybe deleted accidently. Anyway, this typically means the directory does not exist, or the MySQL user does not have the necessary permissions to write to it. Here are the steps you can take to resolve this issue:

sudo mkdir -p /var/log/mysql             //Create the Log Directory
sudo chown mysql:mysql /var/log/mysql    //Ensure that the MySQL user has the correct permissions to write to the log directory
sudo touch /var/log/mysql/error.log      //creating an empty error log file
sudo chown mysql:mysql /var/log/mysql/error.log

Check log rotation setting:

cat /etc/logrotate.d/mysql-server
/var/log.hdd/mysql.log /var/log.hdd/mysql/*log {
	daily
	rotate 7
	missingok
	create 640 mysql adm
	compress
	sharedscripts
	postrotate
		test -x /usr/bin/mysqladmin || exit 0
		# If this fails, check debian.conf! 
		MYADMIN="/usr/bin/mysqladmin --defaults-file=/etc/mysql/debian.cnf"
		if [ -z "`$MYADMIN ping 2>/dev/null`" ]; then
		  # Really no mysqld or rather a missing debian-sys-maint user?
		  # If this occurs and is not a error please report a bug.
		  #if ps cax | grep -q mysqld; then
		  if killall -q -s0 -umysql mysqld; then
 		    exit 1
		  fi 
		else
		  $MYADMIN flush-logs
		fi
	endscript
}

Ensure that the path and file /var/log.hdd/mysql.log and /var/log.hdd/mysql exist and are correct. If the directory /var/log.hdd/ does not exist, the log rotation will fail. Create the folder and file if they do not exist.

Finally start the mysql service again:

sudo systemctl start mysql 

This script will be used later. That’s all for today. Let us continue later with real application.

Posted by

in