how to programmatically restart WAMP or Apache? - wamp

As part of some automated deploy + test scripts I use to verify programming done for a site, I have some scripts which update Apache's config files. I would like to programmatically restart WAMP so the changes take effect. Is there a good way to do this?
The scripts are powershell.
This is whats in my apache bin folder:
iconv
ab.exe
abs.exe
ApacheMonitor.exe
apr_dbd_odbc-1.dll
apr_ldap-1.dll
dbmmanage.pl
htcacheclean.exe
htdbm.exe
htdigest.exe
htpasswd.exe
httpd.exe
httxt2dbm.exe
libapr-1.dll
libapriconv-1.dll
libaprutil-1.dll
libeay32.dll
libhttpd.dll
logresolve.exe
openssl.exe
php.ini
php5isapi.dll
php5ts.dll
rotatelogs.exe
ssleay32.dll
wintty.exe
zlib1.dll

You can use this command to restart Wamp, Apache, MySQL services:
To start services
NET START wampapache
NET START wampmysqld
To stop services
NET STOP wampapache
NET STOP wampmysqld
For mariaDB, replace wampmysqld with wampmariadb.
For 64 bits: append 64 to the service names.

Simple execute command:
httpd.exe -k restart
ps. this is my wathdog for windows
#echo off
:loop
timeout /t 30 /nobreak
REM .
tasklist /FI "IMAGENAME eq php-cgi.exe" 2>NUL | find /I /N "php-cgi.exe">NUL
if "%ERRORLEVEL%"=="1" goto Process_NotFound
tasklist /FI "IMAGENAME eq httpd.exe" 2>NUL | find /I /N "httpd.exe">NUL
if "%ERRORLEVEL%"=="1" goto Process_NotFound
goto loop
:Process_NotFound
TASKKILL /F /IM php-cgi.exe
TASKKILL /F /IM httpd.exe
ping 127.0.0.1 -n 2
Apache -k start
ping 127.0.0.1 -n 3
cls
php.exe -r "$ch = curl_init(); curl_setopt($ch, CURLOPT_URL, 'http://server.name/'); curl_setopt($ch, CURLOPT_VERBOSE, 1); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_exec($ch);"
ping 127.0.0.1 -n 3
ab.exe -n 10 -c 3 http://server.name/
goto loop

CTRL+R -> Type (Command) -> Right Mouse -> Run Administrator
Go to your wamp aptech bin folder eg : D:\wamp\bin\apache\apache2.4.9\bin>
Type httpd.exe -d (Show All apache parameter command )
httpd.exe -k start -n wampapache64
httpd.exe -k stop -n wampapache64
httpd.exe -k restart -n wampapache64
Graphical Instruction :
Step First:
Step Second:

I ended up writing some code to find the "wampapache" service and restarting it.
public static void ResetApache()
{
ServiceUtil.RestartService("wampapache", 10000);
}
...
public class ServiceUtil
{
public static void RestartService(string serviceName, int msTimeout)
{
ServiceController service = new ServiceController(serviceName);
int startTicks = Environment.TickCount;
TimeSpan timeout = TimeSpan.FromMilliseconds(msTimeout);
if (service.Status != ServiceControllerStatus.Stopped
&& service.Status != ServiceControllerStatus.StopPending)
{
service.Stop();
}
service.WaitForStatus(ServiceControllerStatus.Stopped, timeout);
int midTicks = Environment.TickCount;
timeout = TimeSpan.FromMilliseconds(msTimeout - (midTicks - startTicks));
service.Start();
service.WaitForStatus(ServiceControllerStatus.Running, timeout);
//int finalTicks = Environment.TickCount;
//var totalTime = TimeSpan.FromTicks(finalTicks - startTicks);
//Console.WriteLine("Reseting process took " + (totalTime.TotalMilliseconds/1000.0) + " seconds.");
}
}

Related

How can I install Oracle Database 18c XE into Windows docker container?

