Sunday, January 12, 2020

Solution for Docker in WSL and connection problems for Vscode running Remote-Container cmds


Have you already set up an machine running on WSL version 2 with Docker and is about to run and set up your project in an remote container from vscode but can't connect to Docker from Visual Studio Code?

You might encounter errors in Vscode when running Remote-Container: Opening folder in container like these or similar.

error during connect: Get http://localhost:2375/v1.40/version: dial tcp [::1]:2375
ECONNREFUSED 127.0.0.1:2375

Even though you have set up environment variable DOCKER_HOST to "tcp://localhost:2375" and confirmed that the communication works to the Docker server from the terminal/cmd/shell?

Then you might need to change the environment variable of DOCKER_HOST to the actual IP-adress of the WSL machine running the docker server. At least if you want VsCode to be able to run the containers with docker.

You'll find the IP adress of your machine by running i.e. this command from a windows terminal:
wsl.exe -d CHANGE_THIS_TO_YOUR_DIST_NAME /bin/bash -c "ip addr show eth0 | grep 'inet\b' | awk '{print $2}' | cut -d/ -f1"
CHANGE_THIS_TO_YOUR_DIST_NAME could be Ubuntu-16.04 or Ubuntu-18.04 or any other OS you've installed.
Copy the IP-adress and update DOCKER_HOST with the actual IP of the WSL machine. Close down vscode and open again to refresh the env-variables. Vscode should now be able to run the docker commands.

Remember to update the IP-adress in your DOCKER_HOST environment variable when you restart windows and since your virtual machine in WSL doesn't have a static IP, yet. See this issue about WSL dynamic and missing static IP-config

Tip! Guide for setting up WSL2 with Docker server in Windows.

Wednesday, July 31, 2019

"Join.me" free alternative - Best one alternative

Looking for an Join.me alternative since they have no free plans since june 2019?

9€ or $10 might not be much to pay per month for a fantastic and painless share screen meeting product but if you are hosting meetings very rarely, it might not attract you to buy one month for one simple meeting.

My searching for another solution led me to the Zoom product as an alternative to Join Me. Zoom offers a basic plan which is free and allows you to host unlimited meetings, share screen, webcam, recordings, plan meetings etc. A lot of more functionality than Join.me has to offer, and for Free.

Joining a meeting with Zoom in default settings, forces you to download their application but there is an setting in your account where you can make meetings available in the browser without the need to download and install the Zoom application.

My findings is that Zoom is a powerful solutions for online meetings and the best free alternative to Join.me without any download and install hassle.

Pricing and plans comparison


Join.Me plans

Zoom.Us plans

Thursday, January 14, 2016

php init_set session gc_maxlifetime doesn't work (solution VPS)





I had problems with changing the max session lifetime as it didn't work by just writing this to my php code:
ini_set('session.gc_maxlifetime', 8*60*60);
ini_set('session.cookie_lifetime', 8*60*60);
My goal was to set the session lifetime to 8 hours (8*60*60 = 28800 seconds). Still the sessions was destroyed after 1 hour or 3600 seconds. 3600 seconds is my default session gc_maxlifetime setting in php.ini ( /etc/php5/apache2/php.ini Ubuntu 14.04 ) and the default is 1440 seconds.
I confirmed that the parameter was actually changed with
ini_get('session.cookie_lifetime');
And yes. It was set to 28800 seconds. So what then if I could change the session.cookie_lifetime but it still doesn't work?

The problem was not anything with my settings. But with the default settings of how the system handles the garbage collection for the sessions that is stored on the server. There is a cron job that runs every X minute and a bash script that wipes out the old session, where the sessions are stored and based on the value set in the php.ini file, not the manual configuration I'm setting in my script.

So as long as I don't specify another save path for the session files, the default handler for the garbage collection will wipe those out.

