How to detect a power failure? - php

I want to be able to perform an action on power failure i.e when electricity goes off since my network routers are on UPS so it doesn't know about power failures so somehow I want to be able to store the power failure data into a text file through php so anyway possible to write power-failure data to a text file through PHP??
Here is a screenshot of Mikrotik with different windows open regarding the question :

There is no proper way of doing this.
First of, you need an external machine.
Why? Because if a machine shuts down because it has no power, it cannot execute code anymore !
So here is what I thought:
If you have a server running on the routers that can be accessed remotly, you could simply "ping" ("file_get_contents" or "curl") your router with requests. If you get an error, that means it's not online anymore. And then store this into a text file.
If you want to use a local laptop to do this, you could just simply "ping" your router location (could be 192.168.0.1, depends on your router) and if it doesn't respond, that means it's offline.

Most UPS devices have SNMP server where you can query simple statistics (definitely Power failures).
There are some linux packages for instance nut-snmp, which you could use to get information from the UPS.

Related

PHP and server-to-server communication in LAN

I am doing a project that has to incorporate load-balancing using OpenStack platform. It boils down to spreading browser requests, that execute calculation-heavy scripts, across several virtual machines running some distro of Linux.
Due to all installation attempts of OpenStack going horribly wrong, I ended up using TryStack.org, which is a free and working environment. The obvious problem here is, it offers very limited resources. For instance, I can have only 1 floating (external) IP, which can be assigned to only 1 single instance (virtual machine) and there are measures that make it impossible to change it via API.
Due to those limitations, I have to work with a very peculiar setup: I have a network with nodes A, B and C. A, B and C can communicate with each other, but only A has an external IP, ie. is accessible by browser.
(illustration)
Therefore, I have to:
direct all browser requests to A,
have A request (and wait for) execution of calculation-heavy scripts on B/C,
make B/C send back results once they are finished
and finally have A dress results in HTML and send response back to the browser.
Is there any mechanism in PHP that can do 2. and 3.? If not, what (Linux-compatible) language/technology can do that? (I have already written almost all of the code in PHP, but I suppose I can switch.)
Alternatively: is there some other free OpenStack service that would allow me to give every instance an IP (in which case the spreading problem could be solved via simple redirects)?
As arkascha advised in the comments, I used curl to simply send a page request from A to B/C, and then parsed the page using text manipulation.

Webserver from linux(debian) sends data to an Ip in a network

