Friday, December 1, 2017

VirtualBox Cannot ping VM from host - Destination host unreachable.


Virtualbox  on windows host  after create a new virtual machine and choose the network to be bridged , I can reach the world and ping the host machine and the router , but when I try to ping the virtual machine from the hot it respond with "Destination host unreachable".
The solution is simple I was using static IP for the virtual machine , changing the ip on the virtual machine  to be static will solve this issue.

Sunday, November 12, 2017

array_key_exists(): The first argument should be either a string or an integer


array_key_exists(): The first argument should be either a string or an integer In Php when you get this error , that means you are dealing with an Array , and your code trying to get some keys out of this Array, but instead of passing a single parameter (string or an integer) to the function that do the job,you are passing something else.
Example :

$arr = [
'color' => 'Red',
'price' => '50'
]

Now, when you try to check if the color is red you are going to use the code :

if($arr['color'] === 'Red') echo "Red";

and that's ok and no error will be thrown, but the following code:

if($arr['color','price'] === 'Red') echo "Red";

will throw an Error Exception.as the error given above.

Thursday, October 26, 2017

Change all posts permalinks in wordpress when move site from server to server


great trick to change all posts permalinks in wordpress when move site from server to server
UPDATE wp_options SET option_value = replace(option_value, 'http://www.oldurl', 'http://www.newurl') WHERE option_name = 'home' OR option_name = 'siteurl';

UPDATE wp_posts SET guid = replace(guid, 'http://www.oldurl','http://www.newurl');

UPDATE wp_posts SET post_content = replace(post_content, 'http://www.oldurl', 'http://www.newurl');

UPDATE wp_postmeta SET meta_value = replace(meta_value,'http://www.oldurl','http://www.newurl');

Reference

Saturday, October 14, 2017

jQgrid not inserting php returned json data into grid

After return json data from php file , the jQgrid not inserting the json data into the grid , jqgrid built the grid and assigned columns header names , but not the data .
debugging the http response  using firefox developer tools and found the json data syntax is right and no errors there. So what is the problem.

the problem here is that jQgrid requires extra elements in the response other than the real data , which are as follows:

  "page": 2,//current page
    "total": 2,//number of pages
    "records": 11,//# of records in total

So, you have to prepare the json data before sending back to the client to be in the following form:
  
You json should look something like
{
    "page": 2,//current page
    "total": 2,//number of pages
    "records": 11,//# of records in total
    "rows": [//array of data
        {
            "id": "101",//id for this row of data
                "cell": [
                "101",
                "Sundale",
                "OTTP",
                "652",
                "6",
                "65",
                "656665",
                "986346654",
                "823343454",
                "554332"
            ]
        }
    ]
}

Friday, October 13, 2017

Laravel - eloquent - Logging All queries into logfile

Sometimes you need to know the SQL interpretation of your eloquent query to check performance or even check the SQL query syntax is valid , you may try a laravel debugging package like Laravel-Debugbar, But whilst this package is great , it still cannot be good tool when it comes to SPA (single page application) which run tens of requests  , but this package only returns information about each request , which means the next request will write over the previous request debugging information.

So , in this case we need to log all request information , specially the SQL queries to a log file using the Example mentioned in Laravel documentation.

<?php

namespace App\Providers;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        DB::listen(function ($query) {
            // $query->sql
            // $query->bindings
            // $query->time
        });
    }

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

Thursday, October 5, 2017

Laravel : Argument 1 passed to Illuminate\Auth\Guard::login() must implement interface Illuminate\Contracts\Auth\Authenticatable, null given

This Error Happened when I tried to register a new user  using RegistersUsers  trait in :

App\Auth\RegisterController

Method : create

this method must return an instance of the created (registered) user from the mentioned method , which is by default return this instance as follow :

return User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => bcrypt($data['password']),
        ]);

look to the word return in the beginning .
if you manipulated the original code in this method and forgot to return an instance of the created user then Laravel will through this error..

Wednesday, October 4, 2017

SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table `` add constraint `_user_id_foreign` foreign key (`user_id`) references `users` (`id`) on delete cascade)

SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table `profiles` add constraint `profiles_user_id_foreign` foreign
 key (`user_id`) references `users` (`id`) on delete cascade).


Ok , this Error on laravel migration for a new table, when trying to add a foreigen key to profile table references User id  in users table,  what will solve this issue is to change the user_id type to match the data type of (id) in users table :