One solution for this is to save the php sessions in another path:
ini_set('session.save_path', getcwd().'/../phpSessionStorage');
Now everything should work as expected. But one thing to keep in mind is that if you specify another save path for the php sessions then you need to remove all the old ones, some sort of garbage collector. There are different ways to handle this, maybe the easiest way is to use the session.gc_probability ( e.g. ini_set('session.gc_probability', 1) ) but I wrote a short command for my crontab to clear all the old ones that is older than 480 minutes ( 28800 seconds ).
0 * * * * find /var/www/websitefolder/phpSessionStorage -cmin +480 -type f -delete
As you can see, this cron job runs every hour and removes the old session files from the custom session folder.

So after all. My initial problem was never with a php-setting or apache but how Ubuntu-combined-with-php5 handles the garbage collector for the old php sessions.

Some tips when you'are having troubles with not getting the session.gc_maxlifetime to work.

  1. Are you allowed to change the session.gc_maxlifetime with ini_set() function? Check your permissions and your php.ini if the function is maybe disabled ( disable_functions ).
  2. All session settings must be declared before the session_start() function in your php-code. You can see if the session has been started with session_status() function.
  3. Check with ini_get() function if your configuration with ini_set() is really applied.
  4. What is wiping out the stored sessions if there are no configuration fault?
Read more about PHPs sessions configuration.

Friday, December 11, 2015

AutoMySQLBackup daily rotation only keep one day or latest backup day SOLVED

I had problems with my AutoMySQLBackup script on my ubuntu vps server, using the latest (3.0_rc6) available version of the script. The problem I had was that the daily rotation was not working as expected. The script kept yesterdays backup and did not remove it. It seemed to be happening randomly but nothing is ever random.

So today I took some of my precious time to investigate the problem. I found out that the problem was on line 803:

find "${CONFIG_backup_dir}/${subfolder}${subsubfolder}" -mtime +"${rotation}" -type f -exec rm {} \;
The rotation-parameter was configured to be "0". No problems with that as we only want to keep the latest backup file that was created today. But the mtime function with find is the problem where the argument to mtime are the number of whole days. While some backup-files wasn't created (or modified) a whole day from the current time.
-mtime n
       The primary shall evaluate as true if the file modification time subtracted from the initialization time, divided by 86400 (with any remainder discarded), is n.
So this is the problem. Now the solution can be fixed in various of ways. But I just needed a quick fix to this as I always want to only keep the latest mysql database backup files. So I modified that line (in particularly and some others just on case I need something else than 0 in rotation configuration) to:
find "${CONFIG_backup_dir}/${subfolder}${subsubfolder}" -mmin +$((60*23)) -type f -exec rm {} \;
As you can see from above, I'm looking for files that is 23 hours or older. So this covers my gap of backup file creation time.

I'm happy if this helps you out. AutoMySQLBackup is a great script but not really maintained the best.

Thursday, May 28, 2015

Exclude directories and files with Tar in Ubuntu Linux

I had problems with figuring out how to exclude directories with files and sub-directories with tar. I've tried several of ways to accomplish this but all of my effort ended with the exclude being ignored somehow.

But finally I found out how to do this. So my system is Linux Ubuntu 14.04 with Tar version 1.27.1.

tar --exclude=var/www -cvpjf /var/backups/vps/vpsBackup_$(date +"%F").tar.bz2 *
So what the above does: excludes the directory www in var with all it's files and sub directories. So no trailing slash after equal sign and no after in the end of path.

The whole manual for tar can be found here. Also with the command tar --help will show you a list of possible actions.

I hope this will help out somebody.

Tuesday, October 14, 2014

Solution to Knockd won't work / open port in iptables

I had a struggle to get Portknocking with knockd to work on my Ubuntu 14.04 VPS. I've read and followed a lot of instructions, Ubuntus instruction among these. But nothing seemed to help me out here.

I did check my knockd log located to /var/log/knockd.log and the configuration for activating the knockd commands seemed to work. But I always ended up with "command returned non-zero status code (a number)"

