List of Experiments
List of Experiments
AIM:
To learn and develop applications using gcc and make.
PROGRAM:
Hello, world!
--------------
#include <stdio.h>
int main(int argc, char **argv)
{
printf("%s\n", "Hello, world!");
return 0;
}
compilation:
- compile, link, and execute:
gcc hello.c
./a.out
- compile:
gcc -c hello.c
or
gcc -g -Wall -c hello.c
- link:
gcc hello.o
or
gcc -g hello.o -o hello
- link multiple files and library:
gcc -g myfile1.o myfile2.o -lm -o myprogram
Pre-processing:
- Part of compilation
- Process lines that begin with ’#’
- Can be invoked separately with cpp or gcc –E
Function definition:
- return type
- argument list
- function body
- functions can only be at the top level (file scope)
main()
- The only function that a C program will execute
- Other functions can be called from main()
Using multiple functions
Example:
int add(int x, int y);
int main(int argc, char **argv)
{
int sum;
sum = add(1, 2);
printf("%d\n", sum);
return 0;
}
int add(int x, int y)
{
return x + y;
}
Function declaration:
Also called a prototype
A function must have been seen before it’s called
Enables compiler to do type-checking
Using multiple files:
Example:
- myadd.h (called a header file):
#ifndef _MYADD_H_
#define _MYADD_H_
int add(int x, int y);
#endif
- myadd.c:
#include "myadd.h"
int add(int x, int y)
{
return x + y;
}
- main.c:
#include "myadd.h"
int main(int argc, char **argv)
{
...
}
Preprocessor directives:
- conditional compilation
#ifdef __unix__
printf("you are cool");
#else
printf("go away");
#endif
File inclusion
#include <stdio.h>
#include "myadd.h"
- macros
#define PI 3.14
- just a textual substitution - so be careful!
#define square(x) x * x // wrong!
Make file:
This Make file should be used as a template for future Make files.
It’s heavily commented, so hopefully you can understand what eachline does.
We’ll use gcc for C compilation and g++ for C++ compilation
CC = gcc
CXX = g++
# Let’s leave a place holder for additional include directories
INCLUDES =
# Compilation options:
# -g for debugging info and -Wall enables all warnings
CFLAGS = -g -Wall $(INCLUDES)
CXXFLAGS = -g -Wall $(INCLUDES)
# Linking options:
# -g for debugging info
LDFLAGS = -g
# List the libraries you need to link with in LDLIBS
# For example, use "-lm" for the math library
LDLIBS =
# The 1st target gets built when you type "make".
# It’s usually your executable. ("main" in this case.)
#
# Note that we did not specify the linking rule.
# Instead, we rely on one of make’s implicit rules:
#
# $(CC) $(LDFLAGS) <all-dependent-.o-files> $(LDLIBS)
#
# Also note that make assumes that main depends on main.o,
# so we can omit it if we want to.
main: main.o myadd.o
# main.o depends not only on main.c, but also on myadd.h because
# main.c includes myadd.h. main.o will get recompiled if either
# main.c or myadd.h get modified.
#
# make already knows main.o depends on main.c, so we can omit main.c
# in the dependency list if we want to.
#
# make uses the following implicit rule to compile a .c file into a .o
# file:
#
# $(CC) -c $(CFLAGS) <the-.c-file>
#
main.o: main.c myadd.h
# And myadd.o depends on myadd.c and myadd.h.
myadd.o: myadd.c myadd.h
# Always provide the "clean" target that removes intermediate files.
# What you remove depend on your choice of coding tools
# (different editors generate different backup files for example).
#
# And the "clean" target is not a file name, so we tell make that
# it’s a "phony" target.
.PHONY: clean
clean:
rm -f *.o a.out core main
# "all" target is useful if your Makefile builds multiple programs.
# Here we’ll have it first do "clean", and rebuild the main target.
.PHONY: all
all: clean main
RESULT:
Thus, the program to learn and develop applications using gcc and make is completed and executed
successfully.
Ex. No:02
Use version control systems command to clone, commit,
Date:
push, fetch, pull, checkout, reset, and delete repositories
AIM:
Use version control systems command to clone, commit, push, fetch, pull, checkout, reset, and delete
repositories.
FUNCTIONAL DIAGRAM:
COMMANDS:
The commands are,
Clone
Commit
Push
Fetch
Pull
Checkout
Reset
Delete
Clone:
The git clone command is used to create a copy of a specific repository or branch within a repository.
Git is a distributed version control system. Maximize the advantages of a full repository on your own
machine by cloning.
Syntax:
git clone https://github.com/github/training-kit.git
Commit:
git commit creates a commit, which is like a snapshot of your repository. These commits are snapshots
of your entire repository at specific times. You should make new commits often, based around logical
units of change. Over time, commits should tell a story of the history of your repository and how it
came to be the way that it currently is. Commits include lots of metadata in addition to the contents
and message, like the author, timestamp, and more.
Syntax:
git commit -m "update the README.md with link to contributing guide"
Push:
git push updates the remote branch with local commits. It is one of the four commands in Git that
prompts interaction with the remote repository. You can also think of git pushas update or publish.
Syntax:
git push -u origin main
Pull:
git pull is one of the 4 remote operations within Git. Without running git pull, your local repository
will never be updated with changes from the remote. git pull should be used every day you interact
with a repository with a remote, at the minimum. That's why git pull is one of the most used Git
commands.
Syntax:
# General format
git pull OPTIONS REPOSITORY REFSPEC
Checkout:
Use git checkout on the command line to create a new branch, change your current working branch to
a different branch, or even to switch to a different version of a file from a different branch with git
checkout [branchname] [path to file]. The "checkout" action updates all or part of the working tree
with a tree object or blob from the object database, and updates the index and HEAD if the whole
working tree is pointing to a new branch.
Syntax:
git checkout [branch name] [path to file]
Reset:
The term reset stands for undoing changes. The git reset command is used to reset the changes. The git
reset command has three core forms of invocation. These forms are as follows.
Soft
Mixed
Hard
Syntax:
git reset <option> <commit-sha>
Delete:
It is common for a Git repo to have different branches. They are a great way to work on different features and
fixes while isolating the new code from the main codebase.
Repos often have a master branch for the main codebase and developers create other branches to work on
different features.
Syntax:
// delete branch locally
RESULT:
Thus, the program is to use version control systems command to clone, commit, push, fetch, pull,
checkout, reset, and delete repositories.
Ex. No:03
BUILDING MODULAR PROGRAMMING USING MAKE
Date:
AIM:
To use gcc to compile c-programs. Split the programs to different modules and create an application
using make command.
PROCEDURE:
A Monolithic Program
Consider this monolithic program Monolithic.c
Placing the code into one source file has a number of shortcomings:
It doesn't reflect the modularity of the design.
There is no clear separation of the ADT from each other and the main program.
There is no information hiding.
The main program contains details of the Person Type representation which it doesn't need to know.
It doesn't scale. Storing a large program as a single file produces large files that are hard to navigate.
Every time we make a change to one part, we are forced to recompile the whole program.
The mechanisms that enable us to reflect modularity in our code are
Interface and implementation and separate compilation.
Interface and Implementation
A module's interface is a description of the data and functions that are visible to code external to the
module. These descriptions are usually just the type signatures of the externally visible data and
functions.
A module's implementation comprises the data structures and code that make the module work.
Separating the interface from the implementation is the way we reflect abstraction.
When we use a module, we need to know only what effects accessing the data and routines in its
interface will have and we can ignore the details of how the module is implemented.
A Modular Program
We can split the code above into 4 files as follows:
CString.h- defines the C Stringtype
Person.h- defines the PersonTypetype
PrettyPrint.h-defines the PRETTY_PRINT macro
Person.c-implements the person manipulation
Modular.c - mainprogram
This separates the interface of the ADT from the implementation.
The files can all be compiled together
gcc -o Modular Modular.cPerson.c
The "declare before main, define afterwards " style of programming makes the split easy to do later.
Compare these two...
ProgramStructure.c
ProgramStructure2.c
Separate Compilation
Separating the interface from the implementation means compiling multiple small files, and some code
is compiled multiple times.
Some files need not be recompiled when changes are made.
The UNIX commands to compile and link separately are
gcc -c Source.c to compile
gcc-oExecutableObject1.oObject2.o...to link
For the example above...these are the file dependencies
The compiler has some options that support multi-file program development.
Make
Large programs broken up may use many object and library files
Changing a source file means updating the objects, libraries and executables that depend on the source
file.
The UNIX make utility keeps track of such dependencies, and recreates only the dependant files.
To determine which source files are part of the target to be built, and which tools to use to build the
target, make use a file called Make file in the current directory.
A simple Make file for the modular program
Lines starting with a # are comments
A Make file is a sequence of rules in the form
Target: dependencies action
Note that action must be preceded by a tab character; this is a historical artifact that no one has
bothered to fix.
Actions are just standard UNIX commands that are fed to a shell
If a dependency does not have a target entry, it is expected to exist as a result of external activity,
e.g.,editing
Make files are processed from the top down, trying to create a target.
By default the first target is used, but any target can be specified on the command line.
make(Target) {
foreach Dependency do {
if (IsATarget(Dependency))
{ make(Dependency)
}
}
if(!FileExists(Target)||AnyNewer(Dependencies,Target))
{ DoActions(Target)
}
}
Make variables can hold values like environment variables. make automatically sets the value of
certain variables like $@. Variables of this include:
$@The file name of the target of the rule.
$<The name of the first dependency.
$^The names of all the dependencies with spaces between them.
$?The list of dependencies that are out of date.
Make has rules that it applies by default, specified
in/usr/share/lib/make/make.rules. For example, make knows that to get from a. cfiletoa.ofile, it must
run the C compiler with the-c flag.
Make file using defaults
In addition to targets that build programs, make can be made to perform other house keeping by
specifying targets that are not necessarily programs. For example, a common target is
clean:
rm -f *.o *.bak*~
Which causes make to delete object files and any backup files(*.bak and*~) created by other programs such as
editors.
Make depend or mk dep
Examines each of the source files in its command line and looks for #includedirectives.
Generates a list of source files that are needed by the compiler to produce the resulting target.
Result is placed in. depend(FreeBSD) or appended to make file(Linux)
A more realistic Make file for the example
Creating a library.o files can be combined into libraries using the utility.
Library files are given a .a extension.
The object files can be used by the compiler by specifying the location of the library file with the-Lflag, and giving
the library file name.
Example
prompt> gcc -c*.c
prompt>ar-rvlibmystuff.a*.o
prompt>pwd
/home/geoff/c
prompt>gccMyMain.c-L/home/geoff/c-lmystuff-oMyMain
Exercises
Below is the content of a Make file. Assume that the files part1.c and part3.c have just been modified.
Write down the sequence of command activations in the correct order when make is run.
all: part1.o part2.o
gcc part1.o part2.o -o whole
part1.o: part1.c part3.o
gcc -c part1.c
gcc part1.o part3.o -o part3.out
part2.o: part2.c
gcc -c part2.c
part3.o: part3.c
gcc -c part3.c
PROGRAM:
Monolithic.c
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#defineMAX_CSTRING128
typedefcharCString[MAX_CSTRING];
typedefstruct{
CStringFamilyName;
CStringGivenName;
}PersonType;
#definePRETTY_PRINT(This)printf("\n----------------\n%s\n \n",(This)
voidSetNames(CStringNewFamilyName,CStringNewGivenName,PersonType*APerson){
strcpy(APerson->FamilyName,NewFamilyName);
strcpy(APerson->GivenName,NewGivenName);
}
//
voidGetFullName(PersonTypeAPerson,CStringFullName)
{
strcpy(FullName,APerson.GivenName);
strcat(FullName,"");
strcat(FullName,APerson.FamilyName);
}
//
intmain(void){
PersonTypeMyPerson;
CString;
InputFamilyName;
CStringInputGivenName;
CStringFullName;
CStringOutputLine;
printf("Pleaseenterthegivennameandfamilyname:
");
scanf("%s%s",InputGivenName,InputFamilyName);
SetNames(InputFamilyName,InputGivenName,&MyPerson);
GetFullName(MyPerson,FullName);
printf(OutputLine,"Thefullnameis%s",FullName);
PRETTY_PRINT(OutputLine);
return(EXIT_SUCCESS);
}
//
CString.h
#ifndefCSTRING_H
#define
CSTRING_H
//
#defineMAX_CSTRING128
typedefcharCString[MAX_CSTRING];
#endif
Person.h
#ifndefPERSON_H
#definePERSON_H
#include"CString.h"
typedefstruct{
CStringFamilyName;
CStringGivenName;
}PersonType;
//
voidSetNames(CStringNewFamilyName,CStringNewGivenName,PersonType*APerson);
voidGetFullName(PersonTypeAPerson,CStringFullName);
//
#endif
\
PrettyPrint.h
#ifndefPRETTYPRINT_H
#define
PRETTYPRINT_H
//
#definePRETTY_PRINT(This)printf("\n----------------\n%s\n \n",(This))
//
#endif
Person.c
//
#include<string.h>
#include"CString.h"
#include"Person.h"
voidSetNames(CStringNewFamilyName,CStringNewGivenName,PersonType*APerson){
// Comment
strcpy(APerson
->FamilyName, NewFamilyName);
strcpy(APerson
->GivenName, NewGivenName);
}
//
voidGetFullName(PersonTypeAPerson,CStringFullName)
{
strcpy(FullName,APerson.GivenName);
strcat(FullName,"");
strcat(FullName,APerson.FamilyName);
}
//
Modular.c
//
#include<stdio.h>
#include<stdlib.h>
#include"CString.h"
#include"Person.h"
#include
"PrettyPrint.h"
//
intmain(void){
PersonTypeMyPerson;
CString
InputFamilyName;
CStringInputGivenName;
CStringFullName;
CStringOutputLine;
printf("Please enter the given name and family name:");
scanf("%s%s",InputGivenName,InputFamilyName);
SetNames(InputFamilyName,InputGivenName,&MyPerson);
GetFullName(MyPerson,FullName);
sprintf(OutputLine,"Thefullnameis%s",FullName);
PRETTY_PRINT(OutputLine);
return(EXIT_SUCCESS);
}
//
RESULT:
Thus, the program use make command executed and answer is verified.
Ex. No:04
INSTALLING VIRTUAL BOX/VMWARE WITH
DIFFERENT FLAVORS OF OPERATING SYSTEMS
Date:
AIM:
To Install Virtualbox/VMware workstation with different flavors of linux or
windows OS and deploy the same on it.
PROCEDURE:
For Installing a VMwareworkstation this is the direct link to download
https://www.vmware.com/go/getplayer-win
Lets get the process Started.
Start the installer by double clicking it. You might see User Account Control Warning. Click Yes to
continue.
Then, you will see a splash screen. It will prepare the system for installation and
then the installation wizard opens.
Then, you will see a splash screen. It will prepare the system for installation and then the installation
wizard opens.
Click next and accept the license terms and click next again to move on to the next screen.
Step 2 – Custom setup – Enhanced Keyboard driver and Installation directory
In this dialog box, please select the folder in which you want to install the application. I leave it as it is. Also
check the box Enhanced Keyboard Drivers option. Click next.
Step 3 – User Experience Settings
Check the options for Check the product update at Startup and Join the VMware Customer Program. I
normally leave it as it is. You can uncheck it if you so desire. Click next
After sometime, you will see installation compete message. You are done. Click on Finish to complete the
installation.
You will be asked to restart your system. Click on Yes to restart. Click No, if you want to restart later. But
you must restart before using the application, else some features will not work properly.
Step 6 – License
Now Run the application. You should see a desktop icon. Double click on that or use the start menu to
navigate to VMware Player option. Once you run the application for the first time, you will be asked for
licence. Select the option Use VMware Workstation Player 15 for free for non-commercial use.
Click continue.
Creating a New VM
In order to create a new virtual machine for installing Ubuntu on VirtualBox, open VirtualBox and click
New (Machine > New) or press Ctrl+N.
In the Create Virtual Machine screen, set the options for a new VM. In our example of installing Ubuntu on
VirtualBox, the new VM options are the following:
Name: Ubuntu18x64
Machine Folder: C:\Virtual\VirtualBox (try to use disk D, E or other non-system partitions if you have
them).
Type: Linux
Version: Ubuntu (64-bit)
Memory size: Set at least 1 GB of RAM. As our physical machine used in this example has 16 GB of RAM,
we can set 4 GB of RAM for a virtual machine to install Ubuntu on VirtualBox. You should leave enough
memory for your host operating system to operate normally.
Select the Create a virtual hard disk now option. Hit Create to continue.
On the next Create Virtual Hard Disk screen, set the virtual disk file location, for example,
C:\Virtual\VirtualBox\Ubuntu18x64\Ubuntu18x64.vdi
The file size of the virtual disk: 20 GB or more.
Hard disk file type: VDI (VirtualBox Disk Image). Let’s select the native VirtualBox virtual disk format.
Storage on physical hard disk: Dynamically allocated. This option allows you to save space on your physical
disk until the virtual disk grows to its maximum allocated size.
Hit Create to finish creating a new VM to install Ubuntu on VirtualBox.
VM Configuration
A new virtual machine to install Ubuntu on Virtual Box has now been created and its name is displayed
in the list of VMs in the main VirtualBox window. You need to edit VM settings after VM creation.
Select your new VM (Ubuntu18x64 in this case) and click Settings (Machine > Settings or press
Ctrl+S).
In the Settings window, go to the Display section and select the Screen tab. Set video memory to 128
MB. Otherwise, the Ubuntu installer may hang on some installation steps, keyboard may not response
etc. You can enable 3D acceleration.
Hit OK to save settings.
Select the Boot Disk Image
You don’t need to burn the ISO image onto a DVD disk as you would for installing an operating system on
a physical machine. You can mount the ISO image to the virtual DVD drive of the virtual machine and boot
a VM from this media. Let’s insert the ubuntu-18.04.2- desktop-amd64. Iso image that was downloaded
from the official Ubuntu website before, into a virtual DVD drive of the Ubuntu18x64 VM. Open your
VM settings and go to the Storage section. Select your virtual controller used for connecting a virtual
DVD drive (by default a virtual DVD drive is empty). Click the Empty status and in the right pane near the
IDE Secondary Master, click the disc icon. In the menu that appears, click Choose Virtual Optical Disk
File and browse your Ubuntu installation ISO image file (ubuntu-18.04.2- desktop-amd64.iso).
Hit OK to save settings. Now your VM is ready to install Ubuntu on VirtualBox.
Install Ubuntu on VirtualBox VMs
Once the new VM is prepared for installing Ubuntu on Virtual Box, start the VM(Machine> Start). The VM
boots from the ISO Ubuntu installation image. The first screen that you can see after booting is the Welcome
screen.
In the left pane select Language for displaying information in the installer interface. English is selected in the
current example. Then click Install Ubuntu.
Keyboard layout. Choose your keyboard layout. Let’s select English (US).
Updates and other software. There are a few options to choose from on this screen. Normal installation. A
web browser, utilities, office applications and media players are installed.
Minimal installation. Only the main components including a web browser and basic utilities are installed.
Let’s select the normal installation. Other options:
Download updates while installing Ubuntu. The Ubuntu team is always working towards making Linux
better. That’s why after downloading the installer, some updates may be already available. You can
automatically download and install updates right during Ubuntu installation, letting you save time after OS
installation. Let’s select this option.
Install third-party software for graphics and Wi-Fi hardware and additional media formats. Tick this
check box if you would like to install additional software, such as proprietary Wi-Fi drivers, video drivers,
some TTF fonts etc.
Installation type. This screen contains options for preparing a disk for Ubuntu installation. Erased
disk and install Ubuntu. This is the default option. All disk space will be automatically allocated to
Ubuntu. If you select Erase disk and install Ubuntu on VirtualBox VMs, one big /dev/sda1 partition
is created on /dev/sda. This /dev/sda1 partition with ext4 file system is mounted to the / directory
(root directory), though a separate swap partition is not created. Attention: All data on the virtual disk
will be erased—there is no reason to worry about it, however, because an empty virtual disk created
previously is being used for installing Ubuntu on VirtualBox.
There are some additional options:
Encrypt the new Ubuntu installation for security.
Use LVM (Logical Volume Management) with the new Ubuntu installation.
Something else. Use this option for manual creation of the partition table on your virtual disk which is
used to install Ubuntu on VirtualBox.
Click Install Now when you are ready to continue. Then on the confirmation screen, hit Continue.
Where are you? Select your location to set the time zone and regional settings. The time for your selected
region will be set automatically. Let’s select London.
Enter your user name, computer’s name, and set the password. Select Require my password to log in for a
higher level of security. In our example, the username is user1 and the computer’s name is ubuntu18-vm.
As you can see, useful tips are displayed on the screen during the installation process.
When installation is complete, you will see a notification window. You have to restart your VM with
Ubuntu on VirtualBox.
Now you can eject the Ubuntu installation ISO disk from the virtual CD/DVD drive of the VM.
Installing VirtualBox Guest Additions
OnefinalstepislefttocompleteinstallingUbuntuonVirtualBox.Aftertheoperatingsystem reboot, install
VirtualBox Guest Additions, which is a set of drivers and system utilities intended to improve usability
and VM performance as well as tight integration with a host OS.
In the VM window, go to Devices and hit Insert Guest Additions CD image. The ISO disc image that is
located in the VirtualBox installation directory will be inserted into a virtual CD/DVD drive of the VM.
After that, you can see a CD shortcut on the Ubuntu Desktop. The ISO disk contains autorun, and the Guest
Additions installer can be started automatically. Just hit the Run button to start installing VirtualBox Guest
Additions.
If you get the warning message “Please install the gcc make perl packages”, it means that you have to
install these packages first and then install VirtualBox Guest Additions.
In order to install the necessary packages, execute the command:
sudo apt-get install build-essential gcc make perl dkms You may need to type admin credentials when
using sudo. After that, reboot your Ubuntu VM:
init 6
After restarting the VM, open Linux terminal and go to the directory of the virtual CD with Guest
Additions. In our case, the following command is used:
cd /media/user1/VBox_GAs_6.0.8/
Check the contents of the directory:
ls -al
Run the Linux installer of VirtualBox Guest Additions on your Ubuntu on VirtualBox manually:
sudo ./VBoxLinuxAdditions.run
When the installation process is finished, verify whether VirtualBox Guest Additions have been installed
successfully. Let’s check the appropriate kernel modules that are installed with Guest Additions:
lsmod | grep -I vbox
Check the module information:
modinfo vboxguest
You can check only version of VirtualBox Guest Additions:
lsmod | grep -io vboxguest | xargs modinfo | grep -iw version
Result:
Thus, the installation of Virtual machine and a flavor of Linux OS is completed.
Ex.No: 05
INSTALL A ‘C’ COMPILER IN A VIRTUAL MACHINE AND
Date: EXECUTE THE PROGRAMS
Aim:
Install a C Compiler in a virtual machine created using virtual box and execute the
programs.
Procedure:
Install a C Compiler
Upgrade
Installing gcc
sudo gedit first add the following lines save and exit the file
Result:
Thus, the installation of C compiler in Virtual machine and execution of simple program is completed.
Ex. No:06
Installing Google App Engine and creating Hello world App
Date:
AIM:
To install the Google App Engine Software Development Kit (SDK) on a Microsoft Windows and
running a simple “hello world” application.
PROCEDURE:
Pre-•Requisites: Python 2.5.4
If you don't already have Python 2.5.4 installed in your computer, download and Install Python 2.5.4 from:
http://www.python.org/download/releases/2.5.4/
Download the Windows installer – the simplest thing is to download it to your Desktop or another folder that
you remember.
Double Click on the Google Application Engine installer.
Click through the installation wizard, and it should install the App Engine. If you do not have Python 2.5, it
will install Python 2.5 as well. Once the install is complete you can discard the
downloaded installer
Application will start and the launcher will show a little green icon next to your application. Then press
Browse to open a browser pointing at your application which is running at http://localhost:8080/
Paste http://localhost:8080 into your browser and you should see your application as follows:
Just for fun, edit the index.py to change the name “Chuck” to your own name and press Refresh in the browser
to verify your updates.
Watching the Log
You can watch the internal log of the actions that the web server is performing when you are interacting with
your application in the browser. Select your application in the Launcher and press the Logs button to bring up
a log window:
Each time you press Refresh in your browser – you can see it retrieving the output with a GET request.
Dealing With Errors
With two files to edit, there are two general categories of errors that you may encounter. If you make a mistake
on the app.yaml file, the App Engine will not start and your launcher will show a yellow icon near your
application:
To get more detail on what is going wrong, take a look at the log for the application:
In this instance– the mistake is mis-‐indenting the last line in the app.yaml(line 8).
If you make a syntax error in the index.py file, a Python trace back error will appear in your browser.
The error you need to see is likely to be the last few lines of the output – in this case I made a Python syntax
error on line one of our one-‐line application.
Reference: http://en.wikipedia.org/wiki/Stack_trace
When you make a mistake in the app.yaml file – you must fix the mistake and attempt to start the application
again.
If you make a mistake in a file like index.py, you can simply fix the file and press refresh in your browser –
there is no need to restart the server.
Shutting Down the Server
To shut down the server, use the Launcher, select your application and press the
Stop button.
Alternate Method
Download and install CloudSDK:
Download the SDK
Note: If you already have the Cloud SDK installed, update it by running the following command:
Create a newproject:
Replace [YOUR_PROJECT_ID]with a string of charactersthat uniquely identifies your project. For example,
my-project-24.
Verify the project was created:
You see project details that might look like the following:
createTime: year-month-
hour lifecycleState: ACTIVE
name: project-name
parent:
id: '433637338589'
type: organization
projectId: project-name-id
projectNumber: 499227785679
Initialize your App Engine app with your project and choose itsregion:
gcloud app create --project=[YOUR_PROJECT_ID]
When prompted, select the regionwhere you want your App Engine applicationlocated.
Caution: You cannot change an app's region once it has been set.
Make sure billing is enabled for your project. A billing account needs to be linked to your project in order for
the application to be deployed to App Engine.
Enable billing
Note: Running this sample app does not exceed your free quota.
Install the following prerequisites:
Download and install Git.
Run the following command to install the gcloud component that includes the App Engine extension for
Python3:
Prepare your environment for Python development. It is recommended that you have the latest
version of Python, pip, and other related tools installed on your system. For instructions, refer to the
Python Development Environment Setup Guide.
This quick start demonstrates a simple Python app written with the Flask web framework that can be deployed
to App Engine. Although this sample uses Flask, you can use any web framework that satisfies the
requirements above. Alternative frameworks include Django, Pyramid, Bottle, andweb.py.
Download the Hello World app
We've created a simple Hello World app for Python 3 so you can quickly get a feel for deploying an app to the
Google Cloud.
Clone the Hello World sample app repository to your localmachine.
Alternatively, you can download the sampleas a zip file and extract it.
Change to the directory that contains the samplecode.
cd python-docs-samples/appengine/standard_python3/hello_world
cd YOUR_PROJECT
gcloud appdeploy
Learn about the optional flags.
Launch your browser to view the app athttps://PROJECT_ID.REGION_ID.r.appspot.com
gcloud app browse
where PROJECT_IDrepresents your Google Cloud project ID.
This time, the page that displays the Hello World message is delivered by a web server running on an App
Engine instance.
Congratulations! You've deployed your first Python 3 app to App Engine standard environment!
See the following sections for information about cleaning up as well as links to possible next steps that you
can take.
Clean up
To avoid incurring charges, you can delete your Cloud project to stop billing for all the resources used
within that project.
Caution: Deleting a project has the following effects:
Everything in the project is deleted. If you used an existing project for this tutorial, when you delete it, you
also delete any other work you've done in the project. Custom project IDs are lost. When you created this
project, you might have created a custom project ID that you want to use in the future. To preserve the
URLs that use the project ID, such as an appspot.com URL, delete selected resources inside the project
instead of deleting the whole project. In the Cloud Console, go to the Manage resources page. Go to the
Manage resources page. In the project list, select the project that you want to delete and then click Delete
delete. In the dialog, type the project ID and then click Shut down to delete the project.
Result:
Thus, the installation of Google cloud SDK on the system and creating the hello world app is
completed successfully.
Ex. No: 07
LAUNCHING WEB APPLICATIONS USING GAE LAUNCHER
Date:
AIM:
To host the website using Google Application Engine Launcher using Cloud SDK.
PROCEDURE:
STEP 1: Creating the Google Cloud Platform Project
Go to the App Engine dashboard on the Google Cloud Platform Console and press the Createbutton.
If you've not created a project before, you'll need to select whether you want to receive email updates or
not, agree to the Terms of Service, and then you should be able to continue.
Enter a name for the project, edit your project ID and note it down. For this tutorial, the following values are used:
cd sample-app
Youarenowreadytodeployyourapplication,i.e.uploadyourapptoAppEngine:
Enter a number to choose the region where you want your applicationlocated.
Enter Y toconfirm.
Nownavigateyourbrowsertoyour-project-id.appspot.comtoseeyourwebsiteonline.For example, for the
project ID gaesamplesite, go togaesamplesite.appspot.com.
RESULT:
Thus, the website was hosted using Google Application Engine Launcher successfully.
Ex.No:08 MODELING AND SIMULATION CLOUD COMPUTING
ENVIRONMENTS, INCLUDING DATA CENTERS, HOSTS AND
Date: CLOUDLETS AND PERFORM VM PROVISIONING USING CLOUDSIM
AIM:
To design a host with two CPU cores, which receives request for hosting two VMs, such that each
one requires two cores and plans to host four tasks units. More specifically, tasks t1, t2, t3andt4to be hosted
inVM1, while t5, t6, t7, and t8 to be hosted in VM2 and to implement space-shared allocation policy and
time-shared allocation policy.
PROCEDURE:
Steps:
The Above Problem Requires the Following
Eclipse IDE
CloudsimPackage
Note : In Case Eclipse IDE (any version is Installed) and configure it with Cloudsim Package
Step1:
Open the Eclipse IDE Create New JavaProject
Give Name As “CloudsimDemo” and Click Next
Goto Library and Click Add external Jars and
Step2:
Create New Class Called “First” And Write the Following JavaCode
This Java Code Consist For Creating DataCeenter , Data Center Broker ,VMs, Cloudlets
The Space Shared Policy IsUsed
First.java
importjava.io.File;
importjava.io.FileNotFoundException;
importjava.io.FileOutputStream;
importjava.io.IOException;
importjava.text.DecimalFormat;
importjava.util.ArrayList;
importjava.util.Calendar;
importjava.util.LinkedList;
importjava.util.List;
importjava.util.Random;
importorg.cloudbus.cloudsim.Cloudlet;
importorg.cloudbus.cloudsim.CloudletSchedulerTimeShared;
importorg.cloudbus.cloudsim.Datacenter;
importorg.cloudbus.cloudsim.DatacenterBroker;
importorg.cloudbus.cloudsim.DatacenterCharacteristics;
importorg.cloudbus.cloudsim.Host;
importorg.cloudbus.cloudsim.Log;
importorg.cloudbus.cloudsim.Pe;
importorg.cloudbus.cloudsim.Storage;
importorg.cloudbus.cloudsim.UtilizationModel;
importorg.cloudbus.cloudsim.UtilizationModelFull;
importorg.cloudbus.cloudsim.Vm;
importorg.cloudbus.cloudsim.VmAllocationPolicySimple;
importorg.cloudbus.cloudsim.VmSchedulerTimeShared;
importorg.cloudbus.cloudsim.core.CloudSim;
importorg.cloudbus.cloudsim.provisioners.BwProvisionerSimple;
importorg.cloudbus.cloudsim.provisioners.PeProvisionerSimple;
importorg.cloudbus.cloudsim.provisioners.RamProvisionerSimple;
public class First {
/** The cloudlet list. */
private static List<Cloudlet>cloudletList;
/** The vmlist. */
private static List<Vm>vmlist;
private static List<Vm>createVM(intuserId, intvms, intidShift) {
//Creates a container to store VMs. This list is passed to the broker later LinkedList<Vm> list = new
LinkedList<Vm>();
//VM Parameter
long size = 10000; //image size (MB) int ram = 512; //vm memory (MB) intmips = 250;
long bw = 1000;
intpesNumber = 1; //number of cpus String vmm = "Xen"; //VMM name
//create VMs
Vm[] vm = new Vm[vms];
for(inti=0;i<vms;i++){
vm[i] = new Vm(idShift + i, userId, mips, pesNumber, ram, bw, size, vmm, new
CloudletSchedulerSpaceShared());
list.add(vm[i]);
}
return list;
}
private static List<Cloudlet>createCloudlet(intuserId, int cloudlets, intidShift){
// Creates a container to store Cloudlets LinkedList<Cloudlet> list = new LinkedList<Cloudlet>();
//cloudlet parameters long length = 40000; long fileSize = 300; long outputSize = 300; intpesNumber
= 1;
UtilizationModelutilizationModel = new UtilizationModelFull();
Cloudlet[] cloudlet = new Cloudlet[cloudlets]; for(inti=0;i<cloudlets;i++){
cloudlet[i] = new Cloudlet(idShift + i, length, pesNumber, fileSize, outputSize, utilizationModel,
utilizationModel, utilizationModel);
// setting the owner of these Cloudlets
cloudlet[i].setUserId(userId); list.add(cloudlet[i]);
return list;
}
////////////////////////// STATIC METHODS ///////////////////////
/**
* Creates main() to run this example
*/
public static void main(String[] args) { Log.printLine("Starting Clouddemo...");
try {
// First step: Initialize the CloudSim package. It should be called
// before creating any entities. intnum_user = 2;
// number ofusers
Calendar calendar = Calendar.getInstance(); booleantrace_flag = false; // mean trace events
Open The Output File and Convert Text to Columns Plot. The Graph Time Versus Cloudlets.
Change the Time-shared policy to Space shared and obtain the graph and Compare the Results of the
Timeshared And Space Shared
RESULT:
Thus, the scheduling task in cloud sim is executed successfully.
TRANSFER VIRTUALBOX VIRTUAL MACHINES
Ex.No: 09 TOANOTHER HOST
Date:
AIM:
To transfer the VirtualBox's Virtual Machine(s) to another host without having
to perform the Import/Export Appliance procedure.
PROCEDURE:
Step-1: Copy the VM Storage Folder from the Old Host to the New Host. Close VirtualBox on
the old VirtualBox host computer. Then from the old host computer, copy the entire virtual
machine folder (which contains both the .vbox and the .vdi files), to the new VirtualBox host
computer.
Step-2: Add the VM Machines to the VirtualBox on the new Host. Install Virtual Box on the
new VirtualBox HostPC. Then, from the Machine menu, clickAdd.
From the Virtual Machine folder, select the .vbox file of the VM machine that you want to add
(import), in the new Host and click Open.
RESULT:
Thus, the transfer of virtual machine from one host to another host was successfully completed.
Ex. No:10
Launching Virtual Machine using Trystack
Date :
AIM:
To launch virtual machine using try stack in online.
PROCEDURE:
OpenStack is an open-source software cloud computing platform. OpenStack is primarily
used for deploying an infrastructure as a service (IaaS) solution like Amazon Web Service (AWS).
The instance will be connected to a local network and the local network will be connected to
internet.
Step 1: Create Network
Go to Network > Networks and then click Create Network. In Network tab, fill Network Name
for example internal and then click Next. In Subnettab, Fill Network Address with appropriate
CIDR, for example 192.168.1.0/24. Use private network CIDR block as the best practice. Select
IP Version with appropriate IP version, in this caseIPv4. Click Next.
In Subnet Details tab, fill DNS Name Servers with 8.8.8.8 (Google DNS) and then click Create.
Step 2: Create Instance
Go to Compute > Instances and then click LaunchInstance.
In Detailstab,
Fill Instance Name, for example Ubuntu1.
Select Flavor, for examplem1.medium.
Fill Instance Count with1.
Select Instance Boot Source with Boot fromImage.
Select Image Name with Ubuntu 14.04 amd64 (243.7 MB) if you want install Ubuntu 14.04 in
your virtual machine. In Access & Security tab,
Click [+] button of Key Pair to import key pair. This key pair is a public and private key that we
will use to connect to the instance from ourmachine.
In Import Key Pairdialog,
Fill Key Pair Name with your machine name (for exampleEdward-Key).
Fill Public Key with your SSH public key (usually is in ~/.ssh/id_rsa.pub). See description in
Import Key Pair dialog box for more information. If you are using Windows, you can use
Puttygen to generate keypair.
Click Import keypair.
In Security Groups, mark/checkdefault.
In Networking tab,
1. In Selected Networks, select network that have been created in Step 1, for example internal.
Click Launch.
If you want to create multiple instances, you can repeat step 1-5. I created one more instance with
instance name Ubuntu2.
Step 3: Create Router
To make our network has an internet connection, we need a router that running as the gateway
to the internet.
Go to Network > Routers and then click Create Router.
Fill Router Name for example router1 and then click Createrouter.
Click on your router name link, for example router1, Router Detailspage.
Click Set Gateway button in upperright:
Select External networks withexternal.
ThenOK.
5. Click Add Interface button.
Select Subnet with the network that you have been created in Step1.
Click Add interface.
6. Go to Network > Network Topology. You will see the network topology. In the example, there
are two network, i.e. external and internal, those are bridged by a router. There are instances
those are joined to internal network.
Step 4: Configure Floating IP Address
Floating IP address is public IP address. It makes your instance is accessible from the internet.
When you launch your instance, the instance will have a privatenetwork IP, but no public IP. In
OpenStack, the public IPs is collected in a pool and managed byadmin(inour
caseisTryStack).Youneedtorequestapublic(floating)IP address to be assigned to yourinstance.
Go to Compute >Instance.
In one of your instances, click More > Associate FloatingIP.
In IP Address, click Plus[+].
Select Pool to external and then click AllocateIP.
ClickAssociate.
Now you will get a public IP, e.g. 8.21.28.120, for yourinstance.
Step 5: Configure Access & Security
OpenStack has a feature like a firewall. It can whitelist/blacklist your in/out connection. It is
called Security Group.
Go to Compute > Access & Security and then open Security Groupstab.
In default row, click ManageRules.
Click Add Rule, choose ALL ICMP rule to enable ping into your instance, and then click Add.
Click Add Rule, choose HTTP rule to open HTTP port (port 80), and then clickAdd.
Click Add Rule, choose SSH rule to open SSH port (port 22), and then clickAdd.
You can open other ports by creating newrules.
Step 6: SSH to Your Instance
Now, you can SSH your instances to the floating IP address that you got in the step 4. If you are
using Ubuntu image, the SSH user will be ubuntu.
RESULT:
Thus, the creation of virtual machine using Trystack is successfully completed.
Ex. No:11 Install Single Node Hadoop Cluster and Execute the Word
Count Application
Date:
AIM:
To install the single node Hadoop cluster on the physical machine and execute
the word count application.
PROCEDURE:
Hadoop pseudo node setup created for following environment:
Ubuntu Linux 64-bit JDK 1.8.0_05
Hadoop 2.7.x stable release
Note: In this document we have used only compatible versions of Hadoop ecosystem tools or
software downloaded from the official Apache Hadoop website. Preferably use a stable release of the
particular tool.
Prerequisites:
Installing Java v1.8 2. Configuring SSH access.
sudo apt-get install vim
Installing Java:
Hadoop is a framework written in Java for running applications on large clusters of
commodity hardware. Hadoop needs Java 6 or above to work.
Step 1: Download Jdk tar.gz file for linux-62 bit, extract it into “/usr/local” boss@solaiv[]# cd /opt
boss@solaiv[]# sudo tar xvpzf /home/itadmin/Downloads/jdk-8u5-linux-
x64.tar.gz boss@solaiv[]# cd /opt/jdk1.8.0_05
Step 2:
Open the “/etc/profile” file and Add the following line as per the version set a environment for Java
Use the root user to save the /etc/proflie or use gedit instead of vi .
The 'profile' file contains commands that ought to be run for login shells boss@solaiv[]# sudo vi
/etc/profile
#--insert JAVA_HOME JAVA_HOME=/opt/jdk1.8.0_05
#--in PATH variable just append at the end of the line PATH=$PATH:$JAVA _HOME/bin #--
Append JAVA_HOME at end of the export
statement export PATH JAVA_HOME
save the file using by pressing “Esc” key followed by :wq!
Step 3:
Source the /etc/profile boss@solaiv[]# source/etc/profile
Step 4: Update the java alternatives
By default, OS will have a open jdk. Check by “java -version”. You will be prompt “openJDK”
If you also have openjdk installed then you'll need to update the java alternatives:
If your system has more than one version of Java, configure which one your system causes by
entering the following command in a terminal window
By default, OS will have a open jdk. Check by “java -version”. You will be prompt “Java
HotSpot(TM) 64-Bit Server”
boss@solaiv[]# update-alternatives --install "/usr/bin/java" java "/opt/jdk1.8.0_05/bin/java" 1
boss@solaiv[]# update- alternatives --config java --type selection number:
boss@solaiv[]# java –version
configuressh
Hadoop requires SSH access to manage its nodes ,i.e. remote machines plus your local machine if
you want to use Hadoop on it (which is what we want to do in this short tutorial). For our single-
node setup of Hadoop, we therefore need to configure SSH access to localhost. The need to create
a Password-less SSH Key generation based authentication is so that the master node can then login
to slave nodes (and the secondary node) to start/stop them easily without any delays for
authentication
If you skip this step, then have to provide password Generate an SSH key for the user. Then Enable
password-less SSH access to you
sudo apt-get install openssh-server
--You will be asked to enter password, root@solaiv[]# ssh localhost
root@solaiv[]# ssh-keygen root@solaiv[]# ssh-copy-id
-i localhost
--After above 2 steps, You will be connected without password, root@solaiv[]# ssh localhost
root@solaiv[]# exit
Hadoop installation
Now Download Hadoop from the official Apache, preferably a stable release version of Hadoop
2.7.x and extract the contents of the Hadoop package to a location of your choice.
We chose location as “/opt/”
Step 1: Download the tar.gz file of latest version Hadoop ( hadoop-2.7.x) from the official site .
Step 2: Extract(untar) the downloaded file from this commands to /opt/bigdata
root@solaiv[]# cd /opt
root@solaiv[/opt]# sudo tar xvpzf /home/itadmin/Downloads/hadoop- 2.7.0.tar.gz
root@solaiv[/opt]# cd hadoop-2.7.0/
Like java, update Hadop environment variable in /etc/profile boss@solaiv[]# sudo vi /etc/profile
#--insert HADOOP_PREFIX
HADOOP_PREFIX=/opt/ha doop-2.7.0
#--in PATH variable just append at the end of the line PATH=$PATH:$HADOOP_PREFIX/bin
#--Append HADOOP_PREFIX at end of the export statement export PATH JAVA_HOME
HADOOP_PREFIX
save the file using by pressing “Esc” key followed by :wq! Step 3: Sourcethe
/etc/profile boss@solaiv[]# source/etc/profile
Verify Hadoop installation boss@solaiv[]# cd $HADOOP_PREFIX boss@solaiv[]# bin/hadoop
version
Modify the Hadoop ConfigurationFiles
In this section, we will configure the directory where Hadoop will store its configuration files, the
network ports it listens to, etc. Our setup will use Hadoop Distributed File System,(HDFS), even
though we are using only a single local machine.
Add the following properties in the various hadoop configuration files which is available under
$HADOOP_PREFIX/etc/hadoop/
core-site.xml, hdfs-site.xml, mapred-site.xml & yarn-site.xml Update Java, hadoop path to the
Hadoop environment file
boss@solaiv[]# cd $HADOOP_PREFIX/etc/hadoop boss@solaiv[]# vi hadoop-env.sh
Paste following line at beginning of the file
export JAVA_HOME=/usr/local/jdk1.8.0_05 export HADOOP_PREFIX=/opt/hadoop-2.7.0
Modify the core-site.xml
boss@solaiv[]# cd $HADOOP_PREFIX/etc/hadoop boss@solaiv[]# vi core-site.xm
package PackageDemo{
import java.io.IOException;
import org.apache.hadoop.conf.Configuration; importorg.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.LongWritable;
importorg.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import
org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; import
org.apache.hadoop.util.GenericOptionsParser;
public class WordCount {
public static void main(String [] args) throws Exception
{
Configuration c=new Configuration();
String[] files=new GenericOptionsParser(c,args).getRemainingArgs(); Path input=new
Path(files[0]);
Path output=new Path(files[1]); Job j=new Job(c,"wordcount");
j.setJarByClass(WordCount.class);
j.setMapperClass(MapForWordCount.class);
j.setReducerClass(ReduceForWordCount.class);
j.setOutputKeyClass(Text.class);
j.setOutputValueClass(IntWritable.class);
FileInputFormat.addInputPath(j, input);
FileOutputFormat.setOutputPath(j, output);
System.exit(j.waitForCompletion(true)?0:1);
}
public static class MapForWordCount extends Mapper<LongWritable, Tex t, Text, IntWritable>
{
public void map(LongWritable key, Text value, Context con) throws IO Exception,
InterruptedException
{
String line = value.toString(); String[] words=line.split(","); for(String word: words )
{
Text outputKey = new Text(word.toUpperCase().trim()); IntWritable outputValue = new
IntWritable(1); con.write(outputKey, outputValue);
}
}
}
public static class ReduceForWordCount extends Reducer<Text, IntWrit able, Text, IntWritable>{
public void reduce(Text word, Iterable<IntWritable> values, Context con) throws IOException,
InterruptedException
{
int sum = 0;
for(IntWritable value : values)
{
sum += value.get();
}
con.write(word, new IntWritable(sum));
}
}
}
RESULT:
Thus, the installation of single node Hadoop cluster and executing the word count application is
successfully completed.