$table->integer('user_id')
to
$table->integer('user_id')->unsigned()->nullable();

Also, this error can happen, if the referenced table is not created yet. So, if the users table in this example is not exist in the database. then the same error (1215) will be triggered .

Sunday, October 1, 2017

htmlspecialchars() expects parameter 1 to be string, array given Laravel 5.

This Error Happened in View where php trying to echo a value using the function htmlspecialchars(), and this function cannot accept an Array as its first Parameter.

Debug : if you are using Whoops for debugging your application you will see in the left panel a link to the view templates directory .

…\storage\framework\views\eec8a32e98fad0167a61a9f879d076bc29cad5a6.php 43
 
the number in red may change in your case , So open this file in any editor and find the line number 43 , you will find the echo function containing something  function as its parameter, like this :

echo e(app->Somthing()));

the e function is a laravel helper function , which apply htmlspecialchars() function to the expected string between brackets.


Now, the function inside the brackets is causing the error , Here it is the app->Something which is bringing an array as its result while htmlspecialchars () expecting a string , find this function in your view file and change it to give you a string not an array.

Wednesday, September 13, 2017

How to install and manage Letsencrypt certificate certbot on Ubuntu - quick guide

This is a quick reference guide to Add the free ssl certificate letsencrypt to your site , if you don't like to go deep into details .
First create letsEncrypt certificate following these commands :
  sudo a2ensite default-ssl

  sudo add-apt-repository ppa:certbot/certbot 

  sudo apt-get update 

  sudo apt-get install python-certbot-apache 

  sudo certbot --apache -d example.com 



To check certificate validation :
  https://www.ssllabs.com/ssltest/analyze.html?d=example.com&latest 

To check certificate dates :
  echo | openssl s_client -connect yourdomain.tld:443 -servername yourdomain.tld 2>/dev/null | openssl x509 -noout -dates 

OR

 openssl x509 -noout -dates -in /etc/letsencrypt/live/yourdomain.tld/cert.pem 


add to cron job

  crontab -e 

add this line:
  0 0 1,15 * * /usr/bin/certbot renew --quiet 



How to renew the certificate :

 certbot renew 

Monday, July 31, 2017

Cannot Close 137 udp port - ubuntu

if you face some complains about port 137 udp netbios-service is open on your server and firewall cannot close these ports then check if you have samba or cifs installed on your system, then remove this service completely unless you need it for an important application.
Uninstall cifs-utils from Ubuntu 16.04
To remove cifs-utils package :
 
sudo apt-get remove cifs-utils

Uninstall cifs-utils and it's dependent packages
 
sudo apt-get remove --auto-remove cifs-utils

delete configuration and data files of cifs-utils :
 
sudo apt-get purge cifs-utils

delete configuration and data files of cifs-utils and it's dependencies :
 
sudo apt-get purge --auto-remove cifs-utils

Sunday, July 30, 2017

Raid1 Cannot Remove Drive From Raid Array


First, check the mdadm status
cat /proc/mdstatus

then, run
lsblsk
to see the available drives ,and after choosing the drives to be part of RAID,let's say sda,sdb
sudo mdadm --create --verbose /dev/md0 --level=1 --raid-devices=2 /dev/sda /dev/sdb
if one hard disk fail and you want to replace it, then you need to flag it as fail part of raid the remove it from the raid array:
    mdadm --manage /dev/md1 --fail /dev/sdb2

then you can remove it from the raid array
    mdadm --manage /dev/md1 --remove /dev/sdb2
if you want to remove Raid1 : Check the Raid status -- these may will give you clear picture :
sudo mdadm --detail /dev/md0
and 
lsblk

Then stop and remove the Raid
mdadm --stop /dev/md0
mdadm --remove /dev/md0

tell the drive sda to forget about raid
sudo mdadm --zero-superblock /dev/sda/

if the system complain for being busy or such then
sudo dd if=/dev/zero of=/dev/sda
finally unmount the raid in the fstab file and comment it in the /etc/mdadm/mdadm.conf

Tuesday, July 18, 2017

10 most important seo rules

  • Select the right keywords really searchable by audience.
  • Select the domain name that reflect the keywords.
  • Use keywords in file names and folders if you have .
  •  Use keywords in your page titles "H1,H2,......" and the main title
  • Use keyword text in the internal links and their titles and alt attributes.
  • the Content is king , so don't  spaghettize  keywords , use with care
  • put keywords in the  Description meta tag
  • ssl is preferred for the links
  • Use keyword text in your out and in links
  •  Don't forget the site map