So what I figured out that it had to do something with the start_command and stop_command that didn't do the job correctly. Everywhere I could read that you were "supposed to" control the IP tables by having e.g.
start_command = /sbin/iptables -A INPUT -s %IP% -p tcp --dport 22 -j ACCEPT
If it was say to open up the SSH-default port 22. But that didn't work for me.
The first I did was to check if /sbin/iptables even existed and it didn't. No wonder why nothing happen with my iptables configuration...

So one solution to this was for me to create two shell script to configure the iptables for me.
I created a knock-open.sh containing this.
#!/bin/sh 
iptables -I INPUT 1 -s $1 -p tcp -m tcp --dport 22 -j ACCEPT
Then I created a knock-close.sh:
#!/bin/sh
iptables -D INPUT -s $1 -p tcp -m tcp --dport 22 -j ACCEPT
And my knockd.conf-file (/etc/knockd.conf), I configured it like this:
[options] 
logfile = /var/log/knockd.log 
[SSH] 
sequence      = 1212:udp,3861:tcp,8721:udp 
seq_timeout   = 5 
tcpflags      = syn 
start_command = sh /var/scripts/knock-open.sh %IP% 
cmd_timeout   = 20 
stop_command  = sh /var/scripts/knock-close.sh %IP%
So this did the trick for me. After restarting the daemon (service knockd restart) and knocking the sequence ports, iptables was now configured correctly and working with knockd.

I hope this solution helps someone out there who's struggling with knockd and iptables.

Thursday, October 9, 2014

Delete all mails or selected mails in mbox in Linux Ubuntu

Every time you read a mail with the mail command in Linux terminal and you don't delete the mail - those read mails will be stored in an mbox-file located to /root/mbox (if root is the user). This file can get pretty big depending on how many e-mails you leave undeleted.

To view and delete all those in mbox you do this:
mail -f
d *
Where you tell with the -f flag to read all your stored emails and then followed by a delete command and the asterix (*) means everything. If you would like to just delete selected mails from your mbox you write d then followed by the mail number. E.g. I want to delete message number 15 from my mbox:
mail -f
d 15

Tuesday, October 7, 2014

Fix for rsyslog uses almost 100% CPU on OpenVZ system

If you ever get the problem with rsyslog for some reason use nearly 100% of the CPU all the time there may be some compatibility problem (probably a bug out of your control) with your system and rsyslog. Especially systems running on OpenVZ.

I had this problem with my VPS running Ubuntu 14.04.01 and on OpenVZ

A quick fix to prevent this for me was is to change the rsyslog.cnf-file by terminal:
sed -i -e 's/^\$ModLoad imklog/#\$ModLoad imklog/g' /etc/rsyslog.conf
You should restart the rsyslog-service to make the changes apply by:
service rsyslog stop
service rsyslog start
I hope this solve the problem for you.

Monday, November 25, 2013

Solution to order pages/posts specific by id in array with WP Query

Have you had problem with not getting the specific posts displaying in the order you have wanted it to be. Normally the Wordpress WP Query is sorted by the post title but what if you don't want to order the query and just have it "un-ordered", the way you write the id's to be.

The solution to this problem is to order your result with the pages to get.

$you_query = new WP_Query(array('post_type' => 'page', 'post__in' => 'array(12, 10, 18, 22)', 'orderby' => 'post__in'));

So that's how you order your result with your array or string of posts. No manual need of ordering or any other hassling.

Wednesday, November 13, 2013

Bootstrap navbar as your Wordpress menu

Do you want to use the bootstrap navbar as a menu in Wordpress? No problems. It takes just a few seconds to config.

What we want to achieve is to use the bootstrap navbar. No plugin is required but we need to download the helper file to achieve this. That one is called wp-bootstrap-navwalker - "A custom Wordpress walker to implement the Twitter Bootstrap dropdown navigation using the Wordpress built in menu manager." That can be found here and the direct download location of the navbar here. Just note that this is for bootstrap 3.0+ and if you have the legacy version (2.3.2) then you need another version of the helper.