I'm not able to install Oracle Database 18c Express Edtition into a Windows docker container.
The Oracle silent setup (documented here) reports success, but no installation is being performed. The destination directory (C:\OracleXE\) is empty. And, of course, nothing is installed.
What am I doing wrong here?
This is my Dockerfile
# escape=`
FROM mcr.microsoft.com/windows:20H2
USER ContainerAdministrator
COPY / /O18c
WORKDIR /O18c
SHELL ["PowerShell", "-Command"]
RUN New-Item 'C:\db-data' -ItemType Directory; New-LocalUser -Name OracleAdministrator -NoPassword -UserMayNotChangePassword -AccountNeverExpires; Set-LocalUser -Name OracleAdministrator -PasswordNeverExpires:$True; $adm = (Get-LocalGroup | Where-Object {$_.Name.IndexOf('Admin') -eq 0}).Name; Add-LocalGroupMember -Group $adm -Member OracleAdministrator
USER OracleAdministrator
RUN ./Setup.exe /s /v"RSP_FILE=C:\O18c\XEInstall.rsp" /v"/L*v C:\O18c\setup.log" /v"/qn"
EXPOSE 1521 5550 3389
VOLUME C:\db-data
ENTRYPOINT PowerShell
This is my XEInstall.rsp file
#Do not leave any parameter with empty value
#Install Directory location, username can be replaced with current user
INSTALLDIR=C:\OracleXE\
#Database password, All users are set with this password, Remove the value once installation is complete
PASSWORD=foobar123!
#If listener port is set to 0, available port will be allocated starting from 1521 automatically
LISTENER_PORT=0
#If EM express port is set to 0, available port will be used starting from 5550 automatically
EMEXPRESS_PORT=0
#Specify char set of the database
CHAR_SET=AL32UTF8
This is my directory structure:
This is my docker build command:
docker build -f .\Dockerfile .\OracleXE184_Win64\
Apparently, the Oracle setup doesn't work with PowerShell.
When run with standard command prompt, setup installs fine.
This is my working Dockerfile
# escape=`
FROM mcr.microsoft.com/windows:20H2
USER ContainerAdministrator
COPY / /O18c
WORKDIR /O18c
RUN PowerShell -Command "New-Item 'C:\db-data' -ItemType Directory; New-LocalUser -Name OracleAdministrator -NoPassword -UserMayNotChangePassword -AccountNeverExpires; Set-LocalUser -Name OracleAdministrator -PasswordNeverExpires:$True; $adm = (Get-LocalGroup | Where-Object {$_.Name.IndexOf('Admin') -eq 0}).Name; Add-LocalGroupMember -Group $adm -Member OracleAdministrator;"
USER OracleAdministrator
RUN setup.exe /s /v"RSP_FILE=C:\O18c\XEInstall.rsp" /v"/L*v C:\O18c\setup.log" /v"/qn"
RUN PowerShell -Command "Get-ChildItem; Get-ChildItem \ -Attributes Directory;"
EXPOSE 1521 5550 3389
VOLUME C:\db-datado
ENTRYPOINT PowerShell

AWS - WebSockets not connected over HTTPS

i have django web application deployed on aws elastic beanstalk
and i am using websockets in part of it also
,i have installed application load balancer which is supposed to support websockets by default
https://aws.amazon.com/elasticloadbalancing/details/
but when establishing connection ( only in HTTPS ) i receive this
WebSocket is closed before the connection is established
there is no problem in HTTP it works just fine
Here is loadbalancer config
here is how i connect in js
const ws_path = 'wss://<IPv4 Public IP>:5000';
const websocket = new ReconnectingWebSocket(ws_path,
null, {maxReconnectAttempts: 5, timeoutInterval: 5000});
PORT 5000 is where daphne running my django application
and my apache config
files: "/opt/elasticbeanstalk/hooks/appdeploy/post/run_supervised_daemon.sh":
mode: "000755"
owner: root
group: root
content: |
#!/usr/bin/env bash
# Get django environment variables
djangoenv=`cat /opt/python/current/env | tr '\n' ',' | sed 's/%/%%/g' | sed 's/export //g' | sed 's/$PATH/%(ENV_PATH)s/g' | sed 's/$PYTHONPATH//g' | sed 's/$LD_LIBRARY_PATH//g'`
djangoenv=${djangoenv%?}
# Create daemon configuraiton script
daemonconf="[program:daphne]
; Set full path to channels program if using virtualenv
command=/opt/python/run/venv/bin/daphne -b 0.0.0.0 -p 5000 _myapp.asgi:channel_layer
directory=/opt/python/current/app
user=ec2-user
numprocs=1
stdout_logfile=/var/log/stdout_daphne.log
stderr_logfile=/var/log/stderr_daphne.log
autostart=true
autorestart=true
startsecs=10
; Need to wait for currently executing tasks to finish at shutdown.
; Increase this if you have very long running tasks.
stopwaitsecs = 600
; When resorting to send SIGKILL to the program to terminate it
; send SIGKILL to its whole process group instead,
; taking care of its children as well.
killasgroup=true
; if rabbitmq is supervised, set its priority higher
; so it starts first
priority=998
environment=$djangoenv
[program:worker]
; Set full path to program if using virtualenv
command=/opt/python/run/venv/bin/python manage.py runworker
directory=/opt/python/current/app
user=ec2-user
numprocs=1
stdout_logfile=/var/log/stdout_worker.log
stderr_logfile=/var/log/stderr_worker.log
autostart=true
autorestart=true
startsecs=10
; Need to wait for currently executing tasks to finish at shutdown.
; Increase this if you have very long running tasks.
stopwaitsecs = 600
; When resorting to send SIGKILL to the program to terminate it
; send SIGKILL to its whole process group instead,
; taking care of its children as well.
killasgroup=true
; if rabbitmq is supervised, set its priority higher
; so it starts first
priority=998
environment=$djangoenv"
# Create the supervisord conf script
echo "$daemonconf" | sudo tee /opt/python/etc/daemon.conf
# Add configuration script to supervisord conf (if not there already)
if ! grep -Fxq "[include]" /opt/python/etc/supervisord.conf
then
echo "[include]" | sudo tee -a /opt/python/etc/supervisord.conf
echo "files: daemon.conf" | sudo tee -a /opt/python/etc/supervisord.conf
fi
# Reread the supervisord config
sudo /usr/local/bin/supervisorctl -c /opt/python/etc/supervisord.conf reread
# Update supervisord in cache without restarting all services
sudo /usr/local/bin/supervisorctl -c /opt/python/etc/supervisord.conf update
# Start/Restart processes through supervisord
sudo /usr/local/bin/supervisorctl -c /opt/python/etc/supervisord.conf restart daphne
sudo /usr/local/bin/supervisorctl -c /opt/python/etc/supervisord.conf restart worker
and ssl_config
files:
"/etc/httpd/conf.d/ssl_rewrite.conf":
mode: "000644"
owner: root
group: root
content: |
RewriteEngine On
ProxyRequests Off
RewriteCond %{HTTP:UPGRADE} ^WebSocket$ [NC]
RewriteCond %{HTTP:CONNECTION} ^Upgrade$ [NC]
<If "-n '%{HTTP:X-Forwarded-Proto}' && %{HTTP:X-Forwarded-Proto} != 'https'">
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R,L]
</If>