Monday, July 10, 2017

Warning: session_start(): Setting option 'session.hash_function' failed in on line

When I tried to add options parameters to session_start() php function, I got this warning
"Warning: session_start(): Setting option 'session.hash_function' failed in  on line "

I was using the full name of the parameter like this

session_hash_function
 
But the session_start function requires these parameters without the prefix "session", So the new parameter will be "hash_function"
session_start(["hash_function" =>  5 ]);

Notice: in PHP7.1: Session IDs will no longer be hashed upon generation. With this change brings about the removal of the following four ini settings:
    session.entropy_file
    session.entropy_length
    session.hash_function
    session.hash_bits_per_character

Wednesday, June 28, 2017

Fast Method to repair MySQL Master-Master Replication

Fast Method to repair Master-Master Replication

1. On th Good Server
a. mysqldump --add-drop-table --master-data  --quick -u root -p databaseName > databaseName.sql
b. bzip2 databaseName.sql
c.  scp databaseName.sql.bz2 -P port username@192.168.100.5:


2. On Bad Server
bunzip2 databaseName.sql.bz2

mysql> stop slave;
mysql -u root -p databaseName < databaseName.sql
mysql> start slave;
mysql> show slave status\G

You should see Slave_IO_Running: Yes and Slave_SQL_Running: Yes.

Now --
mysql> flush tables with read lock;
mysql> show master status;

Make a note of the File and Position rows.

mysql-bin.000044 | 11726351


3. On the Good Server
mysql> stop slave;
mysql> change master to master_log_file='mysql-bin.000044',
master_log_pos=11726351;
mysql> start slave;
mysql> show slave status\G

You should see Slave_IO_Running: Yes and Slave_SQL_Running: Yes.

4. on the Bad Server
mysql> unlock tables;

Monday, June 12, 2017

Setup Proxmox Cluster High Availability

from the main node issue the command

pvecm create clusterone 


from the other node :

pvecm add MAIN_NODE_IP 


we got cluster running now .

High Availability :

click on the 'Datacenter' --> HA --> Add : choose the virtual machine you need to add to HA.

to test HA is running  or not , go to the node where the virtual machine is install and down the network interface :

ifdown eth0 


the virtual machine should be still running while the main node is off.

Setting up Gluster
Reference 1
Reference 2
Refernce 3
Notice : Directory Need to be Manipulated to serve this job check Reference 2
 Add the GPG key to apt:

    wget -O - http://download.gluster.org/pub/gluster/glusterfs/3.11/rsa.pub | apt-key add -

Add the source:

    echo deb http://download.gluster.org/pub/gluster/glusterfs/3.11/LATEST/Debian/jessie/apt jessie main > /etc/apt/sources.list.d/gluster.list

or:
    echo deb http://download.gluster.org/pub/gluster/glusterfs/3.11/LATEST/Debian/stretch/apt stretch main > /etc/apt/sources.list.d/gluster.list

Update package list:

    apt-get update

Install:

    apt-get install  glusterfs-server glusterfs-client


from the master node
  gluster peer probe node1.proxmox
 

