How Do You Install a C Compiler on Linux?

Problem scenario
You want to program in the C programming language on a Linux server.  How do you code in C and test your programs?

Solution
Overview

Install the C compiler.

Procedures
1.  To find your distribution of Linux run this command:  cat /etc/*-release | grep -i pretty

2.  Find the one option of the below three that applies to your Linux:

  • For a Red Hat distribution (e.g., CentOS/RHEL/Fedora), run this command:  sudo yum -y install gcc gcc-c++
  • For a SUSE distribution of Linux, run this command:  sudo zypper -n install gcc gcc-c++

          # If you need assistance configuring a repository for SUSE for the first time, see this posting.

  • For Debian or Ubuntu distributions, run this command:

           sudo apt-get -y update && sudo apt-get -y install build-essential

How Do You Get Zypper Commands to Work to Install Packages on SUSE?

Problem scenario
No repositories are configured on your Linux SUSE server.  You want to install packages.  You cannot use zypper commands to install Linux utilities or other packages.  You want to know how to you use SUSE direct address XML files to install packages.  You think these XML files could help.  When zypper commands fail because a repository has never been configured on Linux SUSE, how do you begin to install packages?  How can you configure your server to work with a publically available (e.g. internet) server?

Solution
Run these two commands:

sudo zypper ar http://download.opensuse.org/distribution/leap/42.3/repo/oss/ openSUSE-Leap-42.3-Oss
sudo zypper se gcc

Now you are ready to install regular packages with zypper.  (The second command above searches for a C compiler.  You could search for a different package, but this one is common.)

A List of Chef Books

A Practical Guide to Continuous Delivery by Eberhard Wolff         
Automation through Chef Opscode: A Hands-on Approach to Chef by Navin Sabharwal and Manak Wadhwa
Chef Essentials by John Ewart
Chef Cookbook - Third Edition by Matthias Marschall      
Chef Infrastructure Automation Cookbook - Second Edition by Matthias Marschall
Chef Server on AWS (AWS Quick Start) by AWS Whitepapers and Amazon Web Services
Configuration Management with Chef-Solo by Naveed ur Rahman
Customizing Chef: Getting the Most Out of Your Infrastructure Automation by Jon Cowie
Exploration of Chef: Fast And Easy Learning! by Michael Bohner
Implementing Chef by Matt Stratton
Infrastructure as Code: Managing Servers in the Cloud by Kief Morris
Instant Chef Starter by John Ewart
Learning Chef by Rishabh Sharma
Learning Chef: A Guide to Configuration Management and Automation  by Mischa Taylor  and Seth Vargo
Learning MCollective: Parallel Server Management in Puppet and Chef  by Jo Rhett
Managing Windows Servers with Chef by John Ewart
Mastering Chef by Mayank Joshi
Mastering Chef Provisioning by Earl Waud
Test-Driven Infrastructure with Chef: Bring Behavior-Driven Development to Infrastructure as Code by Stephen Nelson-Smith
Using Chef with Microsoft Azure by Stuart Preston

How Do You Install Sysdig in a New Docker Container to Try It Out?

Problem scenario
You want to monitor Docker containers.  Therefore you want to install Sysdig to try it out.  How do you pull down a Docker container that has Sysdig installed in it?

Solution

Prerequisites
Docker needs to be installed.  If you need to install Docker on a CentOS/RedHat/Fedora distribution, see this posting.  If you need to install Docker on a Debian/Ubuntu, see this posting.  If you need to install Docker on a Linux SUSE, see this posting.  The Docker service needs to be running.

Procedures
1.  If your server (the Docker host) is using a Debian/Ubuntu distribution, run this command:
sudo apt-get -y install linux-headers-$(uname -r)

If your server (Docker host) is using a CentOS/RedHat/Fedora distribution, run this command:
sudo yum -y install kernel-devel-$(uname -r)

2.  Be advised that it is not recommended to use --privileged and docker.sock in the way that this step describes.  This is for testing purposes in a non-production environment.  The Docker host should otherwise be secure, and you should not have sensitive data on it. 

To test out Sysdig, run these two commands:
docker pull sysdig/sysdig

docker run -i -t --name sysdig --privileged -v /var/run/docker.sock:/host/var/run/docker.sock -v /dev:/host/dev -v /proc:/host/proc:ro -v /boot:/host/boot:ro -v /lib/modules:/host/lib/modules:ro -v /usr:/host/usr:ro sysdig/sysdig

How Do You Prepare Any Distribution of Linux in GCP to Have Similar Features to New AWS Instances?

Problem scenario
You want to have your Google Cloud Platform servers be ready for what you consider to be "regular" usage.  What should you do to get a server to be ready for these four things listed below?

1.  Able to SSH into it via Putty with a non-root user.
2.  Able to sudo with this non-root user.
3.  Files when modified in vi in "insert mode" can to receive clipboard-copied content with a right-click of a mouse.
4.  The user can press the up key to see previous commands in the history of commands entered.

(These settings are typical with AWS AMIs.)  How do you have a Linux server of any distribution (CentOS/RHEL/Fedora, Debian/Ubuntu, or SUSE) have these four traits before you have ever logged into it?

Solution

Summary
Use the "Startup script" in Google Cloud Platform.  This script comes with precautions.  Be careful when pasting it.  The lines can potentially not wrap properly.  Carriage returns could be introduced to make this script fail.  Be very careful because this script creates a user with sudoer privileges.  It also has a plaintext password in it for this user!  This script is for informational purposes.

If you use Puppet for example, the facter tool will be able to retrieve the entire script below after the script below runs.  This is a potential security concern!

This will create two "ChallengeResponseAuthentication yes" stanzas in most Red Hat family servers.  You can manually comment one out.  It will not prevent you from logging on.

Procedures
1.  When creating an virtual machine in Google Cloud Platform, there is a field for Startup script.  You may have to click the link "Management, disks, networking, SSH keys" to see the Startup script text field.  You can use this in the text field for "Startup script" if you want a user named "cooluser" with a password of "coolpassword" that can log in via SSH right from the beginning.  Use the content of this attachment.  It is a bash script named gcp_start_script_for_linux.txt.  The extension .txt is used so it is not blocked by strict security software programs.

2.  After the server is up, in the GCP web console click on the server's name.  This way you can view the details.  Click the "Edit" button.  Scroll down to the "Custom Metadata" or search for the word "start".  Click on the "X" to the right of it to eliminate the script as this picture shows (otherwise the script will run every time the server is rebooted):

Scroll down and click "Save".

3.  You are done.

For future reference

The settings are permanent.  You can reboot the server, and the settings will remain.  This posting, via the attached script, answers these four questions:
#1  How do you get a new Linux server in GCP to allow for Putty connections with a non-root user from the beginning?
#2  How do you get new Linux servers to have a non-root user be given sudoer privileges before you log in manually to the virtual machine? 
#3  How do you get Linux servers to support right-click mouse insertions of text via the vi text editor before you ever have logged into it? 
#4  How can you get the Linux server to support browsing previous commands with the up arrow before you have logged into it?

What Is the Equivalent of “find where the site.pp file should go on the Puppet Master”?

Problem scenario
You are managing a Puppet master server.  You want to find where the site.pp file should be.  Where do you look to determine the configuration?

Solution
The result of this command is the canonical answer:
puppet master --configprint manifest

If the above returns "No manifest", then run this command:
sudo puppet master --configprint all | grep basemodule

One of the paths resulting from the above command could be the answer to your question.  You may need to build out a directory tree on the Puppet master server with a command like this:

mkdir -p /etc/puppet/code/environments/production/manifests/

What is RedShift?

Question
There are five technology-related concepts called "Redshift" or "red shift."  What is the difference between them?

Answer
We hope to provide a thorough disambiguation of the term "Redshift" or "red shift."

In physics we know that visible light has a wavelength.  Depending on the color we see, the wavelength can be longer or shorter than others.  The longest wavelength is red (according to this page https://socratic.org/questions/what-color-of-light-has-the-longest-wavelength).  When objects in space move closer to a telescope, their wavelengths shorten and the light appears to be more blue (according to this posting https://www.space.com/25732-redshift-blueshift.html that worked).  When objects move farther away, they appear to be more red as the movement affects one cycle of a wave.  That is the trajectory increases the length of one wavelength so the visible color is more red (Space.com).

There is an economics of technology concept called "red shift theory" that was coined by Greg Papadopoulos (Informationweek.com).  This theory states that companies that use vastly more servers and I.T. infrastructure than normal companies will grow more rapidly than normal companies (Informationweek.com).  It is interesting to note that before 2008, he in effect predicted that Hadoop would satisfy the heavy demands of businesses.  He thought that large numbers of commodity (or low cost) servers could overcome the limitations of Moore's Law (Informationweek.com).  (In some articles there is no space between the words "red" and "shift" when referring to Papadopoulos's theory.  In some articles words are in uppercase.)  To learn more about this term, see this link (Zdnet.com).  

Amazon Redshift is a data warehouse PaaS offering for AWS.  It is based on PostgreSQL and the company ParAccel's technology (Wikipedia.com).  The color "red" can refer to Oracle's red logo; Oracle is nicknamed "Big Red" and this is the source of the term Redshift (according to a Quora answer).

Redshift is also a collection of astronomy software applications that can be used in planetariums or used to control telescopes.  To learn more see this external link or Wikipedia.

There is a Linux application called Redshift.  It is designed for the GUI desktop of Linux.  Redshift changes the color display throughout the day based on your geographic location and the season.  It makes it easy on the user's eyes and helps prevent insomnia.  To learn more about it, see this website, the main GitHub site for the project or Wikipedia.

How Do You Install Apache Cassandra on Linux SUSE?

Problem scenario
You are running Linux SUSE and want to install Apache Cassandra.  How do you install Apache Cassandra on Linux SUSE?

Solution
Prerequisites
i.  This solution assumes that you have Java installed.  If you need assistance, see this link.

ii.  This solution assumes your server has a total of 2.5 GB of memory (a combination of either virtual memory or RAM).  If you need to create virtual memory (aka swap space), see this article.  (Less that 2.5 GB may work.  We experienced trouble with 0.5 GB of RAM.)  If you want to upgrade your AWS server (and do not mind paying more for RAM because you need the hard drive space to not be allocated to virtual memory), see this posting.  If you want to resize your GCP server (and do not mind paying more for RAM because you need the hard drive space to not be allocated to virtual memory), see this posting.

iii.  This assumes that you have installed Apache Ant.  If you need directions, see this posting.

iv. This solution assumes that you have installed screen (the command line utility), and Git.  To install screen and Git, use this command:  sudo zypper -n install git screen
If you cannot install screen, you will need to create a duplicate terminal instead of using the screen command.   If you cannot install screen, you will skip step 6.b after you do 6.a.  With two terminal sessions, in one terminal you can start one process and allow the logging to stream to the screen.  With the second terminal you can do the steps in #4 in the procedures below.  If you did install screen, follow the directions as they are written.

Procedures
(If you are using non-AWS Linux server you will have to change the "ec2-user" in the script.)

1.  Run this script (e.g., create /tmp/precas.sh and run it with sudo bash /tmp/precas.sh):

usr=ec2-user  # replace "ec2-user" with the username who will run cassandra
cd /var/lib/
git clone http://git-wip-us.apache.org/repos/asf/cassandra.git
mkdir -p /var/log/cassandra/log
mkdir -p /var/lib/cassandra/{data,saved_caches,commitlog}
groupadd cassandra
usermod -aG cassandra $usr
usermod -aG cassandra root
chown -R root:cassandra /var/lib/cassandra/
chown -R root:cassandra /var/log/cassandra/
chmod 777 /var/lib/cassandra/data/
chmod 777 /var/lib/cassandra/saved_caches/
chmod 777 /var/lib/cassandra/commitlog/
chmod 770 /var/log/cassandra/log/
mkdir /var/lib/cassandra/logs
chown $usr:cassandra *  
echo "log4j.appender.R.file=/var/lib/cassandra/log/system.log" >> /var/lib/cassandra/conf/log4j-server.properties

2.  Manually modify cassandra.yaml.  Run this:

sudo vi /var/lib/cassandra/conf/cassandra.yaml

Uncomment these four stanzas; there should be no leading space either (space on far left) for the data... committ... and saved... lines. (There can be a space with the "- /var/lib"...)

data_file_directories:
   - /var/lib/cassandra/data

commitlog_directory: /var/lib/cassandra/commitlog

saved_caches_directory: /var/lib/cassandra/saved_caches

Comment out this stanza:

cluster_name: 'Test Cluster'

It will look like this when you are done:

#cluster_name: 'Test Cluster'

Save the changes (with "ZZ").

3.  Run these two commands:

cd /var/lib/cassandra
sudo /usr/local/apache-ant/bin/ant
# "sudo ant release" with no quotes may be necessary

Ignore the output about eclipse-warnings such as "Potential resource leak" or
"[java] 4 problems (4 errors)" or "BUILD FAILED /var/lib/cassandra/build.xml:1820: Java returned: 255."

4.a.  Make sure your user has the ability to write to /var/lib/cassandra/logs/
You may want to run this: sudo chown jdoe /var/lib/cassandra/logs #replace "jdoe" with the user that will start the Cassandra service

4.b. Run "hostname". Make sure the output is associated with 127.0.0.1 in /etc/hosts

4.c. Run these commands:  

screen
./bin/cassandra

4.d. Hold control and tap "a" and then "d".  (Ctrl-a, Ctrl-d.) Now go to step #5. (If you did not install screen or run the screen command, create a duplicate terminal session and skip to step #5 without doing step 4.d.)

5.  Wait 30 seconds, and then run these two commands:  

cd /var/lib/cassandra
./bin/cqlsh

How Do You Write a PHP Web Page That Asks for a SQL Table Name Then Returns the Contents after the User Clicks a Button?

Problem scenario
You want users to be able to enter a table name and then see the content of the table.  How do you create a webpage with a text field and a submit button that will display the content of the table if it exists?

Solution
Overview
This assumes you have the LAPP stack set up on a single server.  To set up the LAPP stack on Ubuntu, run this command without quotes: "sudo apt-get -y install php5 apache2-bin postgresql postgresql-contrib ​php-pgsql"

This example below challenges the users for Postgres credentials via the web page.  You could hard code a username and password in the viewer1.php page.  You could also leave out the fields for a username and password in the first web page (login1.php).  Then the web page would allow for anonymous users to browse to the site and enter a table name.  The database is hard-coded in viewer1.php, but you could change these two files to work with a database that the user enters.

Warning:  This is not secure against SQL injection. This is for informational purposes only.  This could be done in a secure, development environment or laboratory.

1.  In /var/www/html/ create a file named login1.php.  Have this be the contents:

<html>
<body>
<h2> Want to see a table?  Enter your credentials and the table name.</h2>
<form action="viewer1.php" method="post">
UserName: <input type="text" name="username"><br>
Password: <input type="password" name="password"><br>
TableToView: <input type="text" name="table"<br>
<input type="submit">
</form>

</body>
</html>

2.  In /var/www/html/ create a file named viewer1.php.  Replace "circle" below, but otherwise use the following as the contents:

<?php
   $part1 = $_POST["username"];
   $part2 = $_POST["password"];
   $part3 = $_POST["table"];
   $comp = 'user='.$part1.' password='.$part2 ;
   $host        = "host=127.0.0.1";
   $port        = "port=5432";
   $dbname      = "dbname=circle";
   $credentials = $comp;
   $db = pg_connect( "$host $port $dbname $credentials"  );
   $query = 'select * from ' . $part3 . ';';
   $cc = pg_query($query);
/* This code below was copied from http://razorsql.com/articles/postgresql_column_names_values.html  It was modified somewhat.*/
$i = 0;
echo '<html><body><table><tr>';
while ($i < pg_num_fields($cc))
{
        $fieldName = pg_field_name($cc, $i);
        echo '<td>' . $fieldName . '</td>';
        $i = $i + 1;
}
echo '</tr>';
$i = 0;

