Tuesday, 29 December 2020

Gitlab Error: couldn't deduce an advertise address: no private IP found, explicit advertise addr not provided

Gitlab log view:

gitlab-ctl tail

Something error:

cluster.go:154 component=cluster err="couldn't deduce an advertise address: no private IP found, explicit advertise addr not provided"

How to fix !

edit file gitlab.rb

vi /etc/gitlab/gitlab.rb

Add the following code

alertmanager['flags'] = {

  'cluster.advertise-address' => "127.0.0.1:9093",

}

Then

gitlab-ctl reconfigure

gitlab-ctl restart

Done ! now recheck gitlab log

gitlab-ctl tail alertmanager

Check alertmanager service

netstat -tulpn | grep LISTEN

output 

tcp        0      0 127.0.0.1:9093              0.0.0.0:*                   LISTEN      30633/alertmanager


Monday, 28 December 2020

Centos 6 - Yum Error: Cannot find a valid baseurl for repo base

When using the commands "yum install/update" on Centos 6 you will get an error:

Loaded plugins: fastestmirror, replace
Setting up Update Process
Determining fastest mirrors
YumRepo Error: All mirror URLs are not using ftp, http[s] or file.
 Eg. Invalid release/repo/arch combination/
removing mirrorlist with no valid mirrors: /var/cache/yum/x86_64/6/base/mirrorlist.txt
Error: Cannot find a valid baseurl for repo: base (base/updates/contrib)

Reason: Centos 6 is out of date and is no longer officially supported.

Solution: Manual change CentOS-Base.repo

Step 1:

Open the following files one by one:

/var/cache/yum/x86_64/6/base/mirrorlist.txt
/var/cache/yum/x86_64/6/extras/mirrorlist.txt
/var/cache/yum/x86_64/6/updates/mirrorlist.txt

Add the following line at the end of the files:

https://vault.centos.org/6.10/

Step 2:

Open file "CentOS-Base.repo" and modify all blocks according to the form below 

vi /etc/yum.repos.d/Centos-Base.repo

 [base]
name=CentOS-$releasever - Base
#mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=os&infra=$infra
baseurl=http://vault.centos.org/6.10/centosplus/$basearch/
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-6
gpgcheck=1

 

#released updates
[updates]
name=CentOS-$releasever - Base
#mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=os&infra=$infra
baseurl=http://vault.centos.org/6.10/centosplus/$basearch/
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-6
gpgcheck=1

 

#additional packages that may be useful
[extras]
name=CentOS-$releasever - Base
#mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=os&infra=$infra
baseurl=http://vault.centos.org/6.10/centosplus/$basearch/
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-6
gpgcheck=1

 

#contrib - packages by Centos Users
[contrib]
name=CentOS-$releasever - Base
#mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=os&infra=$infra
baseurl=http://vault.centos.org/6.10/centosplus/$basearch/
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-6
gpgcheck=1

Step 3: Done ! Solved !

Now on you can continue to use yum normally

Tuesday, 6 October 2020

Laravel: Force to use HTTPS for all routes and url (Support Cloudflare Flexible SSL)

Laravel - In some special cases but especially when you are using Cloudflare Flexible SSL. We need a solution so that all URL on our website (created by url, route function) must be https even though our server currently doesn't support ssl.

Solution:

Edit App\Providers\AppServiceProvider.php in the boot() method

public function boot()
{
       
// custom for cloudflase flexible ssl
        if($this->checkHTTPSStatus()){
            URL::forceScheme('https');
        }
/*...some other code...*/
}
private function checkHTTPSStatus()
{
/*Select code in an option below*/
}

Option 1: Switch to https according to the configuration in the env file

private function checkHTTPSStatus()
{
return env('APP_HTTPS',false) === true;
}

In .env file you must to declare APP_HTTPS parameter

APP_HTTPS=true

Option 2: Automatically switch to https if the user comes from Cloudflare Flexible SSL

private function checkHTTPSStatus()
{
return (isset($_SERVER['HTTP_X_FORWARDED_PROTO'])&&$_SERVER['HTTP_X_FORWARDED_PROTO']==='https');
}

Option 3: Full SSL

private function checkHTTPSStatus()
{
return !empty($_SERVER['HTTPS']);
}

Solved !

Monday, 10 August 2020

Laravel Error "$errors is undefined"

Case: In a Laravel project, when you try to get the form validation error object but it fail. 
    $errors is undefined

Reason: Laravel passes the errors variable from the controller to the view file via session. The $errors variable is bound to the view by the Illuminate\View\Middleware\ShareErrorsFromSession middleware, which is provided by the web middleware group. So when you do not declare the web middleware group (containing middleware \Illuminate\View\Middleware\ShareErrorsFromSession) for your route, you will get the error as seen.

