terraform : Error locking state: Error acquiring the state lock: ConditionalCheckFailedException: The conditional request failed

Error locking state: Error acquiring the state lock: ConditionalCheckFailedException: The conditional request failed
status code: 400, request id:

 

ID: 222Whatever-222Whatever-222Whatever-d86c-222Whatever
Path: terraform.tfstate
Operation: OperationTypePlan
Who: username@hostname
Version: 0.11.7
Created: 2018-09-27 15:02:22.226277904 +0000 UTC
Info:

 

Terraform acquires a state lock to protect the state from being written
by multiple users at the same time. Please resolve the issue above and try
again. For most commands, you can disable locking with the “-lock=false”
flag, but this is not recommended.

 

Fix:

terraform force-unlock 222Whatever-222Whatever-222Whatever-d86c-222Whatever . # this is the ID provided in Error message

How to move terraform state from one bucket to another?

From your existing config/s3 repo setup. Download the state with following command.

  1. terraform state pull > terraform.tfstate
  2. aws s3 cp –sse AES256 terraform.tfstate s3://Bucket_Name/Whatever_Path/terraform.tfstate
  3. Updated your backend config with new s3 location and change the profile for that account in your terrafrom config or backend config.
  4. Run terrafrom init

It will throw an error such as


Error loading state:
state data in S3 does not have the expected content.

This may be caused by unusually long delays in S3 processing a previous state
update. Please wait for a minute or two and try again. If this problem
persists, and neither S3 nor DynamoDB are experiencing an outage, you may need
to manually verify the remote state and update the Digest value stored in the
DynamoDB table to the following value: fe1212121Blah_Blah_Blah_1mduynend

Terraform failed to load the default state from the "s3" backend.
State migration cannot occur unless the state can be loaded. Backend
modification and state migration has been aborted. The state in both the
source and the destination remain unmodified. Please resolve the
above error and try again.

4. Go to your dynamoDB table config that you have setup in your AWS console for the table and LockID string. Search for the KEY that you have provided for LockID and change the value there with above mentioned fe1212121Blah_Blah_Blah_1mduynend value in last error.

5. Run terraform init again

 

This should move your S3 state from one bucket to new account’s bucket.

Gpg decryption error

While trying to decrypt the secrets in single line command line below I was getting error.


cat file <or echo "whatever">  | base64 --decode | gpg -d

gpg: public key decryption failed: Inappropriate ioctl for device
gpg: decryption failed: No secret key

The reason for the key that you have used is password protected. The pipe won’t work with gpg if your key is password protected.


gpg --export "Jayesh-key" | base64 # To get your key

gpg --list-keys

In order to get that working. Either you remove pipe in 2 commands.


echo "whatever" | base64 --decode > file.gpg

gpg -d file.gpg

or you can modify your key to be without password by providing blank password but thats not a recommended or ideal way.


gpg --edit-key YourKey

gpg prmpt > passwd

Once it prompts enter existing password to unlock. Once done just enter for blank password.

gpg prompt > save

Puppet Error 400 on SERVER: A duplicate resource was found while collecting exported resources, with the type and title Host

Even after clearing the certs from puppetmaster and client, if you are getting below error on your puppet client

Error 400 on SERVER: A duplicate resource was found while collecting exported resources, with the type and title Host

then its because you have messed up with certs badly.

Here is what you need to do.

Check the certs name from ls -al ${PUPPET_HOME}/ssl/ -R

once of the cert above has multiple hostname in it. Find all the hostname that comes as part of above command and delete all of them from puppet master.

once done clean the ssl folder from client

rm -rf ${PUPPET_HOME}/ssl/

and run the puppet agent.

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.