AWK catching a regular expression

I have been using this little script for months now with success. Today I realize there is one output it cant seem to catch, screen comes up blank with a new prompt:
user#computer ~]$ myscan ipsFile 23
user#computer ~]$
Here is the code
#!/bin/bash
sudo nmap -v -Pn -p T:$2 -reason -i $1 | awk ' {
if (/syn-ack/) {
print "Yes"
c++
}
else if (/no-response|reset|host-unreach/) {
print "No"
c++
}
}
END { print c} '
If I run the nmap against one of the IPs then it returns
Starting Nmap 5.51 ( http://nmap.org ) at 2017-09-26 11:44 CDT
Initiating Parallel DNS resolution of 1 host. at 11:44
Completed Parallel DNS resolution of 1 host. at 11:44, 0.00s elapsed
Initiating Connect Scan at 11:44
Scanning 1.1.1.1 [1 port]
Completed Connect Scan at 11:44, 0.20s elapsed (1 total ports)
Nmap scan report for 1.1.1.1
Host is up, received user-set (0.20s latency).
PORT STATE SERVICE REASON
23/tcp filtered telnet host-unreach
Read data files from: /usr/share/nmap
Nmap done: 1 IP address (1 host up) scanned in 0.26 seconds
How can I catch the 'host-unreach' portion?
Let's try and debug this. Execute this:
nmap -v -Pn -p T:23 -reason -i ipsFile | awk '{print $0}/syn-ack/{print "Yes";c++}/no-response|reset|host-unreach/{print "No";c++}END {print c}' > out.txt
The only difference here is that the awk script prints $0 (i.e. the output of your nmap calls) to file out.txt. Try to grep your unreach value.
I tried this myself and found that instead of a host-unreach I got a net-unreach. Might be the same thing in your case.
Have you tried piping stderr to stdout like
#!/bin/bash
sudo nmap -v -Pn -p T:$2 -reason -i $1 2>&1 | awk ' {
if (/syn-ack/) {
print "Yes"
c++
}
else if (/no-response|reset|host-unreach/) {
print "No"
c++
}
}
END { print c} '

Three task batch files for my game servers

