Linux run script/service after few mins of reboot

You can use systemd timers to execute script a minute after boot.

First, create service file (/etc/systemd/system/myscript.service):

[Unit]
Description=MyScript

[Service]
Type=simple
ExecStart=/usr/local/bin/myscript

Then create timer (/etc/systemd/system/myscript.timer):

[Unit]
Description=Runs myscript every hour

[Timer]
# Time to wait after booting before activation
OnBootSec=1min
Unit=myscript.service

[Install]
WantedBy=multi-user.target
Now enable and run it:

# systemctl enable myscript.timer
# systemctl start myscript.timer

Eye strain: what to do?

While you are spending lots of your time. Make sure you are not putting too much of pressure on your eyes. Here is some tips.

These days your eyes can be put under a lot of strain for a number of reasons. Fortunately, there are a few things you can do to help relieve and even prevent eye strain so you’ll be able to keep using those babies for a long time.

Eight things you can do for eye health:

1) Get Plenty of Vitamin A
Your mother’s been telling you for years that if you eat carrots, it will increase your eyesight. This is absolutely true, but it isn’t just carrots you can eat–it’s anything with Vitamin A, which helps to safeguard against cataracts and macular degeneration. It also helps you to see better at night. Good food sources for Vitamin A include sweet potatoes, pumpkins, carrot juice, spinach, organ meats, kale, and turnip greens.

2) Take a Break
If you spend hours staring at a computer monitor or even a television every day, then taking a break will definitely help reduce eye strain. Try to spend no more than one hour without taking a break. Computer use results in a decrease of blinking to almost one third of normal, putting even more strain than usual on your eyes.

Note: If you have to stare at a screen for a long time, taking a break is one thing, but you should also look away from the monitor once about each ten minutes. There’s even software available to remind you.

3) Use Good Lighting
Avoid working in rooms that are dark or too dim. Using table lamps are better for your eyes than overhead lights. If you’re staring at a TV or monitor, make sure the light in the room is about equal to the brightness of the display. Movie theaters make up for this by having such a huge screen that their own light fills up the room.

4) Get Lots of Rest
Eyes need to sleep just like any other organ in your body. If your eyes are hurting or are bloodshot, you might need to get more sleep. At the very least, you can simply lay down and “rest your eyes” for a while.

5) Consider Using Reading Glasses
Even if you already wear prescription contacts, using reading glasses can help reduce eye strain. If you don’t wear glasses but have to struggle to read small text, if you use reading glasses not only will you be able to see small text more clearly, but you’ll also be able to sit further away from your computer monitor.

6) Do Eye Exercises
Close your eyes tightly for 5 seconds and then open them. Repeat 5 or 6 times. This will temporarily relieve strain and pressure. Lightly pressing a warm washcloth to your eyes once in a while is also a good idea. Don’t ever rub your eyes too hard, though, or you may break blood vessels.

7) Try Blackle
Viewing a dark screen is better than a bright, white screen. If you tend to use Google to search, try using Blackle instead (www.blackle.com). The search results are the same, plus as well as helping your eyes you also save energy.

9) Change the colour of your desktop/phone.
If you are using mac -> System Preferences -> Accessibiliy -> Display -> Check ” Invert colour. You can do the same by shortcut
Option + Command + N.
If you are using iphone -> Settings -> General -> Accessibility -> Display accomodation -> Invert Colors

9) Use ClearType
If you’re using Windows on your computer, try enabling ClearType font smoothing. (For Mac users, text smoothing is under the Appearance setting in your System Preferences.) This will help make reading type on your monitor much easier and put a little less strain on your eyes.

Mutex vs Semaphore

Mutex vs Semaphore
This post will cover the differences between Mutex vs Semaphore. When to use mutex and when to use semaphore?

Concrete understanding of Operating System concepts is required to design/develop smart applications. Our objective is to educate the reader on these concepts and learn from other expert geeks.

As per operating system terminology, mutex and semaphore are kernel resources that provide synchronization services (also called as synchronization primitives). Why do we need such synchronization primitives? Won’t be only one sufficient? To answer these questions, we need to understand few keywords. Please read the posts on atomicity and critical section. We will illustrate with examples to understand these concepts well, rather than following usual OS textual description.