create the share named testvol with two replicas (please note that the number of replicas is equal to the number of servers :
 gluster volume create testvol replica 2 transport tcp master.proxmox:/data/testvol node1.proxmox:/data/testvol force

Gluster may complainn of spli brain issue , but I think proxmox can avoid that using fencing or Watchdog. Start the Volume
gluster volume start testvol

you can check the connection is established or not using :
 netstat -tap | grep glusterfsd 
if not check the required ports are open .
Now , from Proxmox Datacenter node , Choose --> Storage --> Add --> GlusterFS enter the name you like for this gluster storage, the ip of the two servers and the volume name "testvol" in our case

Don't forget to enables watchdog

just uncomment the line

# select watchdog module (default is softdog)
WATCHDOG_MODULE=ipmi_watchdog

Now It is time to do security job to secure the system

Commands:
Start Stop the Gluster service

 service glusterfs-server start | stop | status 

Information about gluster Volume
gluster volume info

Check status of high availability
systemctl status pve-ha-crm.service 

Check the Cluster Status
 pvecm status 

High Availability Command:
USAGE: ha-manager  [ARGS] [OPTIONS]
       ha-manager groupadd  -nodes  [OPTIONS]
       ha-manager groupconfig
       ha-manager groupremove 
       ha-manager groupset  [OPTIONS]

       ha-manager add  [OPTIONS]
       ha-manager config  [OPTIONS]
       ha-manager migrate  
       ha-manager relocate  
       ha-manager remove 
       ha-manager set  [OPTIONS]

       ha-manager status  [OPTIONS]

       ha-manager help [] [OPTIONS]

Proxmox Network Issues

Promox - Promox Cluster - High Availability -- what the difference

Promox alone is a Virtualization Software that enables you to run many Virtual Machines on a single Server Machine .
Proxmox-Cluster : Where you can manage many physical servers from  one point , each Server is running Proxmox and many Virtual machines.

Proxmox-Cluster-High-Availability: the Promox Cluster provide if a virtual machine (VM) is configured as HA and the physical host fails, the VM is automatically restarted on one of the remaining Proxmox VE Cluster nodes

proxmox cluster TASK ERROR: No accelerator found!

when trying to start VM I got en erroe with this message :

TASK ERROR: No accelerator found!

Solved By Disable "KVM hardware virtualizaion"

from options click the option titled  KVM hardware virtualizaion and disable it

Cannot migrate VM in proxmox cluster

ERROR: Failed to sync data - can't do online migration - VM uses local disks

iso removed from vm-100.conf

Folder is not shared, So I tried to cluster the volume group

vgchange -cy
Trying Again to migrate the Virtual machine gives this error:

Skipping clustered volume group pve
Cannot process volume group pve

rebooting will cause the system not running and the grub will hang on :initramfs

run the command


  WARNING: Locking disabled. Be careful! This could corrupt your metadata.
  VG   #PV #LV #SN Attr   VSize  VFree
  pve    1   4   0 wz--nc 49.75g 6.07g

nc means clustered  So remove the clustering from the volume group:

vgchange -cn vgname --config 'global {locking_type = 0}'
that will bring back the pve lvm group to non clustered If the volume group is set to clustered (vgchange -cy vgname) then the volume group can only be activated if your Red Hat High Availability cluster is quorate, and Clustered LVM Daemon (CLVMD) is active. [Reference]

At last;
when you migrate a vm ; first shutdown the vm then press migrate option  and enable online checkbox .

Saturday, June 10, 2017

Proxmox Cannot add a new node cluster not ready - no quorum?

For some reason when I tried to add a new node I got this error

cluster not ready - no quorum?

I tried a lot of the google suggested solutions but nothing  succeeded , at last I tried this trick
 
pvecm e 1

and that did the trick and solved the issue .

"Failed to start Corosync Cluster Engine"  on the second node for only two nodes setup proxmox :
the problem was in /etc/hosts --> wrong IP.

Thursday, June 8, 2017

sudo permission on remote server using sftp

when connecting to a remote server using sftp command line , you may face a permission denied when you want to run commands on some folders . but you want to do that command using sudo permission ,So you just need to enter this command :

sftp -s "sudo /usr/lib/openssh/sftp-server" 188.40.xxx.xxx
 

Provided that the username is already has ALL permissions in the sudoers file .Ref

Monday, June 5, 2017

HG658 V2 Gateway destination host unreachable between LAN computers

On HG658 V2 Gateway when I tried to ping one of the PC's that are connected to this LAN the response always  the destination host unreachable , So after many hours of digging down to figure out the solution , it return that there is a checked  option on the Router  that should not be checked . this option called "Enable AP isolation" , AP (access point) isolation  or  'Client Isolation' or 'Guest Mode', The name depend on your router type .You can  find this option some where in the Wireless  LAN Properties, So disabling this option well allow computers to reach each other .

Sunday, May 14, 2017

sftp Couldn't remove directory: Failure


using SFTP to connect to other servers , you ma get this error when trying to delete a folder "sftp Couldn't remove directory: Failure" , this because the folder is not empty , so try the command ls -a to show the hidden files , then remove them and try again .

Sometimes when you try to remove a full 100% folder (on Hetzner) , you cannot do that unless you use put command to replace the folder you want to remove by a null size folder with same name.

Note: that put command on ssh uses -r argument for the folders with identical names source and destination. which means it expects a folder with a same name from the command sftp -r source