nginx simple static caching

Creating a Cache Using fastcgi_cache_path

When we make requests to an application, sometimes the content doesn’t change at all, but in our current reverse-proxy setup we would still pass the request over to the application. We can prevent our application servers from receiving this extra load by having NGINX cache responses and serve that data back when the request matches. NGINX has a powerful caching mechanism built into it and works almost exactly the same regardless of whether you’re using proxy_pass, fastcgi_pass, or uwsgi_pass to proxy to another server. Each of the proxy modules that we’ve looked at so far has equivalent caching directives. We’re going to investigate caching by looking at our WordPress application. Let’s add a simple cache by editing /etc/nginx/conf.d/blog.example.com.conf:
/etc/nginx/conf.d/blog.example.com.conf
fastcgi_cache_path /var/cache/nginx/blog levels=1:2
                   keys_zone=blog:10m size=1g inactive=60m;

server {
    listen 80;
    server_name blog.example.com;

    root /var/www/blog.example.com;
    index index.php;

    fastcgi_cache_key $scheme$request_method$host$request_uri;

    location / {
        try_files $uri $uri/ /index.php?$args;
    }

    location ~ \.php$ {
        fastcgi_index index.php;
        fastcgi_pass unix:/var/run/php-fpm.sock;
        fastcgi_cache blog;
        fastcgi_cache_valid 60m;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    }
}
The first thing to notice is that we had to specify the properties and name of our cache using the fastcgi_cache_path directive. There are a lot of arguments to this directive, so see what they each do:
  • /var/cache/nginx/blog - specifies the directory to store the cached objects
  • levels=1:2 - specifies the number of subdirectory levels used in the cache. This is the recommended setting, yet not the default
  • keys_zone=blog:10m - Allows us to specify the name of the cache and the size of the memory space that will hold the keys and metadata information. The name and size of the lookup table so NGINX can quickly know if a request is a cache hit or miss
  • max_size=1g - Defines the maximum amount of storage we’re allowing NGINX to use for this cache. If not set it will keep caching new keys only limited by storage
  • inactive=60m - Defines the maximum cache lifetime of an item if it’s not accessed again. The cache will be populated on the first hit, and then after that, it will have 60 minutes to receive another request or the item will be removed from the cache
We’ve specified where to cache things, but for fastcgi and uwsgi caching we’ll need to also specify the cache key using the appropriate _cache_key directive. Our cache key is created from the requests scheme, host, method (GET | POST | etc), and request URI.
To see the fruits of the caching, we’re best off to open our browser’s developer tools to look at the network response time and response headers (right-click the page select “Inspect Element” then open the “Network” tab). We’ll reload the page after opening the network tab to see how long each request takes. This gives us the non-cached speed. Now we can reload NGINX before reloading the page to see the difference.
[root] $ systemctl reload nginx

Adding Additional Cache Header

It’s really helpful to know if our request was a cache hit or cache miss. We can display this in the browser’s response information by adding an additional header within our location block. NGINX provides an upstream_cache_status variable that indicates whether the current request is a cache hit or miss. We can set this value as a header using the add_header directive. Let’s add this now:
/etc/nginx/conf.d/blog.example.com.conf
fastcgi_cache_path /var/cache/nginx/blog levels=1:2
                   keys_zone=blog:10m max_size=1g inactive=60m;

server {
    listen 80;
    server_name blog.example.com;

    root /var/www/blog.example.com;
    index index.php;

    fastcgi_cache_key $scheme$request_method$host$request_uri;

    location / {
        try_files $uri $uri/ /index.php?$args;
    }

    location ~ \.php$ {
        add_header X-Cache-Status $upstream_cache_status;
        fastcgi_index index.php;
        fastcgi_pass unix:/var/run/php-fpm.sock;
        fastcgi_cache blog;
        fastcgi_cache_valid 60m;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    }
}
Now when we look at the response headers. We’ll see either “X-Cache-Status: MISS” or “X-Cache-Status: HIT”. This makes debugging caching issues a lot easier.

Not Caching Content

Caching the content of our blog is great, but we don’t want to cache more dynamic content like the admin area of WordPress. Let’s see if what we’ve currently got will cache the admin dashboard pages by going to blog.example.com/wp-login.php. Our “X-Cache-Status” shows a “MISS” the first time, but if we reload the page it doesn’t change to a “HIT”. Why not? NGINX caches responses that are valid, but the proxied server can ensure that it doesn’t happen by returning a “Cache-Control” header that includes “no-cache”.
If we would rather not cache some content without relying on the proxied application, we can do so by creating a more specific location block that doesn’t use fastcgi_cache. There are also conditionals and variables that we can use to indicate whether we’d like to bypass the cache. Here’s an example of how we could bypass the cache if the request includes /wp-admin:
/etc/nginx/conf.d/blog.example.com.conf
fastcgi_cache_path /var/cache/nginx/blog levels=1:2
                   keys_zone=blog:10m max_size=1g inactive=60m;