Hi,
From the image above, I have a webserver a linux machine and client/device.. Now i need for this 3 to communicate. The webserver sends data to an ip address(client/device) based on button pressed on the webpage. but before the data is sent, the data must first access the linux machine, the machine then sends the data down to the device which then the device reads the data and act based on the command sent.. then the device sends back data to the linux machine which then the linux machine sends it to the webserver for ack'd. meaning data is received by the device without any problems.
Php is for the webserver. Now how will php sends data to an ip adress.
The linux machine handles all requests and sends everything down to the device and when the device got the data it will send a data to linux machine which then machine sends an ok to the webserver that the data arrived succesfully.(I read about socket programming and i think of creating an application that reads requests.) or if you have any idea how can i do this?.
How can the device read a data sent by the webserver?..
Thanks,
EDIT: The device is not connected to the linux machine. the device is only connnected via the ethernet cable.
Let's call the topmost machine 'Server', the middle machine 'Controller' and the bottom machine 'Device'. It does not matter if the device is a peripheral (say, USB or serial device), or a computer.
The first task is to get the Controller to query the Device. The best way to do this really depends on the Device. If you consider things like USB audio/video devices, they need to be tuned, then they send a continuous stream of data. Things like temperature or humidity sensors are told to do a measurement, then they respond with data.
Usually you write the required functions into a small library, and verify it works using command line tools. In some cases the library may not be necessary, for example if the Device is already supported by the kernel in Controller, and the information is trivially available. (For example, consider the temperature sensors in hard drives: if Device(s) are hard disks, then Controller can simply use the command hddtemp /dev/sda to get the temperature of the /dev/sda (first SATA/ATA/SCSI hard disk). I'd expect the end user to be able to pick which hard disks she is interested in, so that choice would have to flow from Server to Controller.)
Next, you write a service that will run on the Controller. This service will incorporate the library functions already written and tested, so it can easily access the Device. (This way you know the Controller-Device communication works, and don't need to worry about it. One thing at a time.)
There are many different designs for the service, from plain TCP/IP or UDP/IP sockets to Remote Procedure Calls (RPC), to high-level protocols like HTTP. In recent years, the last, using HTTP, has become more and more common, with responses being XML, plain text, or binary media (usually images). The idea is to have the service be basically just another web server that can access the Device directly. Security is simpler, because it does not need to be world-accessible: it can very well only answer to requests coming from the Server only. I've written such services using basic shell scripting (Bash), PHP (both PHP-CGI and command-line PHP, PHP-CLI), and C, among others. The best choice depends on the details, really. I personally prefer either a simple text-based TCP/IP socket, or HTTP.
On the Server, you can write a PHP page, that connects to Controller, requesting whatever it wants to request (usually depends on user data, first checked for sanity and safety, of course). PHP has easy built-in facilities for doing both HTTP requests and connecting using raw TCP/IP, so it suits quite well for this. If HTTP protocol wrappers are enabled, then it is just $handle = fopen("http://192.168.x.x/myservice?param1=" . urlencode($param1) . "&param2=" . urlencode($param2), "r+b");. To get a socket connection, you use the fsockopen() function instead. (For details, see fopen(), http wrappers, and fsockopen() at the PHP Function Reference at www.php.net.)
In practice the PHP page code first creates a connection to the Controller. Then it sends a request, containing the relevant sanitized commands/parameters received from the end user. Then it waits for the Controller to respond with the results (by simply reading the response), then closes the connection. The response should contain all the data needed, so the PHP page is free to construct the page to the end user.
None of this is really difficult, but there is a lot to do. I've found the Controller-Device communication to require the most work; after that is done, the rest has always been quite straightforward.
If you can provide more details what the Controller-Device connection is, what kind of data (text? numbers? images? a lot of binary data?) the Device provides, and what kind of parameters/commands (just "one result, please?", basic commands like "move up", "where are you?") do you expect you need to send to the Controller/Device, I could perhaps be more specific.
Also, are you limited to PHP, or would you be comfortable writing the Controller service using C? I've found that to be a very good combination myself.
Edited to add:
In a nutshell, the three points can be answered as follows:
Either using fopen("http://ip.add.re.ss:port/", "r+b"); if using the HTTP protocol and PHP is configured to allow http wrappers (they usually are), or using fsockopen(). See the PHP documentation linked above for details.
With an IP-connected Device, Controller is basically a relay or translator. Usually this means a daemon running on Controller, managing incoming requests from Server (or Servers), and responses from Device (or Devices). This is more common when there are a varying number of Devices, and/or more than one interface is needed. In practice, the Controller runs a daemon just like described above, except the protocols may be standard or simple enough so there is no need to write a library.
The PHP running on the Server must contain the request details (exactly what is desired) to the Controller. The Controller must pass them on to the Device. If the Controller provides a http URL for the PHPs on the server connect to, it can parse the query parameters, and translate them into a format the Device understands.
One particular issue in practice is to handle concurrent accesses. There is usually only a single connection from Controller to Device, but more than one PHP might connect to the Controller simultaneously. So there is some book-keeping involved.
In some cases the Device provides a continuous stream of data (or regular updates of data) to the Controller, and the Controller simply keeps tabs on it. When a PHP running on the Server queries something from the Controller, the Controller simply looks up the latest data (without contacting the Device at all, just receiving the data as normal), and responds with it. Here, it is common to include a timestamp, or better yet, the age of the data, in the response from Controller to Server.
You really should add some details to your question. (I suspect the downvote is due to lack of details.) You don't need to tell us the exact make and model of the Device, only whether it is a receiver (TV? radio? weather station?) or a sensor cluster or a door lock, and if you know any details on the communications protocols (which ones)? Thus far, we only know it uses IP. That does not help at all, just about everything uses IP nowadays. This is also why my answer is so vague; I'd like to be more precise, but you do not provide enough information for me to do so.

Service to ping web server

I have a dedicated webserver running PHP software which needs to automatically collect and update the IP's of a couple Windows and possibly Linux machines of mine which have dynamic IP's (roughly same idea as the no-ip.com client). The simplest thing to do I think is to run a service on each machine which simply pulls a unique URL from the webserver which can then lookup the client IP and match it with the URL etc.
$_SERVER["HTTP_CLIENT_IP"]
What's the best language/library/environment to build a client service which can make a URL request with easy access to the machine's external IP (to check for changes to the dynamic IP so as to not flood the webserver)? It need not be anything fancy, it doesn't even need to read anything from the server, it just has to make the URL request.
Besides web programming, I have some experience with Python and C and a few others. Any pointers or resources I can read up on the subject would be appreciated. Also, am I over-thinking this? Thanks
you can write a shell script with wget calls followed by a sleep in a loop.
wget performs http requests and it's available for windows and is already installed on all/some unix machines.
Mechanize is way overkill for making URL requests in Python. It's really really easy:
from urllib2 import urlopen
urlopen("my://url").read()
The first line may vary depending on your version of Python (for instance, it's urllib.request in Python 3.)
There are hundreds of "What's my IP" services out there; or you could even write your own! Plug one of those into the URL read to get the IP. You'll have to poll to work out when it changes, since you can't run code on the router.
If you already have some kind of method to do an URL request, do one each 10 minutes to this Page:
http://checkip.dyndns.org/Current%20IP%20Check.htm
wich will tell you "Current IP Address: XXX.XXX.XXX.XXX", and you only have to extract some string data.
(You only flood the whatsmyip webserver, and not your own anymore!)
Glad to Help
EGOrecords

Establish & Receive Calls via a GSM modem in PHP

I am having a CRM (Customer Relationship Management Software) built on php and running it on localhost (windows XP system). This contains the list of my clients. I want to be able to call these clients directly from my CRM and keep a log of the same. (Call time, call duration and record the calls). For incoming calls, I should be able to link it to my CRM, display the client details and log the data.
I have a voice enabled 3G GSM Modem (with USB connector) which can be used for this purpose. From my search, I understand I would need to send AT commands from PHP to interact with the modem. But I am not able to move ahead as I am completely new to this. I have never done any device interfacing before this.
Can you help me to understand how can I go about solving the above issue? Any leads, resources in this direction will be of great help.
I wouldn't try to do this with pure PHP since then you would have to have PHP interface with the hardware through the webserver, which can be a pain, if it is manageable at all. There are (edit) three options in my view:
1: AKA the hard way:
Write a PHP extension in C that does what you want, but this would mean a lot of programming for a relative small task.
2: The eas[y/ier] way:
Find a program (Maybe Skype?) that can do voice communication with your modem and has an API or a CLI so you can make PHP run:
voiceprogram.exe --call=555-000-5555 --saveTo=client1_20113103_1200.mp3
This allows the application to do what it's good as and only use PHP as the controller. The resulting MP3 (or Wav, OGG, etc) can be saved back to the CRM.
3: Other options
If you are able to program in a different language that does communicate easily with your modem you can write some custom code that can be triggered by PHP (sockets/SOAP/CLI) and handles the call. When finished it can 'POST' the call information back to your PHP script.
The first 2 solutions only work when the CRM runs on localhost, if you plan on using this in a shared network environment complexity will go up. The last option, if done correctly, can be used in a shared environment.

Will I run into load problems with this application stack?

I am designing a file download network.
The ultimate goal is to have an API that lets you directly upload a file to a storage server (no gateway or something). The file is then stored and referenced in a database.
When the file is requsted a server that currently holds the file is selected from the database and a http redirect is done (or an API gives the currently valid direct URL).
Background jobs take care of desired replication of the file for durability/scaling purposes.
Background jobs also move files around to ensure even workload on the servers regarding disk and bandwidth usage.
There is no Raid or something at any point. Every drive ist just hung into the server as JBOD. All the replication is at application level. If one server breaks down it is just marked as broken in the database and the background jobs take care of replication from healthy sources until the desired redundancy is reached again.
The system also needs accurate stats for monitoring / balancing and maby later billing.
So I thought about the following setup.
The environment is a classic Ubuntu, Apache2, PHP, MySql LAMP stack.
An url that hits the currently storage server is generated by the API (thats no problem far. Just a classic PHP website and MySQL Database)
Now it gets interesting...
The Storage server runs Apache2 and a PHP script catches the request. URL parameters (secure token hash) are validated. IP, Timestamp and filename are validated so the request is authorized. (No database connection required, just a PHP script that knows a secret token).
The PHP script sets the file hader to use apache2 mod_xsendfile
Apache delivers the file passed by mod_xsendfile and is configured to have the access log piped to another PHP script
Apache runs mod_logio and an access log is in Combined I/O log format but additionally estended with the %D variable (The time taken to serve the request, in microseconds.) to calculate the transfer speed spot bottlenecks int he network and stuff.
The piped access log then goes to a PHP script that parses the url (first folder is a "bucked" just as google storage or amazon s3 that is assigned one client. So the client is known) counts input/output traffic and increases database fields. For performance reasons i thought about having daily fields, and updating them like traffic = traffic+X and if no row has been updated create it.
I have to mention that the server will be low budget servers with massive strage.
The can have a close look at the intended setup in this thread on serverfault.
The key data is that the systems will have Gigabit throughput (maxed out 24/7) and the fiel requests will be rather large (so no images or loads of small files that produce high load by lots of log lines and requests). Maby on average 500MB or something!
The currently planned setup runs on a cheap consumer mainboard (asus), 2 GB DDR3 RAM and a AMD Athlon II X2 220, 2x 2.80GHz tray cpu.
Of course download managers and range requests will be an issue, but I think the average size of an access will be around at least 50 megs or so.
So my questions are:
Do I have any sever bottleneck in this flow? Can you spot any problems?
Am I right in assuming that mysql_affected_rows() can be directly read from the last request and does not do another request to the mysql server?
Do you think the system with the specs given above can handle this? If not, how could I improve? I think the first bottleneck would be the CPU wouldnt it?
What do you think about it? Do you have any suggestions for improvement? Maby something completely different? I thought about using Lighttpd and the mod_secdownload module. Unfortunately it cant check IP adress and I am not so flexible. It would have the advantage that the download validation would not need a php process to fire. But as it only runs short and doesnt read and output the data itself i think this is ok. Do you? I once did download using lighttpd on old throwaway pcs and the performance was awesome. I also thought about using nginx, but I have no experience with that. But
What do you think ab out the piped logging to a script that directly updates the database? Should I rather write requests to a job queue and update them in the database in a 2nd process that can handle delays? Or not do it at all but parse the log files at night? My thought that i would like to have it as real time as possible and dont have accumulated data somehwere else than in the central database. I also don't want to keep track on jobs running on all the servers. This could be a mess to maintain. There should be a simple unit test that generates a secured link, downlads it and checks whether everything worked and the logging has taken place.
Any further suggestions? I am happy for any input you may have!
I am also planning to open soure all of this. I just think there needs to be an open source alternative to the expensive storage services as amazon s3 that is oriented on file downloads.
I really searched a lot but didnt find anything like this out there that. Of course I would re use an existing solution. Preferrably open source. Do you know of anything like that?
MogileFS, http://code.google.com/p/mogilefs/ -- this is almost exactly thing, that you want.

Categories