while ($row = pg_fetch_row($cc))
{
        echo '<tr>';
        $count = count($row);
        $y = 0;
        while ($y < $count)
        {
                $c_row = current($row);
                echo '<td>' . $c_row . '</td>';
                next($row);
                $y = $y + 1;
        }
        echo '</tr>';
        $i = $i + 1;
   }

pg_free_result($cc);
echo '</table></body></html>';
?>

3.  Go to a web browser.  Go to http://x.x.x.x/login1.php.  Enter the credentials and the table name of the database you want to see.

How Do You Optimize Data Warehouse Performance?

Problem scenario
You have a data warehouse that has not been performing as well as you would like.  What are some things that you can do to optimize the performance?

Solution
1.  Schedule processes such as back ups or ETL jobs at different times from hours of peak demand.  Rebuilding indexes can be a good idea or a bad one depending on when it is performed.  Be mindful of when statistics (meta data related to database transactions) are updated.  Transactions to a database involve locks.  In memory constrained situations, granular cells in tables cannot be locked so an "lock escalation" happens.  This involves more rows or even entire tables being locked and inoperable by other processes.  For a primer on avoiding database lock contention, see this external article.

It may make sense to have a time window for certain batch processing to take place.  Ad hoc tasks can happen inside or outside certain windows.