Include the file from your functions.php-file. The file should be placed somewhere in your theme-folder.

require_once('wp_bootstrap_navwalker.php');

Then you need to update your wp_nav_menu() in your theme.
    wp_nav_menu( array(
        'menu'              => 'primary',
        'theme_location'    => 'primary',
        'depth'             => 2,
        'container'         => 'div',
        'container_class'   => 'collapse navbar-collapse navbar-ex1-collapse',
        'menu_class'        => 'nav navbar-nav',
        'fallback_cb'       => 'wp_bootstrap_navwalker::fallback',
        'walker'            => new wp_bootstrap_navwalker())
    );

"primary" is the name of your menu that you have probably already defined somewhere in your functions.php-file but if you don't have done that this is how you could do it:

register_nav_menus( array(    'primary' => __( 'Primary menu', 'yourthemename' ),) );

That's it. But you may need to put some surrounding code to get the appearance you look for. It could be something like this in the source of your theme-file:

<div class="navbar navbar-default navbar-fixed-top" role="navigation"><nav>    <div class="container">        <div class="navbar-header">            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse">                <span class="sr-only">Toggle navigation</span>                <span class="icon-bar"></span>                <span class="icon-bar"></span>                <span class="icon-bar"></span>            </button>            <a class="navbar-brand" href="<?php bloginfo('url'); ?>"><?php bloginfo('name'); ?></a>        </div>
        <?php            wp_nav_menu( array(                'menu'              => 'primary',                'theme_location'    => 'primary',                'depth'             => 2,                'container'         => 'div',                'container_class'   => 'collapse navbar-collapse navbar-ex1-collapse',                'menu_class'        => 'nav navbar-nav',                'fallback_cb'       => 'wp_bootstrap_navwalker::fallback',                'walker'            => new wp_bootstrap_navwalker())            );        ?>    </div></nav></div>

Heads up! This menu does only support 2-level of depths. Check out the links above to learn more about the navbar.

Monday, November 11, 2013

Custom image sizes missing in the media up-loader in Wordpress administration

Does your Wordpress media uploader in the administration miss the custom images sizes that you have configured? Don't worry.

In Wordpress 3.5 something seemed to have changed and any custom image sizes weren't available to select when inserting an image to a post or page. I really don't know what have changed but I know the solution and it's quite simple.

The thing you need to do is to create an filter in your functions.php that modify the Wordpress built-in function "image_size_names_choose()" and add all your custom image size to the "list".

Add this following code to your functions.php-file:

function my_custom_sizes( $sizes ) {    return array_merge( $sizes, array(        'custom-300' => __('Custom 300')    ) );}add_filter( 'image_size_names_choose', 'my_custom_sizes' );
That's it!

And if your don't remember how to add a custom image size in Wordpress. It's simple. Add this code to your functions.php-file:

add_image_size( 'custom-300', 300, 300 );

Wednesday, November 6, 2013

Change or modify elements in the content in Wordpress

Have you ever wanted to change the output of a Wordpress page or a post? Maybe modify the H1-elements in the content or something else. The solution is quite simple to achieve this.

Lets say we wanted to add something, in this case a header-element before the H1-element and a closing one right after. This is how you do it:

Put this code below in your functions.php-file:
function filter_h1_pages( $content ) {
$content = str_ireplace( '<h1>', '<header><h1>', $content ); return str_ireplace( '</h1>', '</header></h1>', $content );}add_filter( 'the_content', 'filter_h1_pages' );

What the code does is replacing a string with something else, twice and then return it. So we have filtered the main function the_content in Wordpress.

Friday, October 4, 2013

Woocommerce - Removing or changing fields in edit shipping or billing addresses.

Have you had problems with alter/remove/change or add fields for the edit shipping or edit billing addresses? Doing a search on this topic seems like I wasn't the only one who had the problem. But I've the solution for how to do this.