I need 3 different batch files for 3 different tasks:
-log the output of HldsUpdateTool.exe console, so far I don't see what's going on but I managed this:
#echo off
echo Updating...
call :Logit>>log.txt 2>&1
exit /b 0
:Logit
hldsupdatetool.exe -command update -game "Counter-Strike Source" -dir "Source 2007 Dedicated Server" -verify_all -retry
start notepad log.txt
-clean this log to get a files and folders list; the log will look like this:
Checking bootstrapper version ...
Updating Installation
Determining which depot(s) to install/update...
5 depot(s) will be installed/updated
0:30 Checking local files and building download list for depot 242 'Counter-Strike Source Shared' version 126
0:30 Connecting content server session for version 126
0:31 [80.239.194.146:27030] Connecting...
0:31 [80.239.194.146:27030] Connection established; handshaking...
0:31 [80.239.194.146:27030] Sending login message...
0:31 Fetching version 126 manifest
0:41 Reading version 126 checksum table
0:54 Calculating download size and verifying checksums
0:54 Checking...: /
0:54 Checking...: cstrike
0:54 Checking...: cstrike\bin
0:54 Checking...: cstrike\cfg
0:54 Checking...: cstrike\classes
0:54 Checking...: cstrike\maps
0:54 Checking...: cstrike\maps\graphs
0:54 Checking...: cstrike\maps\soundcache
0:57 Checking...: cstrike\materials
0:57 Checking...: cstrike\materials\brick
0:57 Checking...: cstrike\materials\buildings
0:57 Checking...: cstrike\materials\carpet
0:57 Checking...: cstrike\materials\composite
0:57 Checking...: cstrike\materials\concrete
0:58 Checking...: cstrike\materials\console
etc... later on files do not have extensions!
-clean the server folder from any files or folders not listed!
I did search around for 2 days but this is as far as I can go by myself...
You can shorten that to
#echo off
hldsupdatetool.exe -command update -game "Counter-Strike Source" -dir "Source 2007 Dedicated Server" -verify_all -retry >Log.txt
start notepad Log.txt
The problem with the files not showing extensions will be down to the program you are running, all the batch does is call the exe and redirect the output.
First of all,I'm a definitely newer to batch :)
As for the 2nd question:
-clean this log to get a files and folders list; the log will look like this:
for /f "tokens=3" %G in ('findstr /i /c:"checking..." log.txt')do echo %G>>_.log
May it works for you.
Update:
I download your log.txt and test immediately,this is the result(file names _.log):
/
cstrike
cstrike\bin
cstrike\cfg
cstrike\classes
cstrike\maps
cstrike\maps\graphs
cstrike\maps\soundcache
cstrike\materials
cstrike\materials\brick
cstrike\materials\buildings
cstrike\materials\carpet
cstrike\materials\composite
cstrike\materials\concrete
cstrike\materials\console
cstrike\materials\cs_assault
cstrike\materials\cs_havana
cstrike\materials\cs_italy
cstrike\materials\cstrike
cstrike\materials\de_aztec
cstrike\materials\de_cbble
cstrike\materials\de_chateau
cstrike\materials\de_dust
cstrike\materials\de_nuke
cstrike\materials\de_piranesi
cstrike\materials\de_prodigy
cstrike\materials\de_tides
cstrike\materials\de_train
cstrike\materials\decals
cstrike\materials\decals\concrete
cstrike\materials\decals\metal
cstrike\materials\decals\wood
...
Maybe i misunderstood your meaning?
Update again
As for 3rd question
#echo off
set /p origin=Where is the original folder?(Type absoulute path directly.)
echo origin: %origin%
set /p destin=Where can i put file temporarily(Type absoulute path directly.)
echo destination :%destin%
for /f %%G in (_.log) do (
if "%%G"=="/" (
echo.
) else (
xcopy %origin%\%%G %destin%\%%G /H /K /R /E /D /I /Y
))
rm -rf %origin%
set /p origin=What is the name of original folder?(Type name)
rename %destin% %origin%
May it help you!
Update the third time :)
Because the first edition maybe little confusing for you.Sorry for my lacking of ability ti code well.
#echo off
setlocal enabledelayedexpansion
set MAXNUM=100
set /p origin=Where is the original folder?(Type absoulute path directly.)
echo origin: %origin%
set backup_origin=%origin%
for /L %%H in (1,1,%MAXNUM%) do (
for /F "delims=\" %%G in ("!origin!") do (
set name=%%G
set origin=!origin:%%G\=!
))
set father=!backup_origin:\%name%=!
xcopy !father!\!name! !father!\backup_!name! /H /K /R /E /D /I /Y
::copy files
rm -rf !father!\!name!
::delete origin
rename !father!\backup_!name! !name!
::rename the new folder using the old's name
if your files are in such an format C:\template\example\cstrike\materials\brick,you should just type c:\template\example,which includes \hl2 \cstrike and so on.
I work on Win7,which you may not.So I recommend you to adjust my batch file to your OS.Before running ,check that you have xcopy,rm,rename working for you.T