2.  Use indexes that are neither too complex nor too simple. Some indexes in an effort to make them "covered" (hold each row that a given query needs) become too complex for the associated queries.  Queries are not as fast as they otherwise would be.  The indexes should be made for the most demanding (e.g., frequent) queries.  This may mean creating a composite key for the uniqueness of the key.  If the indexes are general purpose, ensure the key is on a unique row.  Data warehouses are usually not subject to regular OLTP activity.  So they are good candidates for indexes.

3.  Ensure that where clauses filter out unnecessary rows.  Some analytical processing does not need to fetch any more rows than a few.  This is obvious, but before investing large amounts of money in optimization, it is worth mentioning.  There can be greater atomicity between queries when greater filtering is performed.

4.  Model the data in a way that makes sense.  Redesigning table schemas is not a small task.  Remember that for data warehouses, depending on how much analysis and ETL activity there is, you should normalize and denormalize as appropriate.  Some tables perform better with reads if they are denormalized.  OLAP presentations can do well with unnecessary tables (e.g., those that are redundant) that are denormalized.  Analysis can use the entire table.  This can make analytical development easier too.  But creating tables with redundant data can add to the disk space.   Normalization is useful if there are many different types of analysis.  OLAP queries may not cause disk contention if they draw data from different tables that are mutually exclusive.  Avoiding concurrency problems is key.  Some data warehouses span multiple disks and thus highly normalized tables are more likely to quickly support independent queries simultaneously.

