Monday, February 23, 2015

Php exec, track your processes.

DIRECT QUOTE!!!

(This is for linux users only).


We know now how we can fork a process in linux with the & operator.
And by using command: nohup MY_COMMAND > /dev/null 2>&1 & echo $! we can return the pid of the process.

This small class is made so you can keep in track of your created processes ( meaning start/stop/status ).

You may use it to start a process or join an exisiting PID process.

<?php
    
// You may use status(), start(), and stop(). notice that start() method gets called automatically one time.
    
$process = new Process('ls -al');

    
// or if you got the pid, however here only the status() metod will work.
    
$process = new Process();
    
$process.setPid(my_pid);?>
<?php
    
// Then you can start/stop/ check status of the job.
    
$process.stop();
    
$process.start();
    if (
$process.status()){
        echo 
"The process is currently running";
    }else{
        echo 
"The process is not running.";
    }
?>
<?php/* An easy way to keep in track of external processes.
* Ever wanted to execute a process in php, but you still wanted to have somewhat controll of the process ? Well.. This is a way of doing it.
* @compability: Linux only. (Windows does not work).
* @author: Peec
*/
class Process{
    private 
$pid;
    private 
$command;

    public function 
__construct($cl=false){
        if (
$cl != false){
            
$this->command $cl;
            
$this->runCom();
        }
    }
    private function 
runCom(){
        
$command 'nohup '.$this->command.' > /dev/null 2>&1 & echo $!';
        
exec($command ,$op);
        
$this->pid = (int)$op[0];
    }

    public function 
setPid($pid){
        
$this->pid $pid;
    }

    public function 
getPid(){
        return 
$this->pid;
    }

    public function 
status(){
        
$command 'ps -p '.$this->pid;
        
exec($command,$op);
        if (!isset(
$op[1]))return false;
        else return 
true;
    }

    public function 
start(){
        if (
$this->command != '')$this->runCom();
        else return 
true;
    }

    public function 
stop(){
        
$command 'kill '.$this->pid;
        
exec($command);
        if (
$this->status() == false)return true;
        else return 
false;
    }
}
?>

php exec command (or similar) to not wait for result

I have a command I want to run, but I do not want PHP to sit and wait for the result.

It's always good to check the documentation:
You can run the command in the background by adding a & at the end of it as:
exec('run_baby_run &');
But doing this alone will hang your script because:
If a program is started with exec function, in order for it to continue running in the background, the output of the program must be redirected to a file or another output stream. Failing to do so will cause PHP to hang until the execution of the program ends.
So you can redirect the stdout of the command to a file, if you want to see it later or to /dev/nullif you want to discard it as:
exec('run_baby_run > /dev/null &');

"exec nohup setsid your_command"
the nohup allows your_command to continue even though the process that launched may terminate first. If it does, the the SIGNUP signal will be sent to your_command causing it to terminate (unless it catches that signal and ignores it).

by using command: nohup MY_COMMAND > /dev/null 2>&1 & echo $! we can return the pid of the process.

FINAL ANSWER:

This uses wget to notify a URL of something without waiting.

$command = 'wget -qO- http://test.com/data=data';
exec('nohup '.$command.' >> /dev/null 2>&1 echo $!',$pid);

Loading / Processing in PHP cli

So that it would display from "Loading 1%" to "Loading 100%". But this will result in all appearing one at a time without disappearing after the new line appears. So I want to know how to make the new line appear and the old disappear and this starts after the page loads, so the user will be able to watch a loader actually loading from 1% to 100%.
In order to give the impression that the line is being overwritten, you can insert a CR (Carriage Return, "\r") in front of your output. I wrote it down on an example:
<?php
$x=1;
while($x<=100) {
   echo "\rLoading: $x %";
   usleep(10000);
   $x++;
}
?>
Running this on a terminal I get a cool loading status: $ php code.php
Hope that's what you've been looking for.

Thursday, February 19, 2015

Reset Auto Increment IDs.

Reset Auto Increment IDs.
update all auto increment columns in a database to the smallest possible value based on current values in the databases. We needed to do this after cleaning out a database.
Use a Prepared Statement within a Stored Procedure:
drop PROCEDURE if exists reset_autoincrement;
DELIMITER //
CREATE PROCEDURE reset_autoincrement (IN schemaName varchar(255))
 BEGIN
    DECLARE done INT DEFAULT FALSE;
    DECLARE o_name VARCHAR(255);
    DECLARE o_table VARCHAR(255);
    DECLARE cur1 CURSOR FOR SELECT COLUMN_NAME, TABLE_NAME FROM information_schema.`COLUMNS` WHERE extra LIKE '%auto_increment%' and table_schema=schemaName;
    DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
    OPEN cur1;
    read_loop: LOOP
     FETCH cur1 INTO o_name, o_table;

     IF done THEN
       LEAVE read_loop;
     END IF;

  set @qry1 = concat('SELECT MAX(`',o_name,'`) + 1 as autoincrement FROM `',o_table,'` INTO @ai'); 
  PREPARE stmt1 FROM @qry1;
  EXECUTE stmt1;

  IF @ai IS NOT NULL THEN
      SELECT  o_name, o_table;
   select @qry1;
   select @ai;
   set @qry2 = concat('ALTER TABLE `',o_table,'` AUTO_INCREMENT = ', @ai);
   select @qry2;
   PREPARE stmt2 FROM @qry2;
   EXECUTE stmt2;
  END IF;

    END LOOP;

    CLOSE cur1;
 END //