The producer-consumer problem:

Note that the content is generalized explanation. Practical details vary with implementation.

Consider the standard producer-consumer problem. Assume, we have a buffer of 4096 byte length. A producer thread collects the data and writes it to the buffer. A consumer thread processes the collected data from the buffer. Objective is, both the threads should not run at the same time.

Using Mutex:

A mutex provides mutual exclusion, either producer or consumer can have the key (mutex) and proceed with their work. As long as the buffer is filled by producer, the consumer needs to wait, and vice versa.

At any point of time, only one thread can work with the entire buffer. The concept can be generalized using semaphore.

Using Semaphore:

A semaphore is a generalized mutex. In lieu of single buffer, we can split the 4 KB buffer into four 1 KB buffers (identical resources). A semaphore can be associated with these four buffers. The consumer and producer can work on different buffers at the same time.

Misconception:

There is an ambiguity between binary semaphore and mutex. We might have come across that a mutex is binary semaphore. But they are not! The purpose of mutex and semaphore are different. May be, due to similarity in their implementation a mutex would be referred as binary semaphore.

Strictly speaking, a mutex is locking mechanism used to synchronize access to a resource. Only one task (can be a thread or process based on OS abstraction) can acquire the mutex. It means there is ownership associated with mutex, and only the owner can release the lock (mutex).

Semaphore is signaling mechanism (“I am done, you can carry on” kind of signal). For example, if you are listening songs (assume it as one task) on your mobile and at the same time your friend calls you, an interrupt is triggered upon which an interrupt service routine (ISR) signals the call processing task to wakeup.

General Questions:

1. Can a thread acquire more than one lock (Mutex)?

Yes, it is possible that a thread is in need of more than one resource, hence the locks. If any lock is not available the thread will wait (block) on the lock.

2. Can a mutex be locked more than once?

A mutex is a lock. Only one state (locked/unlocked) is associated with it. However, a recursive mutex can be locked more than once (POSIX complaint systems), in which a count is associated with it, yet retains only one state (locked/unlocked). The programmer must unlock the mutex as many number times as it was locked.

3. What happens if a non-recursive mutex is locked more than once.

Deadlock. If a thread which had already locked a mutex, tries to lock the mutex again, it will enter into the waiting list of that mutex, which results in deadlock. It is because no other thread can unlock the mutex. An operating system implementer can exercise care in identifying the owner of mutex and return if it is already locked by same thread to prevent deadlocks.

4. Are binary semaphore and mutex same?

No. We suggest to treat them separately, as it is explained signalling vs locking mechanisms. But a binary semaphore may experience the same critical issues (e.g. priority inversion) associated with mutex. We will cover these in later article.

A programmer can prefer mutex rather than creating a semaphore with count 1.

5. What is a mutex and critical section?

Some operating systems use the same word critical section in the API. Usually a mutex is costly operation due to protection protocols associated with it. At last, the objective of mutex is atomic access. There are other ways to achieve atomic access like disabling interrupts which can be much faster but ruins responsiveness. The alternate API makes use of disabling interrupts.

6. What are events?

The semantics of mutex, semaphore, event, critical section, etc… are same. All are synchronization primitives. Based on their cost in using them they are different. We should consult the OS documentation for exact details.

7. Can we acquire mutex/semaphore in an Interrupt Service Routine?

An ISR will run asynchronously in the context of current running thread. It is not recommended to query (blocking call) the availability of synchronization primitives in an ISR. The ISR are meant be short, the call to mutex/semaphore may block the current running thread. However, an ISR can signal a semaphore or unlock a mutex.

8. What we mean by “thread blocking on mutex/semaphore” when they are not available?

Every synchronization primitive has a waiting list associated with it. When the resource is not available, the requesting thread will be moved from the running list of processor to the waiting list of the synchronization primitive. When the resource is available, the higher priority thread on the waiting list gets the resource (more precisely, it depends on the scheduling policies).