The first problem I had was to to know what function that controlled this fields. But pretty soon I found out that they where in fact described in the woocommerce docs.
The shipping fields exists in this function : woocommerce_shipping_fields and the billing fields exists in this function: woocommerce_billing_fields.

So the method to change these fields are then fairly easy to do. This is an example code in the functions.php-file on how to remove an unnecessary field "shipping state" and to set an label to the "shipping address 2":

add_filter( 'woocommerce_shipping_fields' , 'custom_override_shipping_fields' );
function custom_override_shipping_fields( $fields ) {

unset($fields['shipping_state']);
$fields['shipping_address_2']['label'] = 'Address Field 2';

     return $fields;
}

The same solution goes for billing fields. 
If you want to alter any fields on the checkout page you could use this method also. The function for those fields lays in this function "woocommerce_checkout_fields". An heads up: the array $fields is one step deeper and therefore if you want to remove the shipping_state like in the example above then you would need to to it like this: "unset($fields['shipping']['shipping_state']);" - notice the extra bracket. 

If you would like to know which fields exist for e.g. the shipping fields function, then use the php function var_dump(). IE: Put "var_dump($fields)" inside the custom override function and it will show you how the array looks like and all the settings for all fields.


Tuesday, January 15, 2013

Config logrotate for apache log-files in "www"-directory or in other non-standard

If you have configured Apache to split error and access logs for each virtual server or configured website. Then logrotate wont rotate those log-files in their custom locations with standard configs. Logrotate comes normally installed with your distribution and is configured to rotate the apache log files that is located in /var/logs/apache2.

But if you have several websites running on your VPS or server, it's linkley you have a seperate log file for each website that you have configured and the logging wont be in the standard location.

As an example. I've several websites running under a structure of "/var/www/$NAMEOFTHEWEBSITE". Now each website has separate logging, in a structure like this  "/var/www/$NAMEOFTHEWEBSITE/logs". In each logs-directory I've a access.log, error.log and a php-error.log. If I want to rotate these with logrotate I need to configure logrotate for that.

This is done by creating another config file for my custom directories.

vim /etc/logrotate.d/www