5.  Use data types that are appropriate and no larger than they need to be.  While some data types or covariant (compatible) with another or contravariant (not compatible), for performance reasons, it is best to be consistent with data types for evaluation and comparison purposes.  "Mixing different data types can cause performance problems, and even if it doesn’t, implicit type conversions during comparisons can create hard-to-find errors. " taken from this external site.

SQL Server 2008 introduced a data type called datetime2.  This was strictly smaller on the disk compared to the previous data type called datatype.  Surprisingly datetime2 could hold greater accuracy of subseconds.  Some database tables use suboptimal data types for the columns because they started as a proof-of-concept or prototype.  Analyze the data types and the business' requirements to accommodate no more than what is needed.  In other words for choosing a column's data type support the longest string that is required but no longer than that.  Find the most simple as possible numeric data type for the business' required level of precision.  Reads and writes to such a column will be faster than if you chose a data type that supported many decimals and negative values when you only needed positive integers.  This practice of choosing smaller (few characters in a string) and simpler data types will lead to the most efficient operations down the road.

6.  Use the NOT NULL constraint on columns when you can.  "It’s harder for MySQL to optimize queries that refer to nullable columns," taken from this external site.

7.  Adjust and possibly reduce the logging*. Some transactions are logged in such detail that the transactions slow things down.  Tools like Change Data Capture can be great, but not for sheer speed.  Transaction logging is more complex than "either a SQL statement is logged or not."  TRUNCATE is not logged the same was as DELETE.  You can eliminate all the rows in a table quickly with the TRUNCATE command.  To learn about the differences between DELETE and TRUNCATE as people find TRUNCATE to be faster, see this external posting. 