Solution: Check your route to make sure you added ShareErrorsFromSession Middleware



Solved !


Sunday, 26 July 2020

Laravel Fix Error : Function name must be a string by Illuminate\Pipeline\Pipeline.php


Laravel

Issue: Laravel encountered error "Function name should be a string" or "Function name must be a string" in Api or somewhere. Error reported from file "Illuminate\Pipeline\Pipeline.php"
$carry = method_exists($pipe, $this->method)
                                    ? $pipe->{$this->method}(...$parameters)
                                    : $pipe(...$parameters);
Reason: You have used some middleware by name that has not been previously declared.
Debug: Check all middleware used, make sure it is already declared in the file Kernel.php. The most common scenario is that you have not declared 'auth' middleware yet.

protected $routeMiddleware = [
        'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
        ...
}
Done ! 

Wednesday, 8 July 2020

Fix PHP Mongodb Error: connection refused calling ismaster on 'localhost:27017'


Step by step, Debug and fix PHP Mongodb error "No suitable servers found". This tutorial works with pure php and also popular php frameworks today such as: Laravel, Yii, CodeIgniter ...

Raw Error:
No suitable servers found (`serverSelectionTryOnce` set): 
[connection refused calling ismaster on 'localhost:27017']
[connection refused calling ismaster on '127.0.0.1:27017']
Debug Step by Step !

1. Check if mongodb is working or not:
netstat -tulpn | grep LISTEN
Please check if the mongodb process is working or not, the correct port or not. If the mongodb server is not working properly please resolve that issue.

2. Check that the php-mongodb extension is installed correctly (Unrelated, but I think it is useful)
Create a php file with content:
<?php
phpinfo();
?>
If no Mongodb found in the results page means you are missing this ext. Please install it according to the following tutorial: https://www.codesiri.com/2020/07/install-php-mongodb-extension-for-php7.html

3. Can you connect to the mongodb server via the Command line (CLI)?
mongo
4. Check SELinux Permission (Very important)
If you've debugged through steps 1 - 3 and haven't found the problem yet, SELinux is probably the problem that caused your error.
For added security, SELinux is enabled by default on newer server versions. By default SELinux will not allow apache, PHP is automatically opened to the new socket to connect out (or local). Meanwhile, php-mongodb ext needs to initialize the socket to connect to the mongodb server. So you will encounter the error as seen.
To fix this issue grant SELinux permission to apache to freely open the socket.
setsebool -P httpd_can_network_connect 1
Note: Some other php libraries that use sockets may have similar problems with SELinux, for example: php-redis, curl ...

Done !

Tuesday, 7 July 2020

Fix Laravel Error - Please provide a valid cache path


Error when install new Laravel project in server.

InvalidArgumentException
Please provide a valid cache path.

This error can be caused by

…/vendor/laravel/framework/src/Illuminate/View/Compilers/Compiler.php line 36

* Reason: 
To increase performance, the default laravel will need to be configured in a directory to store the cache files of views, sessions ...., so you need a cache directory in your project. Normally this directory will be created automatically, but in some situations such as the user who does not have much experience in the installation of the project git, this cache directory may be lost or incorrect.

* Solve:
Declare the cache directory for Laravel and make sure php needs write permissions in that directory

- create 4 folder for cache:

.../bootstrap/cache
.../storage/framework
.../storage/framework/views
.../storage/framework/cache
.../storage/framework/sessions
(... is the path to your project folder)

- grant write permissions to these directories (777 is not a good choice for security)

chmod 777 .../bootstrap/cache -R
chmod 777 .../storage/framework -R

- To keep these directories empty in the git project, you can add a .gitignore file to those directories with the content:

*
!.gitignore

- If your server is using selinux remember to give write permission to php

sudo chcon -t httpd_sys_rw_content_t .../bootstrap/cache -R
sudo chcon -t httpd_sys_rw_content_t .../storage/framework -R
Done !

Saturday, 4 July 2020

[Linux] Install PHP mongodb extension for PHP 7.2 and higher

This article will guide you to install php mongodb extension for PHP7 on linux operating system platform. The operating system we use is Centos, but it is also true for other linux distributions like Ubuntu, Redhat, Fedora ....

When upgrading to PHP7 we often encounter problems when we cannot install the php-mongo extension. You may encounter the following error message:

Package: php-pecl-mongo-1.6.14-1.el7.remi.5.4.x86_64 (remi)
Requires: php(zend-abi) = 20100525-64
* Reason: 
We have 2 mongo extensions for PHP: php-mongo and php-mongodb. Php-mongo only supports php 5.6, but php-mongodb supports the latest version 7.4. That's why you have an error when trying to install php-mongo for PHP7.
php-mongo is older and has been discontinued, but it is currently available as a library in remi repos. And php-mongodb is Pecl's latest library but it is not available and you have to install it yourself via php-pear.

* Solving problems: install php-mongodb extension for PHP7 

Step 1: Install apache(httpd) and php 7
Step 2: Install php-pear
install gcc php-pear php-devel
Step 3: Install mongodb extension 
pecl install mongodb
Step 4: Enable php-mongodb extension 
open php.ini file, then add the following line
;;;;;;;;;;;;;;;;;;;;;;
; Dynamic Extensions ;
;;;;;;;;;;;;;;;;;;;;;;
extension=mongodb

Step 5: Verify PHP Mongodb extension is enabled
php -m
Done !

* Note: The syntax used in previous PHP versions ('extension=<ext>.so' and 'extension='php_<ext>.dll') is supported for legacy reasons and may be deprecated in a future PHP major version. So, when it is possible, please move to the new ('extension=<ext>) syntax.

* Refer: https://blog.remirepo.net/pages/PECL-extensions-RPM-status



Saturday, 27 June 2020

MySQL: Fix Error 2013 - Lost connection to MySQL server during query