9. Is it necessary that a thread must block always when resource is not available?

Not necessary. If the design is sure ‘what has to be done when resource is not available‘, the thread can take up that work (a different code branch). To support application requirements the OS provides non-blocking API.

For example POSIX pthread_mutex_trylock() API. When mutex is not available the function returns immediately whereas the API pthread_mutex_lock() blocks the thread till resource is available.

References:

http://www.netrino.com/node/202

http://doc.trolltech.com/4.7/qsemaphore.html

Also compare mutex/semaphores with Peterson’s algorithm and Dekker’s algorithm. A good reference is the Art of Concurrency book. Also explore reader locks and writer locks in Qt documentation.

AWS CLI: 10 useful commands you may not know

The AWS console is certainly very well laid out and, with time, becomes very easy to use. However if you are not using the AWS CLI (Command Line Interface) from your local terminal, you may be missing out on whole lot of great functionality and speed. If you are not yet comfortable with the AWS Command Line Interface, there’s a great course on the subject available right now on Cloud Academy.

Even if you are used to the AWS CLI, I encourage you to take a look at the commands below, as you may not be completely aware of the power of the AWS CLI, and you might just end up saving yourself a whole lot of time. One important note: the precise syntax of some commands can vary between versions and packages.

1. Delete an S3 bucket and all its contents with just one command

Sometimes you may end up with a bucket full of hundreds or thousands of files that you no longer need. If you have ever had to delete a substantial number of items in S3, you know that this can be a little time consuming. The following command will delete a bucket and all of its content including directories:

aws s3 rb s3://bucket-name –force

2. Recursively copy a directory and its subfolders from your PC to Amazon S3

If you have used the S3 Console, at some stage, you’ve probably found yourself having to copy a ton of files to a bucket from your PC. It can be a little clunky at times, especially if you have multiple directory levels that need to be copied. The following AWS CLI command will make the process a little easier, as it will copy a directory and all of its sub folders from your PC to Amazon S3 to a specified region.

aws s3 cp MyFolder s3://bucket-name — recursive [–region us-west-2]

3. Display subsets of all available ec2 images

The following will display all available ec2 images, filtered to include only those built on Ubuntu (assuming, of course, that you’re working from a terminal on a Linux or Mac machine).

aws ec2 describe-images | grep ubuntu

Warning: this may take a few minutes.

4. List users in a different format

Sometimes, depending on the output format you chose as default, when you invoke long lists – like a large set of users – the display format can be a little hard to read. Including the –output parameter with, say, the table argument, will display a nice, easy-to-read table this one time without having to change your default.

aws iam list-users –output table

5. List the sizes of an S3 bucket and its contents

The following command uses JSON output to list the size of a bucket and the items stored within. This might come in handy when auditing what is taking up all your S3 storage.

1
aws s3api list-objects –bucket BUCKETNAME –output json –query “[sum(Contents[].Size), length(Contents[])]”

6. Move S3 bucket to different location

If you need to quickly move an S3 bucket to a different location, then this command just might save you a ton of time.

1
aws s3 sync s3://oldbucket s3://newbucket –source-region us-west-1 –region us-west-2

7. List users by ARN

“jq” is like sed for JSON data – you can use it to slice, filter, map, and transform structured data with the same ease that sed, awk, grep and friends let you play with non-JSON text.

Armed with that knowledge, we can now nicely list all our users, but only show their ARNs.

aws iam list-users –output json | jq -r .Users[].Arn

Note: jq, might not be installed on your system by default. On Debian-based systems (including Ubuntu), use sudo apt-get install jq

8. List all of your instances that are currently stopped, and the reason for the stop

Here’s another use of the JSON output parameter. This one will list all of your stopped instances and, best of all, show the reason that they were stopped:

1
aws ec2 describe-instances –filters Name=instance-state-name,Values=stopped –region eu-west-1 –output json | jq -r .Reservations[].Instances[].StateReason.Message
9. Test one of your public CloudFormation templates

If you have written a Cloud Formation Template and need to validate it before launching, you can do it from the CLI using the following format:

1
aws cloudformation validate-template –region eu-west-1 –template-url https://s3-eu-west-1.amazonaws.com/ca/ca.cftemplate
10. Other ways to pass input parameters to the AWS CLI with JSON:

You can pass all sorts of input parameters to the AWS CLI. Here’s an example of how to do it:

1
aws iam put-user-policy –user-name AWS-Cli-Test –policy-name Power-Access –policy-document ‘{ “Statement”: [ { “Effect”: “Allow”, “NotAction”: “iam:*”, “Resource”: “*” } ] }’

.so: cannot open shared object file: Permission denied

When I start the application in debug mode (sh -x) it works fine after taking few seconds while loading the libraries but without debug mode it failes with .so : cannot open shared object file: Permission denied even though it has proper read permission as well as proper read permission to all parent folders.

Then I figured out that its due to selinux in enforcing state.

Change : /etc/selinux/config from SELINUX=enforcing ## or permissive to SELINUX=disabled

Vagrant and Ansible: Automate wordpress blog site. Post a blog using a file by python script

Prerequisites:

1. You need to have Virtualization software installed on your desktop. You can try Oracle Vm VirtualBox.

2. You need to have Vagrant installed your computer.

Instruction for using this.
Steps:

1. Setup Linux Vagrant VM. I have used CentOS here as mentioned in below command.

#mkdir -p /path/to/your/project

#vagrant init chef/centos-6.5 https://atlas.hashicorp.com/chef/boxes/centos-6.5

– Setup the Vagrantfile provided in this repository and replace it here. Make sure to change the port on line no 45 if the
host port 8888 is already used on your computer.

2. Start the Virtual machine Vagrant box.

#vagrant up

– You are now running with wordpress site and you can verify that by accessing http://localhost:8888/ ( The port no is the
one that you have specified as host port no in above step)

– During this installation it installs epel repo, git and ansible locally

– It also runs ansible locally here. But you can leverage ansible script to run remotely.

– It also make sure that sshe keys are setup so that it wont prompt for login promp and key authentication during ansible play book run.

– It downloads the current git repo as per Vagrant files config.vm.provision script.

– It runs the ansible playbook to install all require software for wordpress.

– Here is the command that you have use in order to apply ansible-playbook manually.

– ansible-playbook -i hosts site.yml
3. Make sure to change the permission for blog_post.py as executable and while executing that script pass file that you want
to post it.

#chmod +x blog_post.py

#./blog_post.py filename.txt

– This adds the first line of filename.txt as a title of the post and rest of the line as contents of the post.

– Make sure to provide correct site URL here. on line no 7 of the script wp_site = “http://localhost/” or wp_site = “http://localhost:8888/” from whereever you are testing the site.

– This scripts uses automation user login credentails which were created during mysql db creation/import processs from
ansible’s wordpress role.

Documentation for Ansible configuration.

1. hosts:

– In this file make sure to add the correct IP or hostname at the bottom of the file. Right now it had localhost IP. but
if you are running it remotely make sure to add the IP or hostname under [wordpress-server]

2. site.yml
– Thi is site configuration and will apply only for all machines mentioned in [wordpress-server] and applied those by
roles.

3. roles
– This folder has different roles which has details about different components require for wordpress installation.
– common: You can add common software here. I have added epel-release repo and git there. So if you are using the ansible config from seperate ansible it will install require software on local macine if you are not installing it from vagrant provision script.

– apache: Installs httpd apache. Make sure to update. Custom config file for it is at templates/vhost.conf.j2

– mysql: Installs mysql related sofrware and adds the configuration for it. my.cnf file is specified in
templates/my.cnf.j2
– wordpress: Downloads and installs wordpress. Custom config file for it is at templates/wp-config.php.j2 as as well as
sql dump file. This mysqldump has been created after insall process (seperately) in order to get plain site page to
take out UI steps of going through install process after wordpress installation.

Configurations and credentails:

Configuations are mentioned in : /group_vars/all

wordpress console login :

Admin User : admin

Password: q1w2e3r4

Api script login :

Username: automation

Password: q1w2e3r4