Then with this configuration:
/var/www/*/logs/*.log { 
weekly
missingok
rotate 26
compress
delaycompress
dateext
notifempty
create 640 root adm
sharedscripts
postrotate
if [ -f "`. /etc/apache2/envvars ; echo ${APACHE_PID_FILE:-/var/run/apache2.pid}`" ];

then /etc/init.d/apache2 reload > /dev/null fi 
endscript
}

My configuration does this:
  • For each and any .log-file in /var/www/*/logs/
  • Do weekly rotation. (weekly)
  • If  log-file is missing, ignore without error message (missingok)
  • Rotate for 26 weeks (rotate 26)
  • Compress all log-files (compress)
  • Delay compression with one time (delaycompress)
  • Name the rotated files with a date-based name so it's easier for me to know where to look (dateext)
  • Do not rotate if log-file is empty (notifempty)
  • Owner and permission settings for rotated file (create 640 root adm)
  • Normally, prescript and postscript scripts are run for each log which is rotated, meaning that a single script may be run multiple times for log file entries which match multiple files (such as the /var/log/news/* example). If sharedscript is specified, the scripts are only run once, no matter how many logs match the wildcarded pattern. However, if none of the logs in the pattern require rotating, the scripts will not be run at all. This option overrides the nosharedscripts option and implies create option. (sharedscripts)
  • The lines between postrotate and endscript (both of which must appear on lines by themselves) are executed after the log file is rotated. These directives may only appear inside of a log file definition. (postrotate & endscript)

That's it. I hope it helps you out configuring your vps or server with the very useful logrotate.

Wednesday, December 5, 2012

require directives present and no Authoritative handler

If you get an error that looks like this in the Apache error.log:
access to / failed, reason: require directives present and no Authoritative handler.

Then you've probably configured your .htaccess file wrong. As an example, you may have configure the Require user wrong.

If you want to grant access to a singel user then the line in the htaccess-file should look like this:
Require user <username>
And if you want to grant access to any valid user then it should be like this:
Require valid-user

An example of the whole htaccess with Basic authentication:
AuthUserFile /var/www/.htpasswd
AuthName "Enter Password"
AuthType Basic
Require user admin

Hope it helps you out!

Monday, September 17, 2012

checkdnsrr() PHP always return true or false, alternative with Windows

Have you had problem with the PHP function checkdnsrr() is always returning false?
Then you should first check if your php-version is >= 5.3.0 otherwise it wont function in Windows environment.

Have you had problems with checkdnsrr() is always returning true?
Then there may be other problems with windows not able to do the DNS-record check properly.

An alternative to checkdnsrr() with Windows built in function, "nslookup" and by wiriting this much self-explaining php-code:

    if(!empty($host)) {
        $recType="ns";
        exec("nslookup -type=$recType $host",$output);
        foreach($output as $line) {
            if(preg_match("/^$host/", $line)) {
                return true;
            }
        }
        return false;
    }
    return false;

Good luck!

Monday, September 10, 2012

Image slider, vSlider to Wordpress not function in IE or Chrome

Are you having problems with the image slider plugin vSlider 4.0 or another Wordpress image slider plugin? The problem I'll describe here is that the images won't be shown / displayed in Internet Explorer and Chrome but works fine in FireFox.

Then the problem can be that the plugin is configured with an "auto resize" setting. Try with unset this and see if the problem disappear.

Hope that will help you out here.

View cronjobs in ubuntu server

To see what cron jobs are running on your Ubuntu server or in terminal you can try with:
crontab -u [user] -l
"-u" parameter is the user cronjob.

To view what cronjob root has configured, you may use:
crontab -l
You can also view what cronjobs are set, daily, weekly, monthly and software specific jobs.
ls /etc/cron.daily/ -l
cat [filename]
To view the software specific  jobs you use the path, /etc/cron.d/

Monday, August 15, 2011

Custom time or interval for Cron to Wordpress

If you want to specify another interval to run a cron job in Wordpress beside the 3 built in you can do so. The custom code for specify another cron interval is:

add_filter( 'cron_schedules', 'my_corn_schedules');
function my_corn_schedules(){
return array(
'per_minute' => array(
'interval' => 60,
'display' => 'Every Mintue'
)
);
}

Interval is how many seconds in between. And display is an value for naming the interval or custom cron interval. Remember that when you are creating a cron job with the built in cron function in Wordpress, the cron job triggers by a user when the user is visiting your website.

Wednesday, February 23, 2011

The Dagon Design Sitemap Generator plug-in for wordpress and WP_Error

I've had some trouble with the Dagon Design Sitemap Generator for Wordpress, version 3.15. When I installed it for my Wordpress 3.0 installation, I got an error on the page.

The error message i got was: Catchable fatal error: Object of class WP_Error could not be converted to string in .. \wp-content\plugins\sitemap-generator\sitemap-generator.php on line 513

It seems like I'm not the only one who has this problem when I googled for 'sitemap-generator.php on line 513'. Neither has the founder of the plug-in updated it lately so there seems like there is no update for this problem.

However I've found an solution or rather work around to this problem that seems to work.

What to do is to modify the PHP code with just a few lines.
The original code was on line 513:
return DDSG_CAT_HEADER . ' < a href="' . get_category_link($post_data[$p]['id']) . '" title="' . strip_tags($post_data[$p]['title']) . '">' . $post_data[$p]['title'] . '< /a>';

Now the modifications that needs to be done are:

if(is_string($p))
return DDSG_CAT_HEADER . ' < a href="' . get_category_link($post_data[$p]['id']) . '" title="' . strip_tags($post_data[$p]['title']) . '">' . $post_data[$p]['title'] . '< /a>';
else
return false;


The only thing you need to do with this is to remove the white-spaces after '<' in the code because Blogger will treat that as a link so I had to make an space in between.

The problem seems to be empty categories, but I'm not sure.