DELIMITER ;


call reset_autoincrement('my_schema_name');

mysql cli password - mysql_config_editor

mysql_config_editor set --login-path=storedPasswordKey --host=localhost --user=root --password


How do I execute a command line with a secure password??
use the config editor!!!

As of mysql 5.6.6 you can store the password in a config file and then execute cli commands like this....

mysql --login-path=storedPasswordKey ....

--login-path replaces variables... host, user AND password.
excellent right!

Monday, February 16, 2015

MySQL Compare replicated database table

I needed to compare 2 tables in separate instances (siblings) of MySQL replication. So this script dumps the unique id from the first server into a temp table on the second server. This is assuming that the second server is having missing record errors. There are MANY comments in the code for more details. This is meant to be made executable and run on command line.

Source Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#!/usr/bin/php
<?php 

error_reporting(E_ALL);
ini_set("display_errors", 1);

$user = 'localuser';
$password = 'password';

$schema = 'myDatabase';
$intkey = 'theID';
$table = 'myTable';

$serverClean = 'mysql2a.local';
$dsnClean = 'mysql:dbname='.$schema.';host='.$serverClean;
$serverMissing = 'mysql2b.local';
$dsnMissing = 'mysql:dbname='.$schema.';host=mysql2a.usi.ben';

echo "check database table sync \n\n";
echo "clean: $serverClean \n";
echo "dirty: $serverMissing \n";
echo "table: $schema.$table \n\n"
// create database connection
try {
    $dbMissing = new PDO($dsnMissing, $user, $password);
    $dbMissing->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage();
}
// temp table on serverMissing
try{
    $dbMissing->exec("
        CREATE TABLE `unique_ids_tmp` (
          `id` bigint(20) NOT NULL,
          PRIMARY KEY (`id`)
        ) ENGINE=MEMORY DEFAULT CHARSET=latin1;
    ");
} catch(Exception $e){
}
// make sure table is clean
$dbMissing->exec("TRUNCATE TABLE `unique_ids_tmp`");
// select IDs from serverClean, this is much faster than selecting with pdo.
exec("mysql -u $user --password=$password -h $serverClean --database=$schema --execute='SELECT `$intkey` FROM `$table`' > /tmp/source.list");
// insert IDs into serverMissing
$dbMissing->exec("LOAD DATA INFILE '/tmp/source.list' INTO TABLE $schema.unique_ids_tmp IGNORE 1 LINES");
// where null, missing ids on serverMissing.
$sql = 'SELECT a.id FROM unique_ids_tmp a LEFT JOIN `'.$table.'` b ON a.id=b.`'.$intkey.'` where b.`'.$intkey.'` IS NULL';
// count number of missing
$cnt=0;
// each missing id
foreach ($dbMissing->query($sql, PDO::FETCH_ASSOC) as $row) {
    // echo id
    echo $row['id'].",";
    // count it.
    $cnt++;
}
// show total count of missing ids
echo "\n\n$cnt total\n\n";

Sunday, February 1, 2015

Billiard vs Carom

I had to look up billiard and carom. A friend used "billiard" in a post and that is not commonly use among my pool peers. He mentioned a shot that was a carom, so I thought he was mistake. Actually I was, but I had to dig to find the answer.
PER GOOGLE:
billiard <noun>: a stroke in which the cue ball strikes two balls successively.
carom <noun>: another term for billiard
carom <verb>: make a carom; strike and rebound.
Not very definitive definitions.
This seems like the resource I was looking for...
http://www.billiardworld.com/glossary.html
BILLIARD. (Carom games) A count or score; a successful shot.
CAROM. (General) To bounce off or glance off an object ball or cushion; a shot in which the cue ball bounces off one ball into another is termed a carom.
CAROM, SCORING. (General) Contact by the cue ball with object balls, the bottle or cushions in such a way that a legal score is made, according to specific game rules.
So carom (scoring) is also a billiard, but carom (general) is not.
Easy Pool Tutor - In pocket billiards a carom shot is defined as a shot in which the cue ball hits an object ball which then hits another object ball before going into a pocket.
EASYPOOLTUTOR.COM|BY EASY POOL TUTOR