DDL commands can be logged.  You may want to determine if this is necessary.  We recommend  keeping logging settings the same in all environments (from development to production) because parity in the development pipeline is important.

8.  Reconfigure the underlying storage RAID that supports the data warehouse.  Sometimes  redundancy is not necessary given the transaction logging*.  Disk controllers and disk writing algorithms can be bottlenecks for importing data in the warehouse.

9.  Convert the underlying file system to something that is more minimalistic and fast.  Journaled file systems do their own transaction logging.  This is not necessary if the transaction logging the database does is on a different hard disk from the actual database or data warehouse itself.  The closer to bare metal you place the data warehouse on, the greater speed the I/O activity will be.

10.  Leverage views.  These can provide all the rows that a given query or group of queries will need.  Views exist in memory, so they are fast.  This can free up the disk to serve other I/O activity.

11.  Consider upgrading the database engine.  As new versions of databases are released, the database engines can be perform much faster.

12.  Consider using data compression.  This can enhance reads and writes.  It may be appropriate for a data warehouse.  Not every database can supports compression.  This can also reduce the footprint on the disk too.

13.  Real-time replication of the data warehouse may be unnecessary.  Regularly scheduled back ups may be enough.  Sometimes data warehouses are an after-thought and combined with OLTP databases on a given instance.  Depending on your business' needs, replicating other databases may make sense but the data warehouse could be spared.  On the other hand, you want want to balance a load by having a highly-available data warehouse solution in different geographic locations.