How can I reliably launch multiple DJango FCGI servers at startup?

I currently use the following script to launch my DJango FCGI servers:
#!/bin/bash
MYAPP=$1
PIDFILE=/var/run/${MYAPP}_fcgi.pid
SOCKET=/var/django/${MYAPP}/socket.sock
MANAGESCRIPT=/var/django/${MYAPP}/manage.py
# Maximum requests for a child to service before expiring
#MAXREQ=
# Spawning method - prefork or threaded
#METHOD=
# Maximum number of children to have idle
MAXSPARE=2
# Minimum number of children to have idle
MINSPARE=1
# Maximum number of children to spawn
MAXCHILDREN=3
cd "`dirname $0`"
function failure () {
STATUS=$?;
echo; echo "Failed $1 (exit code ${STATUS}).";
exit ${STATUS};
}
function start_server () {
$MANAGESCRIPT runfcgi socket=$SOCKET pidfile=$PIDFILE \
${MAXREQ:+maxrequests=$MAXREQ} \
${METHOD:+method=$METHOD} \
${MAXSPARE:+maxspare=$MAXSPARE} \
${MINSPARE:+minspare=$MINSPARE} \
${MAXCHILDREN:+maxchildren=$MAXCHILDREN} \
${DAEMONISE:+damonize=True}
touch $SOCKET
chown www-data:www-data $SOCKET
chmod 755 $SOCKET
}
function stop_server () {
if [ -f "$PIDFILE" ]
then
kill `cat $PIDFILE` || failure "Server was not running."
rm $PIDFILE
fi
}
DAEMONISE=$3
case "$2" in
start)
echo -n "Starting fcgi: "
[ -e $PIDFILE ] && { echo "PID file exsts."; exit; }
start_server || failure "starting fcgi"
echo "Done."
;;
stop)
echo -n "Stopping fcgi: "
[ -e $PIDFILE ] || { echo "No PID file found."; exit; }
stop_server
echo "Done."
;;
restart)
echo -n "Restarting fcgi: "
[ -e $PIDFILE ] || { echo -n "No PID file found..."; }
stop_server
start_server || failure "restarting fcgi"
echo "Done."
;;
*)
echo "Usage: $0 {start|stop|restart} [--daemonise]"
;;
esac
exit 0
Which I manually call like this:
/var/django/server.sh mysite start
This works fine but when my hosting company reboots our server it leaves me two issues:
I don't have an automated way to launch multiple sites.
I end up with a mysite_fcgi.pid file existing but no associated process.
So I have two questions:
How can I launch a list of sites (stored in a plain text file) automatically on startup? i.e. call /var/django/server.sh mysite1 start then /var/django/server.sh myothersite start?
How can I get rid of the .pid file if the process doesn't exist and attempt to start the server as normal?
Create an init script and assign it to the appropriate runlevel.
You need to implement this in your startup/init script (that you would write in step 1)
Or, use a process manager like supervisord which takes care of all your concerns.
Here is a configuration example for fcgi from supervisord.
[fcgi-program:fcgiprogramname]
command=/usr/bin/example.fcgi
socket=unix:///var/run/supervisor/%(program_name)s.sock
process_name=%(program_name)s_%(process_num)02d
numprocs=5
priority=999
autostart=true
autorestart=unexpected
startsecs=1
startretries=3
exitcodes=0,2
stopsignal=QUIT
stopwaitsecs=10
user=chrism
redirect_stderr=true
stdout_logfile=/a/path
stdout_logfile_maxbytes=1MB
stdout_logfile_backups=10
stderr_logfile=/a/path
stderr_logfile_maxbytes=1MB
stderr_logfile_backups
environment=A=1,B=2
How can I launch a list of sites (stored in a plain text file) automatically on startup?
In general, your OS provides a file where you can hook your commands at startup. For example, arch linux uses rc.local, gentoo either /etc/local.start either /etc/local.d/*.start, debian requires you to make an init script - which is basically a script that takes "start" or "stop" as argument and lives in /etc/init.d or /etc/rc.d depending on the distribution ...
You can use some bash code as such.
for site in $(</path/to/text/file); do
/var/django/server.sh $site start
done
How can I get rid of the .pid file if the process doesn't exist and attempt to start the server as normal?
if [[ -f $PIDFILE ]]; then # if pidfile exists
if [[ ! -d /proc/$(<$PIDFILE)/ ]]; then # if it contains a non running proc
unlink $PIDFILE # delete the pidfile
fi
fi