server {
    listen 80;
    server_name blog.example.com;

    root /var/www/blog.example.com;
    index index.php;

    fastcgi_cache_key $scheme$request_method$host$request_uri;

    set $skip_cache 0;

    if ($request_uri ~* "/wp-admin") {
        set $skip_cache 1;
    }

    location / {
        try_files $uri $uri/ /index.php?$args;
    }

    location ~ \.php$ {
        add_header X-Cache-Status $upstream_cache_status;
        fastcgi_index index.php;
        fastcgi_pass unix:/var/run/php-fpm.sock;
        fastcgi_cache_bypass $skip_cache;
        fastcgi_no_cache $skip_cache;
        fastcgi_cache blog;
        fastcgi_cache_valid 60m;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    }
}
We’re using set and an if context to manipulate a variable before routing the request. If $skip_cache is set to anything other than 0, we can us it with fastcgi_cache_bypass and fastcgi_no_cache to skip checking the cache and not cache the returned response.

Purging the Cache

To get rid of already cached content, we have a few options:
  1. Remove files from disk within our cache directory (/var/cache/nginx/blog in our case).
  2. Utilizing the fastcgi_cache_purge directive.

The first option is self-explanatory, we would use rm -rf to delete the directories under /var/cache/nginx/blog. The second option is more interesting and provides us with a way to programmatically purge the cache. Unfortunately, the documentation shows a fastcgi_cache_purge directive, but it is only part of the commercial distribution, NGINX Plus.

zfs tuning

zfs tuning:-
---------------

#!/usr/bin/env bash

echo "42949672960" >> /sys/module/zfs/parameters/zfs_arc_max
echo "32212254720" >> /sys/module/zfs/parameters/zfs_arc_min
echo "10737418240" >> /sys/module/zfs/parameters/zfs_dirty_data_max
echo "12" >> /sys/module/zfs/parameters/zfs_vdev_async_read_max_active
echo "8" >> /sys/module/zfs/parameters/zfs_vdev_async_read_min_active
echo "12" >> /sys/module/zfs/parameters/zfs_vdev_async_write_max_active
echo "8" >>/sys/module/zfs/parameters/zfs_vdev_async_write_min_active
echo "12" >> /sys/module/zfs/parameters/zfs_vdev_sync_read_max_active
echo 12 >>/sys/module/zfs/parameters/zfs_vdev_sync_write_max_active
echo 8 >>/sys/module/zfs/parameters/zfs_vdev_sync_write_min_active
echo 8 >> /sys/module/zfs/parameters/zfs_vdev_sync_read_min_active
echo 1 > /sys/module/zfs/parameters/zfs_prefetch_disable
echo "131072" >>/sys/module/zfs/parameters/zfs_vdev_write_gap_limit
 


cat zfs_prefetch_disable
 echo 1 > zfs_prefetch_disable
  zfs get recordsize data_pool
  zfs get recordsize data_pool/storage
  zpool status data_pool
grep gap
echo "131072" >>zfs_vdev_write_gap_limit
 zfs get sync data_pool/storage
 zfs set sync=disabled data_pool/storage

1_recommender_system_popularity_based

Data source: cuisine.csv kaggle
#ratings 2=best 1=medium 0=worst
import pandas as pd
import numpy as np
initialFrame=pd.read_csv('/Users/ezer/Downloads/RCdata/rating_final.csv')
cuisine=pd.read_csv('/Users/ezer/Downloads/RCdata/chefmozcuisine.csv')
#select restaurant with rating 2 gives boolean true false
top_rated_restaurant=initialFrame['rating']==2
#now create dataframe with rating2
frame=initialFrame[top_rated_restaurant]
# print(top_rated_restaurant.head())


result1=pd.DataFrame(frame.groupby('placeID')['rating'].count().sort_values(ascending=False))
# display 10 top rated popular restaurants
pd.DataFrame(frame.groupby('placeID')['rating'].count().sort_values(ascending=False)).head(10)

rating
placeID
135085 18
132825 15
135052 14
 ## creating dataframe of placeID
#pd.DataFrame([135085,132825,135052..],index=np.arange(5),columns=['placeID'])
#above is too manual so lets get index value only from above df
dfindexarray=result1.index
print(dfindexarray)