14.  Rewrite SQL queries and remember big O notation.  Some SQL statements use O (n^2) computational complexity.  If you do not know what this is, do two things: One, make sure your SQL statements to not do more comparisons and intermediate processing than absolutely necessary.  Two, consider worst case scenarios where large numbers of rows are returned and then compared.  You may need to rewrite logic to reduce the number of rows being compared or manipulated.  Some I.T. professionals prefer to process data with a high level programming language and use databases and data warehouses as basic data store.  If your SQL statements do the processing themselves, you may want to analyze your SQL code carefully.  It may make sense to use Java or Python for the data processing instead of SQL.  If you must stick with rewriting SQL statements, which can be faster than using a traditional, high level programming language, you may want to read this external guide to identifying which SQL statements you will target in your optimization process.

15.  Can data warehouse operations be performed in-memory?  In-memory databases are becoming more common.  Some public clouds have RAM that is available at a low price.  Memory input and output is faster than disk input and output.

16.  Most databases support various types of prioritization.  Designations called "degree of parallelism" specify a dedicated number of CPUs for a process.  Database engines can take hints which can remove a SQL statement from the native optimizer leading to undesirable results.  This is related to scheduling of back ups and reindexing.  But it is a different process altogether.
The trade-offs in prioritizing can be more clear than other optimization techniques.  Keep a global perspective if you are not the only administrator.

17.  Be aware of what is cached and what is not cached in a database.  See this external link about Postgres caching if you have time.  The cache behavior will vary from database system to database system.  Manually manipulating what is cached can help you.  But keep a global perspective as some processes automatically cached and predicted by increasingly sophisticated tools with every new generation of database version.  

*** It is highly recommended to analyze the queries and use other methods above before making hardware upgrades.  ***

18.  Optimize your network.  Using multiple NICs and multiple network paths (through cabling and routers) for the data warehouse server.  This can ensure that there is no TCP/IP bottleneck.  TCP/IP network collisions degrade the performance of a network.  Spikes in bandwidth attributable to business activity or DDoS attacks can leave you susceptible to reduced performance.  You may want to analyze your entire network for optimal performance and reliability.

19.a.  Add more RAM or use faster RAM (with a higher bus speed).  Available memory has a way of getting consumed.  This can enable you to use in-memory databases or keep operations from paging or swapping (writing to disk via virtual memory).  
19.b. In some cases you have enough disk space to warrant increasing the virtual memory at your disposal. To increase the swap space of the operating system, see this link.

20.  Upgrade the CPUs to have more cores, faster speeds (higher GHz), larger caches and faster caches (e.g., L2 instead of L3). If you can afford the higher costs, click here if your data warehouse is running on a server in AWS or click here if the server is in GCP.

21.  Migrate to a faster storage device (e.g., some SANs and NASes perform better than others).

22. From a pragmatic perspective, many SQL databases include data warehouses. If you want advice on optimizing a SQL database, see this posting.

23. At the OS level if you are running Linux, you may want to enable hugepages.

*  SQL Server has Transaction Logs, Oracle Databases have Redo Logs, Postgres has Write-Ahead-Logs, and MariaDB has binary logs.  To learn more about transaction logging, see this Wikipedia article.