Skip to content

Commit

Permalink
clone
Browse files Browse the repository at this point in the history
  • Loading branch information
mrnazu committed Aug 5, 2023
0 parents commit b1aeaaa
Show file tree
Hide file tree
Showing 120 changed files with 5,132 additions and 0 deletions.
14 changes: 14 additions & 0 deletions 0-setup_web_static.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
#!/usr/bin/env bash
# Script using bash to setup webservers for deployment of simple HTML
# content

apt-get update && \
apt-get install -y nginx && \
mkdir -p -m=755 /data/web_static/{releases/test,shared} || exit 0
echo 'Testing 123' > /data/web_static/releases/test/index.html
ln -sf /data/web_static/releases/test/ /data/web_static/current
chown -hR ubuntu:ubuntu /data/
insert='\\tlocation /hbnb_static/ {\n\t\talias /data/web_static/current/;}'
sed -i "37i $insert" /etc/nginx/sites-available/default
service nginx restart
exit 0
28 changes: 28 additions & 0 deletions 1-pack_web_static.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
#!/usr/bin/python3
"""Generate .tgz file from the contents of the web_static folder"""

from fabric import api
from datetime import datetime
import os


def do_pack():
"""Function to create tarball of webstatic files from the web_static
folder in Airbnb_v2.
Returns: path of .tgz file on success, None otherwise
"""
with api.settings(warn_only=True):
isdir = os.path.isdir('versions')
if not isdir:
mkdir = api.local('mkdir versions')
if mkdir.failed:
return None
suffix = datetime.now().strftime('%Y%m%d%M%S')
path = 'versions/web_static_{}.tgz'.format(suffix)
tar = api.local('tar -cvzf {} web_static'.format(path))
if tar.failed:
return None
size = os.stat(path).st_size
print('web_static packed: {} -> {}Bytes'.format(path, size))
return path
43 changes: 43 additions & 0 deletions 2-do_deploy_web_static.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
#!/usr/bin/python3
"""Deploy an archive of static html to my web servers with Fabric3"""

from fabric import api
from fabric.contrib import files
import os


api.env.hosts = ['142.44.167.235', '144.217.246.199']
api.env.user = 'ubuntu'
api.env.key_filename = '~/.ssh/holberton'


def do_deploy(archive_path):
"""Function to transfer `archive_path` to web servers.
Args:
archive_path (str): path of the .tgz file to transfer
Returns: True on success, False otherwise.
"""
if not os.path.isfile(archive_path):
return False
with api.cd('/tmp'):
basename = os.path.basename(archive_path)
root, ext = os.path.splitext(basename)
outpath = '/data/web_static/releases/{}'.format(root)
try:
putpath = api.put(archive_path)
if files.exists(outpath):
api.run('rm -rdf {}'.format(outpath))
api.run('mkdir -p {}'.format(outpath))
api.run('tar -xzf {} -C {}'.format(putpath[0], outpath))
api.run('rm -f {}'.format(putpath[0]))
api.run('mv -u {}/web_static/* {}'.format(outpath, outpath))
api.run('rm -rf {}/web_static'.format(outpath))
api.run('rm -rf /data/web_static/current')
api.run('ln -sf {} /data/web_static/current'.format(outpath))
print('New version deployed!')
except:
return False
else:
return True
73 changes: 73 additions & 0 deletions 3-deploy_web_static.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
#!/usr/bin/python3
"""Tar, transfer, and deploy static html to webservers"""

from fabric import api, decorators
from fabric.contrib import files
from datetime import datetime
import os

api.env.hosts = ['holberton1', 'holberton3']
api.env.hosts = ['142.44.167.235', '144.217.246.199']
api.env.user = 'ubuntu'
api.env.key_filename = '~/.ssh/holberton'


def deploy():
"""Wrapper function to pack html files into tarball and transfer
to web servers."""
return do_deploy(do_pack())