Int64Index([135085, 132825, 135052, 135032, 135025, 135038, 135075, 132862,
            135062, 135042,

LenOfDf=len(dfindexarray)
most_rated_places=pd.DataFrame(dfindexarray,index=np.arange(LenOfDf),columns=['placeID'])
print(most_rated_places)

summary=pd.merge(most_rated_places,cuisine,on='placeID')
# print(summary)
# get most common cuisine in top restaurants
# summary['Rcuisine'].describe()
# get cuisines from restaurant with id 135052
summary[summary['placeID']==135052]


placeID Rcuisine
2 135052 Bar
3 135052 Bar_Pub_Brewery

# Recommender system says that most popular rated Place serves Mexican food


matplotlib basics 2

 import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
x=np.linspace(0,5,11)
y=x**2

fig=plt.figure()
ax=fig.add_axes([0,0,1,1])
ax.plot(x,y)
ax.set_title('Title')

fig=plt.figure()
ax=fig.add_axes([0,0,1,1])
ax.plot(x,y,color='#FF8c00',linewidth=1,alpha=0.5,linestyle='--',marker='o',markersize=5) #rgb hex code and alha is transparency

matplotlib basics 1

import matplotlib.pyplot as plt
%matplotlib inline
plt.plot([3,7,8],[5,2,9],label="FirstLine")
plt.plot([2,5,7],[3,5,1],label="Second Line")
plt.xlabel('X-label sample')
plt.ylabel('Y-label sample')
plt.title('Interesting Graph\nCheckit out')
plt.legend()
plt.show()


1 numpy data science

 
a=[0,1,2,3,4,5] 
a[-1]    # last item in the array 
>>> a[-2]  # second last item in array it returns 4
 
a[-2:]   # last two items in the array
 
a[:-2]   # everything except the last two items
a[::-1]    # all items in the array, reversed
a[1::-1]   # the first two items, reversed
a[:-3:-1]  # the last two items, reversed
a[-3::-1]  # everything except the last two items, reversed
 
import numpy as np
array([0, 1, 2, 3, 4]) 
 
 

lacp bonding ubuntu


cat /etc/network/interfaces

# The primary network interface
# Interfaces bonding
auto eth4
iface eth4 inet manual
bond-master bond0

auto eth5
iface eth5 inet manual
bond-master bond0

auto bond0
iface bond0 inet static
address 10.233.193.23 
netmask 255.255.255.0
gateway 10.233.193.254
dns-nameservers 217.16.102.1
bond-mode 802.3ad
bond-miimon 100
bond-lacp-rate 1
bond-slaves none


# cat /proc/net/bonding/bond0 

Ethernet Channel Bonding Driver: v3.7.1 (April 27, 2011)

Bonding Mode: IEEE 802.3ad Dynamic link aggregation
Transmit Hash Policy: layer2 (0)
MII Status: up
MII Polling Interval (ms): 100
Up Delay (ms): 0
Down Delay (ms): 0

802.3ad info
LACP rate: fast
Min links: 0
Aggregator selection policy (ad_select): stable

Slave Interface: eth5
MII Status: up
Speed: 10000 Mbps
Duplex: full
Link Failure Count: 0
Permanent HW addr: f8:f2:1e:09:18:c1
Slave queue ID: 0
Aggregator ID: 1
Actor Churn State: none
Partner Churn State: none
Actor Churned Count: 0
Partner Churned Count: 0

Slave Interface: eth4
MII Status: up
Speed: 10000 Mbps
Duplex: full
Link Failure Count: 1
Permanent HW addr: f8:f2:1e:09:18:c0
Slave queue ID: 0
Aggregator ID: 1
Actor Churn State: none
Partner Churn State: none
Actor Churned Count: 0
Partner Churned Count: 0

Mode1 Activebackup
DEVICE=bond0
TYPE=Bond
BONDING_MASTER=yes
IPADDR=192.168.99.110
PREFIX=24
ONBOOT=yes
BOOTPROTO=static
BONDING_OPTS="mode=1 miimon=100 fail_over_mac=1"
DEVICE=bond0 TYPE=Bond BONDING_MASTER=yes IPADDR=192.168.99.110 PREFIX=24 ONBOOT=yes BOOTPROTO=static BONDING_OPTS="mode=1 miimon=100 fail_over_mac=1"

multipath ubuntu

# Single Path in multipath (not useful)
root@L0004906:~# cat /etc/multipath.conf | grep -v "#"
defaults {
    polling_interval    10
    selector        "round-robin 0"
    path_grouping_policy    multibus
    prio            const
    path_checker        directio
    failback        immediate
    no_path_retry       1
    features        "0"
}
blacklist {
}
blacklist_exceptions {
}
multipaths {
    multipath {
        alias           mpath0
    }
    multipath {
                wwid                    3600c0ff0001e54bae320f75401000000
                alias                   mpath1
        }
}

#Multiple path in multipath
root@L0004909:~# cat /etc/multipath.conf | grep -v "#"
defaults {
        polling_interval        10
        selector                "round-robin 0"
        path_grouping_policy    multibus
        prio                    const
        path_checker            directio
        failback                immediate
        no_path_retry           1
        features                "0"
}
blacklist {
}
blacklist_exceptions {
}
multipaths {
        multipath {
                alias                   mpath0
        }
        multipath {
                wwid                    3600c0ff0001e44ef1bd1fe5401000000
                alias                   mpath1
        }
    multipath {
                alias                   mpath2
        }
        multipath {
                wwid                    3600c0ff0001e44efd7cefe5401000000
                alias                   mpath3
        }
}
root@L0004909:~# multipath -ll
mpath2 (3600c0ff0001e6fd3d3cefe5401000000) dm-2 HP      ,MSA 2040 SAS   
size=3.3T features='1 queue_if_no_path' hwhandler='0' wp=rw
`-+- policy='round-robin 0' prio=1 status=active
  |- 4:0:0:11 sdh 8:112 active ready running
  `- 3:0:0:11 sdd 8:48  active ready running
mpath3 (3600c0ff0001e44efd7cefe5401000000) dm-3 HP      ,MSA 2040 SAS   
size=3.3T features='1 queue_if_no_path' hwhandler='0' wp=rw
`-+- policy='round-robin 0' prio=1 status=active
  |- 4:0:0:12 sdi 8:128 active ready running
  `- 3:0:0:12 sde 8:64  active ready running



  /opt/immune/bin/envdo python /opt/immune/installed/idx/apps/NewMerger/util/requester.py --q "|chart count() by device_ip"

sudoer nopasswd


root@ip-172-31-29-138:/etc/sudoers.d# cat 90-cloud-init-users 
# Created by cloud-init v. 18.2 on Fri, 22 Jun 2018 11:43:26 +0000

# User rules for ubuntu
ubuntu ALL=(ALL) NOPASSWD:ALL

vsftpd and pam

We will be using PAM to deny access to the VSFTPD service to certain users.
  1. Install the VSFTPD FTP server.
yum install vsftpd
  1. Start the service and verify it is running.
systemctl start vsftpdsystemctl status vsftpd
[OUTPUT]
● vsftpd.service - Vsftpd ftp daemon
   Loaded: loaded (/usr/lib/systemd/system/vsftpd.service; disabled; vendor preset: disabled)
   Active: active (running) since Fri 2017-02-24 13:39:42 CST; 5min ago
  Process: 17739 ExecStart=/usr/sbin/vsftpd /etc/vsftpd/vsftpd.conf (code=exited, status=0/SUCCESS)
 Main PID: 17741 (vsftpd)
   Memory: 592.0K
   CGroup: /system.slice/vsftpd.service
           └─17741 /usr/sbin/vsftpd /etc/vsftpd/vsftpd.conf
  1. Install the FTP client utility.
yum install ftp
  1. Using the client, verify that the user account can log in to the server.
ftp localhost
[output]
Connected to localhost (127.0.0.1).
220 (vsFTPd 3.0.2)
Name (localhost:root):
  1. Display the contents of the PAM VSFTP module, note the file referred to for denying user access.
cat /etc/pam.d/vsftpd
[output]
#%PAM-1.0
session    optional     pam_keyinit.so    force revoke
auth       required pam_listfile.so item=user sense=deny file=/etc/vsftpd/ftpusers onerr=succeed
auth       required pam_shells.so
auth       include password-auth
account    include password-auth
session    required     pam_loginuid.so
session    include password-auth
  1. Add the user account to the appropriate file noted from Step 5.
vim /etc/vsftpd/ftpusers
[contents with our setting on last line]
# Users that are not allowed to login via ftp
root
bin
daemon
adm
lp
sync
shutdown
halt
mail
news
uucp
operator
games
nobody
user
  1. Verify the user account is no longer permitted to log in.
ftp localhost
[output]
Connected to localhost (127.0.0.1).
220 (vsFTPd 3.0.2)
Name (localhost:root): user
331 Please specify the password.
Password:
530 Login incorrect.
Login failed.
ftp> quit
221 Goodbye.