Case: You have successfully connected to a MySQL/MariaDB database. But when trying to import a large SQL file, an error occurred.
Error Code: 2013. Lost connection to MySQL server during query
Reason:
- Timeout due to slow connection or too much data (Not the server's fault)
- Memory allocated is not enough: the data fields are too large ....

Quick fix:
Increase memory for Mysql package.
Find config file
Eg:
Xampp Windows: C:\xampp\mysql\bin\my.ini
Linux: /etc/my.cnf
Edit file my.ini (my.cnf), find [mysqld] block, to change max_allowed_packet to a larger value (16, 32, or 128 M)
Eg:
[mysqld]
.....
max_allowed_packet=128M
Then restart MySQL
*Note: 
- If max_allowed_packet is not found, you can add it to your [mysqld] block yourself.
- Increasing memory capacity may affect the stability of MySQL server. So you can freely change it on your local computer, but if you are on the product server, please consider carefully. Another solution to importing large mysql files on the server is to use the command line.

Done ! Solved !

Monday, 22 June 2020

[PHP] Laravel Exception: Malformed UTF-8 characters, possibly incorrectly encoded

This error can be caused from many laravel modules such as Datatables, Json Output, Monolog ... So this is a very difficult error to analyze and fix. In this article we try to find some way to fix that bug in laravel (in the common cases).
Why did you get this error? and how to fix it?

* Case 1: In case of failure due to wrong configuration of database connection
The most common is when you connect to a second database. Developers often have a configuration that lacks the "charset" and "collation" parameters, causing the error as you see it:
Exception Message:↵↵Malformed UTF-8 characters, possibly incorrectly encoded
To fix it please configure the connection parameters are complete.
Eg:

'mysql' => array(
            'driver'    => 'mysql',
            'host'      => 'localhost',
            'database'  => 'database_name_1',
            'username'  => 'user_1',
            'password'  => 'password_1'
            'charset'   => 'utf8',
            'collation' => 'utf8_unicode_ci',

            'prefix'    => '',
    ....
 ),
/*mysql2 if you use two database*/
'mysql2' => array(
            'driver'    => 'mysql',
            'host'      => 'hostForDB2',
            'database'  => 'database_name_2',
            'username'  => 'user_2',
            'password'  => 'password_2'
            'charset'   => 'utf8',
            'collation' => 'utf8_unicode_ci',

            'prefix'    => '',
    ...
),

* Case 2: Regex Error - Caused by some regex function in route, url validate ....
PREG_BAD_UTF8_ERROR 'Malformed UTF-8 characters, possibly incorrectly encoded'

*Case 3: JSON Encode, Json output error - Caused by Monolog, Datatables Logs..

To Fix Case 2 & 3 you can try converting the input to utf-8, or remove non-utf-8 characters.

Eg1: Function to auto convert any string to utf-8 encoding

$newString = mb_convert_encoding($inputString, "UTF-8", "auto");

Eg2: fix utf-8 encoding for Datatables column

$datatable->editColumn('title', function(Post $node) {
            return mb_convert_encoding($node->title,"UTF-8", "auto");
        });
Done ! For any other questions you can leave them in the comment section at the end of this article. Thank you.

Tuesday, 19 May 2020

MySQL: Fix Error 1071 "Specified key was too long"

MySQL/MariaDB Error 1071 when try to import SQL File:

#1071 - Specified key was too long; max key length is 767 bytes
Sometime error is "max key length is 1000 bytes"

Reason:
From MySQL 5.6 and MariaDB 10.2.2 InnoDB File Format default is Barracudar. Barracudar is newer file type ,support many new format types (DYNAMIC and COMPRESSED). But in older version of MySQL or MariaDB default InnoDB File Format is still Antelope. So if you want to import a database using Barracudar(exported from newer version), you also need to change the current file format to Barracudar.

Solved:
To do that, run the following command in the Mysql command line (Root account is required):

SET GLOBAL innodb_file_format = Barracuda;
SET GLOBAL innodb_file_per_table = on;
SET GLOBAL innodb_default_row_format = dynamic;
SET GLOBAL innodb_large_prefix = 1;
SET GLOBAL innodb_file_format_max = Barracuda;
FLUSH PRIVILEGES;
Done ! The problem has been solved, you can try imoport SQL file again.

Tip: You can run Mysql command line from linux terminal or run Query in Navicat, PHPMyadmin ....

mysql -h localhost -u root -p
Refer: https://dev.mysql.com/doc/refman/5.6/en/innodb-file-format-enabling.html

Thursday, 14 May 2020

Git: How to fix Error Pulling is not possible because you have unmerged files



If you try to pull new code while some local files have been changed without commit, you will get this error.

Error Pulling is not possible because you have unmerged files.
or
Error: Your local changes to the following files would be overwritten by merge
To fix it you have 2 options:

* Method 1: Commit the changes, then pull the new code
- Add new files if available
git add filename1.xyz folder/filename2.xyz  
or (add all new file)
git add -A    
- Commit new changes

git commit -m "Add new file or something need to noted"
* Method 2: Remove all local changes to update new code
(We often encounter this situation on the server)
To do so, run the following command:

git reset --hard origin/master
- note: 'master' is the name of the branch you want to update new code from that.

Done ! Now we can update new code by git pull command.

git pull




Friday, 8 May 2020

MongoDB: Error Unsupported mechanism SCRAM-SHA-256


Studio 3T Fix Error 2 "Unsupported mechanism SCRAM-SHA-256" when try to connect to server.

Cause: 
MongoDB only supports SCRAM-SHA-256 for authenticating users with passwords from MongoDB version 4.0. So if you encounter this error, you can try to switch back to the SCRAM-SHA-1 method.

More about MongoDB SCRAM supports :
MongoDB >= 4.0 Support SCRAM-SHA-1 and SCRAM-SHA-256
MongoDB 3.x Support only MONGODB-CR and SCRAM-SHA-1
MongoDB <3.0 Support only MONGODB-CR

Thursday, 7 May 2020

Composer: How to fix error "Fork failed errors" in Linux server


In many cases we encounter lack of memory errors when running "composer install" or "composer update" command to update packages in our PHP project.
Some of the error messages you may receive:

  • - proc_open(): fork failed errors - Cannot allocate memory
  • - exception is caused by a lack of memory
  • - Killed

The cause of all these errors is because our server does not have enough RAM to allocate to Composer. Increasing packages in the project, the larger the size, so this error is also becoming more and more common. To fix them you can increase the server's physical RAM but the cost will be quite expensive.

There is another solution simpler and completely free to fix Composer memory error. That is we can enable swap space for the server. This is quite easy to implement and will thoroughly fix the error we encounter. For each operating system, there will be different ways to initialize swap partitions. You can refer to one of the instructions below:

Enable Swap to fix Composer memory error for Centos, Ubuntu ...:

Step 1: Create a new Swap file (1GB to 3Gb)
sudo fallocate -l 3G /swapfile
Step 2: Add Write permission for Swap file
sudo chmod 600 /swapfile
* If your server is running under SELinux, after chmod command you must run the following command
sudo chcon -t swapfile_t /swapfile 
Step 3: set up a Linux swap area
sudo mkswap /swapfile
Step 4: Active Swap for server
sudo swapon /swapfile
opening the "/etc/fstab" file
vi /etc/fstab
then add the following line at end of file.
/swapfile swap swap defaults 0 0

Done ! If there are no errors, you have successfully enabled the swap for your server. You can try checking the swap partition with one of the following commands:
sudo swapon --show
or
top
or
sudo free -h

Now it's time to try running the composer commands again. Hopefully the bug has been fixed. Good luck.

*Note:
- /swapfile  - is file name for swap file, you can use another name or put it in another folder.
- In addition to using swap files, you can also try to use swap partitions.
- Some problems with PHP modules can also cause errors because Composer runs on PHP

*Refer: https://getcomposer.org/doc/articles/troubleshooting.md