@decorators.runs_once
def do_pack():
"""Function to create tarball of webstatic files from the web_static
folder in Airbnb_v2.
Returns: path of .tgz file on success, False otherwise
"""
with api.settings(warn_only=True):
isdir = os.path.isdir('versions')
if not isdir:
mkdir = api.local('mkdir versions')
if mkdir.failed:
return False
suffix = datetime.now().strftime('%Y%m%d%M%S')
path = 'versions/web_static_{}.tgz'.format(suffix)
tar = api.local('tar -cvzf {} web_static'.format(path))
if tar.failed:
return False
size = os.stat(path).st_size
print('web_static packed: {} -> {}Bytes'.format(path, size))
return path


def do_deploy(archive_path):
"""Function to transfer `archive_path` to web servers.
Args:
archive_path (str): path of the .tgz file to transfer
Returns: True on success, False otherwise.
"""
if not os.path.isfile(archive_path):
return False
with api.cd('/tmp'):
basename = os.path.basename(archive_path)
root, ext = os.path.splitext(basename)
outpath = '/data/web_static/releases/{}'.format(root)
try:
putpath = api.put(archive_path)
if files.exists(outpath):
api.run('rm -rdf {}'.format(outpath))
api.run('mkdir -p {}'.format(outpath))
api.run('tar -xzf {} -C {}'.format(putpath[0], outpath))
api.run('rm -f {}'.format(putpath[0]))
api.run('mv -u {}/web_static/* {}'.format(outpath, outpath))
api.run('rm -rf {}/web_static'.format(outpath))
api.run('rm -rf /data/web_static/current')
api.run('ln -s {} /data/web_static/current'.format(outpath))
print('New version deployed!')
except:
return False
else:
return True
2 changes: 2 additions & 0 deletions AUTHORS
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
# This file lists all individuals having contributed content to the repository.
Samuel Amsalu <[email protected]>
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
# 0x06. AirBnB clone - Web dynamic
181 changes: 181 additions & 0 deletions console.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,181 @@
#!/usr/bin/python3
""" console """

import cmd
from datetime import datetime
import models
from models.amenity import Amenity
from models.base_model import BaseModel
from models.city import City
from models.place import Place
from models.review import Review
from models.state import State
from models.user import User
import shlex # for splitting the line along spaces except in double quotes
import re

classes = {"Amenity": Amenity, "BaseModel": BaseModel, "City": City,
"Place": Place, "Review": Review, "State": State, "User": User}


class HBNBCommand(cmd.Cmd):
""" HBNH console """
prompt = '(hbnb) '

def do_EOF(self, arg):
"""Exits console"""
return True

def emptyline(self):
""" overwriting the emptyline method """
return False

def do_quit(self, arg):
"""Quit command to exit the program"""
return True

def do_create(self, arg):
"""Creates a new instance of a class
Command syntax: create <Class name> <param 1> <param 2> <param 3>...
Param syntax: <key name>=<value>
Value syntax:
string: "<value>"
Internal double quotes should be escaped. Spaces can be
represented using `_` and will be replaced by spaces.
float: <unit>.<decimal>
Unit or decimal may be missing.
int: <number>
Decimal integer.
Any parameter that does not fit this pattern will be ignored.
"""
args = shlex.split(arg)
if len(args) == 0:
print("** class name missing **")
return False
if args[0] not in classes:
print("** class doesn't exist **")
return False
else:
kwargs = {}
for arg in args[1:]:
match = re.fullmatch('(?P<key>[a-zA-Z_]\w*)=(?:'
'(?P<int>\d+)|'
'(?P<float>\d*\.\d*)|'
'(?P<string>.*))',
arg)
match = match.groupdict()
if match['string']:
kwargs[match['key']] = match['string'].replace('_', ' ')
elif match['float']:
if match['float'] == '.':
continue
kwargs[match['key']] = float(match['float'])
else:
kwargs[match['key']] = int(match['int'])

