Adding support for start, restart, stop

This commit is contained in:
sergiotarxz 2021-11-13 14:06:43 +01:00
parent e16a5e52fa
commit 9c1f1a7ecd

View File

@ -60,11 +60,7 @@ sub handle_del {
my $name = $params{name};
my $dbh = Cualsea::Server::DB->dbh();
my $service = $dbh->selectrow_hashref( <<"EOF", undef, $name );
SELECT name FROM services WHERE name = ?
EOF
if ( !defined $service ) {
if ( !check_if_service_exists_in_db($name) ) {
return {
is_error => 1,
desc => 'Service not found.',
@ -83,6 +79,98 @@ EOF
};
}
sub check_if_service_exists_in_db {
my $name = shift;
my $dbh = Cualsea::Server::DB->dbh();
my $service = $dbh->selectrow_hashref( <<"EOF", undef, $name );
SELECT name FROM services WHERE name = ?
EOF
if ( !defined $service ) {
return 0;
}
return 1;
}
sub handle_start {
my %params = @_;
my $name = $params{name};
if ( !check_if_service_exists_in_db($name) ) {
return {
is_error => 1,
desc => 'Service not found.',
status => 404,
};
}
if ( _is_started_service($name) ) {
return {
is_error => 1,
desc => 'Service already started.',
status => 400,
};
}
system 'sudo', "/etc/init.d/$name", 'start';
return {
is_error => 0,
desc => 'Service started.',
status => 200,
};
}
sub _is_started_service {
my $name = shift;
return !system "/etc/init.d/$name", 'status';
}
sub handle_stop {
my %params = @_;
my $name = $params{name};
if ( !check_if_service_exists_in_db($name) ) {
return {
is_error => 1,
desc => 'Service not found.',
status => 404,
};
}
if ( !_is_started_service($name) ) {
return {
is_error => 1,
desc => 'Service already stopped.',
status => 400,
};
}
system 'sudo', "/etc/init.d/$name", 'stop';
return {
is_error => 0,
desc => 'Service stopped.',
status => 200,
};
}
sub handle_restart {
my %params = @_;
my $name = $params{name};
if ( !check_if_service_exists_in_db($name) ) {
return {
is_error => 1,
desc => 'Service not found.',
status => 404,
};
}
system 'sudo', "/etc/init.d/$name", 'restart';
return {
is_error => 0,
desc => 'Service restarted.',
status => 200,
};
}
my %COMMANDS = (
add => {
params => [
@ -108,7 +196,7 @@ my %COMMANDS = (
name => { type => Str },
}
),
handle => \&handle_del
handle => \&handle_del,
},
report => {
params => [],
@ -121,6 +209,7 @@ my %COMMANDS = (
name => { type => Str },
}
),
handle => \&handle_start,
},
stop => {
params => ['name'],
@ -129,6 +218,7 @@ my %COMMANDS = (
name => { type => Str },
}
),
handle => \&handle_stop,
},
restart => {
params => ['name'],
@ -137,6 +227,7 @@ my %COMMANDS = (
name => { type => Str },
}
),
handle => \&handle_restart,
}
);