instance = classes[args[0]](**kwargs)
try:
instance.save()
except Exception as e:
print("** could not save [{}] object **".format(args[0]))
print(e)
return False
else:
print(instance.id)

def do_show(self, arg):
"""Prints an instance as a string based on the class and id"""
args = shlex.split(arg)
if len(args) == 0:
print("** class name missing **")
return False
if args[0] in classes:
if len(args) > 1:
key = args[0] + "." + args[1]
if key in models.storage.all():
print(models.storage.all()[key])
else:
print("** no instance found **")
else:
print("** instance id missing **")
else:
print("** class doesn't exist **")

def do_destroy(self, arg):
"""Deletes an instance based on the class and id"""
args = shlex.split(arg)
if len(args) == 0:
print("** class name missing **")
elif args[0] in classes:
if len(args) > 1:
key = args[0] + "." + args[1]
if key in models.storage.all():
models.storage.all()[key].delete()
models.storage.save()
else:
print("** no instance found **")
else:
print("** instance id missing **")
else:
print("** class doesn't exist **")

def do_all(self, arg):
"""Prints string representations of instances"""
args = shlex.split(arg)
obj_list = []
if len(args) == 0:
for value in models.storage.all().values():
obj_list.append(str(value))
elif args[0] in classes:
for key in models.storage.all():
if key.startswith(args[0]):
obj_list.append(str(models.storage.all()[key]))
else:
print("** class doesn't exist **")
return False
print(obj_list)

def do_update(self, arg):
"""Update an instance based on the class name, id, attribute & value"""
args = shlex.split(arg)
integers = ["number_rooms", "number_bathrooms", "max_guest",
"price_by_night"]
floats = ["latitude", "longitude"]
if len(args) == 0:
print("** class name missing **")
elif args[0] in classes:
if len(args) > 1:
k = args[0] + "." + args[1]
if k in models.storage.all():
if len(args) > 2:
if len(args) > 3:
if args[0] == "Place":
if args[2] in integers:
try:
args[3] = int(args[3])
except:
args[3] = 0
elif args[2] in floats:
try:
args[3] = float(args[3])
except:
args[3] = 0.0
setattr(models.storage.all()[k], args[2], args[3])
models.storage.all()[k].save()
else:
print("** value missing **")
else:
print("** attribute name missing **")
else:
print("** no instance found **")
else:
print("** instance id missing **")
else:
print("** class doesn't exist **")

if __name__ == '__main__':
HBNBCommand().cmdloop()
13 changes: 13 additions & 0 deletions models/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# AirBnB clone - Models
This directory contains all classes used to store information for the website.
## File Structure
- [base_model.py](base_model.py) - The BaseModel class from which future classes will be derived
- [amenity.py](amenity.py) - contains the Amenity class, derived from BaseModel
- [city.py](city.py) - contains the City class, derived from BaseModel
- [place.py](place.py) - contains the Place class, derived from BaseModel
- [review.py](review.py) - contains the Review class, derived from BaseModel
- [state.py](state.py) - contains the State class, derived from BaseModel
- [user.py](user.py) - contains the User class, derived from BaseModel
- **[engine](engine)** directory contains all storage classes:
- [file_storage.py](engine/file_storage.py) - serializes/deserializes instances to/from a JSON file
- [db_storage.py](engine/db_storage.py) - saves and loads instances to/from a MySQL database
16 changes: 16 additions & 0 deletions models/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
#!/usr/bin/python3
"""
initialize the models package
"""

from os import getenv

# DBSTORAGE
if getenv('HBNB_TYPE_STORAGE') == 'db':
from models.engine.db_storage import DBStorage
storage = DBStorage()
# FILESTORAGE
else:
from models.engine.file_storage import FileStorage
storage = FileStorage()
storage.reload()
Loading

0 comments on commit b1aeaaa

Please sign in to comment.