diff --git a/swh/loader/git/backend/api.py b/swh/loader/git/backend/api.py index 253eb04..9a4b679 100755 --- a/swh/loader/git/backend/api.py +++ b/swh/loader/git/backend/api.py @@ -1,254 +1,280 @@ #!/usr/bin/env python3 # Copyright (C) 2015 The Software Heritage developers # See the AUTHORS file at the top-level directory of this distribution # License: GNU General Public License version 3, or any later version # See top-level LICENSE file for more information + import logging from flask import Flask, Response, make_response, request from swh.loader.git.storage import storage, db, service from swh.loader.git.protocols import serial # api's definition app = Flask(__name__) def read_request_payload(request): """Read the request's payload. + """ # TODO: Check the signed pickled data? return serial.load(request.stream) def write_response(data): """Write response from data. + """ return Response(serial.dumps(data), mimetype=serial.MIMETYPE) @app.route('/') def hello(): """A simple api to define what the server is all about. FIXME: A redirect towards a static page defining the routes would be nice. + """ return 'Dev SWH API' # from uri to type -_uri_types = {'revisions': storage.Type.revision, - 'directories': storage.Type.directory, - 'contents': storage.Type.content, - 'releases': storage.Type.release, - 'occurrences': storage.Type.occurrence, - 'persons': storage.Type.person} +_uri_types = { + 'revisions': storage.Type.revision, + 'directories': storage.Type.directory, + 'contents': storage.Type.content, + 'releases': storage.Type.release, + 'occurrences': storage.Type.occurrence, + 'persons': storage.Type.person +} def _do_action_with_payload(conf, action_fn, uri_type, id, map_result_fn): uri_type_ok = _uri_types.get(uri_type, None) if uri_type_ok is None: return make_response('Bad request!', 400) vcs_object = read_request_payload(request) vcs_object.update({'id': id, 'type': uri_type_ok}) return action_fn(conf, vcs_object, map_result_fn) # occurrence type is not dealt the same way -_post_all_uri_types = {'revisions': storage.Type.revision, - 'directories': storage.Type.directory, - 'contents': storage.Type.content} +_post_all_uri_types = { + 'revisions': storage.Type.revision, + 'directories': storage.Type.directory, + 'contents': storage.Type.content +} @app.route('/vcs//', methods=['POST']) def filter_unknowns_type(uri_type): """Filters unknown sha1 to the backend and returns them. + """ if request.headers.get('Content-Type') != serial.MIMETYPE: - return make_response('Bad request. Expected %s data!' % serial.MIMETYPE, 400) + return make_response('Bad request. Expected ' + '%s data!' % serial.MIMETYPE, 400) obj_type = _post_all_uri_types.get(uri_type) if obj_type is None: return make_response('Bad request. Type not supported!', 400) sha1s = read_request_payload(request) config = app.config['conf'] with db.connect(config['db_url']) as db_conn: unknowns_sha1s = service.filter_unknowns_type(db_conn, obj_type, sha1s) if unknowns_sha1s is None: return make_response('Bad request!', 400) else: return write_response(unknowns_sha1s) + @app.route('/vcs/persons/', methods=['POST']) def post_person(): """Find a person. + """ if request.headers.get('Content-Type') != serial.MIMETYPE: - return make_response('Bad request. Expected %s data!' % serial.MIMETYPE, 400) + return make_response('Bad request. Expected ' + '%s data!' % serial.MIMETYPE, 400) origin = read_request_payload(request) config = app.config['conf'] with db.connect(config['db_url']) as db_conn: try: person_found = service.find_person(db_conn, origin) if person_found: return write_response(person_found) else: return make_response('Person not found!', 404) except: return make_response('Bad request!', 400) @app.route('/origins/', methods=['POST']) def post_origin(): """Find an origin. + """ if request.headers.get('Content-Type') != serial.MIMETYPE: - return make_response('Bad request. Expected %s data!' % serial.MIMETYPE, 400) + return make_response('Bad request. Expected ' + '%s data!' % serial.MIMETYPE, 400) origin = read_request_payload(request) config = app.config['conf'] with db.connect(config['db_url']) as db_conn: try: origin_found = service.find_origin(db_conn, origin) if origin_found: return write_response(origin_found) else: return make_response('Origin not found!', 404) except: return make_response('Bad request!', 400) @app.route('/origins/', methods=['PUT']) def put_origin(): """Create an origin or returns it if already existing. + """ if request.headers.get('Content-Type') != serial.MIMETYPE: - return make_response('Bad request. Expected %s data!' % serial.MIMETYPE, 400) + return make_response('Bad request. Expected ' + '%s data!' % serial.MIMETYPE, 400) origin = read_request_payload(request) config = app.config['conf'] with db.connect(config['db_url']) as db_conn: try: origin_found = service.add_origin(db_conn, origin) return write_response(origin_found) # FIXME: 204 except: return make_response('Bad request!', 400) @app.route('/vcs//', methods=['PUT']) def put_all(uri_type): - """Store or update given objects (uri_type in {contents, directories, releases). + """Store/update objects (uri_type in {contents, directories, releases}). + """ if request.headers.get('Content-Type') != serial.MIMETYPE: - return make_response('Bad request. Expected %s data!' % serial.MIMETYPE, 400) + return make_response('Bad request. Expected ' + '%s data!' % serial.MIMETYPE, 400) payload = read_request_payload(request) obj_type = _uri_types[uri_type] config = app.config['conf'] with db.connect(config['db_url']) as db_conn: service.persist(db_conn, config, obj_type, payload) return make_response('Successful creation!', 204) def add_object(config, vcs_object, map_result_fn): """Add object in storage. - config is the configuration needed for the backend to execute query - vcs_object is the object to look for in the backend - map_result_fn is a mapping function which takes the backend's result and transform its output accordingly. This function returns an http response of the result. + """ type = vcs_object['type'] id = vcs_object['id'] logging.debug('storage %s %s' % (type, id)) with db.connect(config['db_url']) as db_conn: res = service.persist(db_conn, config, type, [vcs_object]) return make_response(map_result_fn(id, res), 204) def _do_lookup(conf, uri_type, id, map_result_fn): """Looking up type object with sha1. - config is the configuration needed for the backend to execute query - vcs_object is the object to look for in the backend - map_result_fn is a mapping function which takes the backend's result and transform its output accordingly. This function returns an http response of the result. + """ uri_type_ok = _uri_types.get(uri_type, None) if not uri_type_ok: return make_response('Bad request!', 400) with db.connect(conf['db_url']) as db_conn: res = storage.find(db_conn, id, uri_type_ok) if res: return write_response(map_result_fn(id, res)) # 200 return make_response('Not found!', 404) @app.route('/vcs/occurrences/') def list_occurrences_for(id): """Return the occurrences pointing to the revision id. + """ return _do_lookup(app.config['conf'], 'occurrences', id, lambda _, result: list(map(lambda col: col[1], result))) @app.route('/vcs//') def object_exists_p(uri_type, id): """Assert if the object with sha1 id, of type uri_type, exists. + """ return _do_lookup(app.config['conf'], uri_type, id, lambda sha1, _: {'id': sha1}) @app.route('/vcs//', methods=['PUT']) def put_object(uri_type, id): """Put an object in storage. + """ return _do_action_with_payload(app.config['conf'], add_object, uri_type, id, - lambda sha1, _2: sha1) # FIXME: use id or result instead + # FIXME: use id or result instead + lambda sha1, _2: sha1) def run(conf): """Run the api's server. conf is a dictionary of keywords: - 'db_url' the db url's access (through psycopg2 format) - 'content_storage_dir' revisions/directories/contents storage on disk - 'host' to override the default 127.0.0.1 to open or not the server to the world - 'port' to override the default of 5000 (from the underlying layer: flask) - 'debug' activate the verbose logs + """ print("""SWH Api run host: %s port: %s debug: %s""" % (conf['host'], conf.get('port', None), conf['debug'])) # app.config is the app's state (accessible) app.config.update({'conf': conf}) app.run(host=conf['host'], port=conf.get('port', None), debug=conf['debug'] == 'true') diff --git a/swh/loader/git/client/http.py b/swh/loader/git/client/http.py index 4bb11fc..65fde00 100755 --- a/swh/loader/git/client/http.py +++ b/swh/loader/git/client/http.py @@ -1,86 +1,97 @@ #!/usr/bin/env python3 # Copyright (C) 2015 The Software Heritage developers # See the AUTHORS file at the top-level directory of this distribution # License: GNU General Public License version 3, or any later version # See top-level LICENSE file for more information import requests from retrying import retry from swh.loader.git.retry import policy from swh.loader.git.storage import storage from swh.loader.git.protocols import serial session_swh = requests.Session() def compute_simple_url(base_url, type): """Compute the api url. + """ return '%s%s' % (base_url, type) @retry(retry_on_exception=policy.retry_if_connection_error, wrap_exception=True, stop_max_attempt_number=3) def execute(map_type_url, method_fn, base_url, obj_type, data, result_fn=lambda result: result.ok): """Execute a query to the backend. - map_type_url is a map of {type: url backend} - method_fn is swh_session.post or swh_session.put - base_url is the base url of the backend - obj_type is the nature of the data - data is the data to send to the backend - result_fn is a function which takes the response result and do something with it. The default function is to return if the server is ok or not. + """ if not data: return data res = method_fn(compute_simple_url(base_url, map_type_url[obj_type]), data=serial.dumps(data), headers={'Content-Type': serial.MIMETYPE}) return result_fn(res) # url mapping for lookup -url_lookup_per_type = { storage.Type.origin: "/origins/" - , storage.Type.content: "/vcs/contents/" - , storage.Type.directory: "/vcs/directories/" - , storage.Type.revision: "/vcs/revisions/" - } +url_lookup_per_type = { + storage.Type.origin: "/origins/", + storage.Type.content: "/vcs/contents/", + storage.Type.directory: "/vcs/directories/", + storage.Type.revision: "/vcs/revisions/", +} def post(base_url, obj_type, obj_sha1s): """Retrieve the objects of type type with sha1 sha1hex. + """ return execute(url_lookup_per_type, session_swh.post, base_url, obj_type, obj_sha1s, result_fn=lambda res: serial.loads(res.content)) # url mapping for storage -url_store_per_type = { storage.Type.origin: "/origins/" - , storage.Type.content: "/vcs/contents/" - , storage.Type.directory: "/vcs/directories/" - , storage.Type.revision: "/vcs/revisions/" - , storage.Type.release: "/vcs/releases/" - , storage.Type.occurrence: "/vcs/occurrences/" - , storage.Type.person: "/vcs/persons/" - } +url_store_per_type = { + storage.Type.origin: "/origins/", + storage.Type.content: "/vcs/contents/", + storage.Type.directory: "/vcs/directories/", + storage.Type.revision: "/vcs/revisions/", + storage.Type.release: "/vcs/releases/", + storage.Type.occurrence: "/vcs/occurrences/", + storage.Type.person: "/vcs/persons/", +} + def put(base_url, obj_type, obj): """Given an obj (map, simple object) of obj_type, PUT it in the backend. + """ - return execute(url_store_per_type, session_swh.put, base_url, obj_type, obj) + return execute(url_store_per_type, + session_swh.put, + base_url, + obj_type, + obj) diff --git a/swh/loader/git/data/swhrepo.py b/swh/loader/git/data/swhrepo.py index df4963d..90c6951 100644 --- a/swh/loader/git/data/swhrepo.py +++ b/swh/loader/git/data/swhrepo.py @@ -1,70 +1,71 @@ # Copyright (C) 2015 The Software Heritage developers # See the AUTHORS file at the top-level directory of this distribution # License: GNU General Public License version 3, or any later version # See top-level LICENSE file for more information + class SWHRepo(): """Structure with: - sha1s as list - map indexed by sha1 """ def __init__(self): self.origin = {} self.releases = [] self.occurrences = [] self.contents = {} self.directories = {} self.revisions = {} self.persons = {} self.visited = set() def add_origin(self, origin): self.origin = origin def get_origin(self): return self.origin def add_release(self, release): self.releases.append(release) def get_releases(self): return self.releases def add_occurrence(self, occurrence): self.occurrences.append(occurrence) def get_occurrences(self): return self.occurrences def add_content(self, content_ref): sha1 = content_ref['id'] self.contents[sha1] = content_ref self.visited.add(sha1) def get_contents(self): return self.contents def add_directory(self, directory): sha1 = directory['id'] self.directories[sha1] = directory self.visited.add(sha1) def get_directories(self): return self.directories def add_revision(self, revision): sha1 = revision['id'] self.revisions[sha1] = revision self.visited.add(sha1) def add_person(self, id, person): self.persons[id] = person def get_persons(self): return self.persons.values() def already_visited(self, sha1): return sha1 in self.visited def get_revisions(self): return self.revisions diff --git a/swh/loader/git/git.py b/swh/loader/git/git.py index 7882918..8a1cea7 100644 --- a/swh/loader/git/git.py +++ b/swh/loader/git/git.py @@ -1,228 +1,234 @@ # Copyright (C) 2015 The Software Heritage developers # See the AUTHORS file at the top-level directory of this distribution # License: GNU General Public License version 3, or any later version # See top-level LICENSE file for more information import glob import logging import os import subprocess import time import pygit2 from datetime import datetime from pygit2 import GIT_REF_OID from pygit2 import GIT_OBJ_COMMIT, GIT_OBJ_TREE, GIT_SORT_TOPOLOGICAL from enum import Enum from swh.core import hashutil from swh.loader.git.data import swhrepo from swh.loader.git.storage import storage -class DirectoryTypeEntry(Enum): - """Types of git objects. - """ - file = 'file' - directory = 'directory' - - def date_format(d): """d is expected to be a datetime object. + """ return time.strftime("%a, %d %b %Y %H:%M:%S +0000", d.timetuple()) def now(): - """Cheat time values.""" + """Cheat time values. + + """ return date_format(datetime.utcnow()) def timestamp_to_string(timestamp): """Convert a timestamps to string. + """ return date_format(datetime.utcfromtimestamp(timestamp)) + def list_objects_from_packfile_index(packfile_index): - """List the objects indexed by this packfile""" + """List the objects indexed by this packfile. + + """ input_file = open(packfile_index, 'rb') with subprocess.Popen( ['/usr/bin/git', 'show-index'], stdin=input_file, stdout=subprocess.PIPE, ) as process: for line in process.stdout.readlines(): obj_id = line.decode('utf-8', 'ignore').split()[1] yield obj_id + def list_objects(repo): - """List the objects in a given repository""" + """List the objects in a given repository. + + """ objects_dir = os.path.join(repo.path, 'objects') objects_glob = os.path.join(objects_dir, '[0-9a-f]' * 2, '[0-9a-f]' * 38) packfile_dir = os.path.join(objects_dir, 'pack') if os.path.isdir(packfile_dir): for packfile_index in os.listdir(packfile_dir): if not packfile_index.endswith('.idx'): # Not an index file continue packfile_index_path = os.path.join(packfile_dir, packfile_index) yield from list_objects_from_packfile_index(packfile_index_path) for object_file in glob.glob(objects_glob): yield ''.join(object_file.split(os.path.sep)[-2:]) -HASH_ALGORITHMS=['sha1', 'sha256'] +HASH_ALGORITHMS = ['sha1', 'sha256'] def parse(repo_path): """Given a repository path, parse and return a memory model of such - repository.""" + repository. + + """ def read_signature(signature): return '%s <%s>' % (signature.name, signature.email) def treewalk(repo, tree): """Walk a tree with the same implementation as `os.path`. Returns: tree, trees, contents """ trees, contents, dir_entry_dirs, dir_entry_files = [], [], [], [] for tree_entry in tree: if swh_repo.already_visited(tree_entry.hex): - logging.debug('tree_entry %s already visited, skipped' % tree_entry.hex) + logging.debug('tree_entry %s already visited,' + ' skipped' % tree_entry.hex) continue obj = repo.get(tree_entry.oid) if obj is None: # or obj.type == GIT_OBJ_COMMIT: logging.warn('skip submodule-commit %s' % tree_entry.hex) continue # submodule! dir_entry = {'name': tree_entry.name, 'type': storage.Type.directory_entry, 'target-sha1': obj.hex, 'perms': tree_entry.filemode, 'atime': None, 'mtime': None, 'ctime': None} if obj.type == GIT_OBJ_TREE: logging.debug('found tree %s' % tree_entry.hex) - nature = DirectoryTypeEntry.directory.value trees.append(tree_entry) dir_entry_dirs.append(dir_entry) else: logging.debug('found content %s' % tree_entry.hex) data = obj.data - nature = DirectoryTypeEntry.file.value hashes = hashutil.hashdata(data, HASH_ALGORITHMS) contents.append({'id': hashes['sha1'], 'type': storage.Type.content, 'git-sha1': obj.hex, 'content-sha256': hashes['sha256'], 'content': data, 'size': obj.size}) dir_entry_files.append(dir_entry) yield tree, dir_entry_dirs, dir_entry_files, trees, contents for tree_entry in trees: for x in treewalk(repo, repo[tree_entry.oid]): yield x def walk_tree(repo, swh_repo, rev): """Walk the rev revision's directories. + """ if swh_repo.already_visited(rev.hex): logging.debug('commit %s already visited, skipped' % rev.hex) return swh_repo for dir_root, dir_entry_dirs, dir_entry_files, _, contents_ref \ in treewalk(repo, rev.tree): for content_ref in contents_ref: swh_repo.add_content(content_ref) swh_repo.add_directory({'id': dir_root.hex, 'type': storage.Type.directory, 'entry-dirs': dir_entry_dirs, 'entry-files': dir_entry_files}) revision_parent_sha1s = list(map(str, rev.parent_ids)) author = {'name': rev.author.name, 'email': rev.author.email, 'type': storage.Type.person} committer = {'name': rev.committer.name, 'email': rev.committer.email, 'type': storage.Type.person} swh_repo.add_revision({'id': rev.hex, - 'type':storage.Type.revision, + 'type': storage.Type.revision, 'date': timestamp_to_string(rev.commit_time), 'directory': rev.tree.hex, 'message': rev.message, 'committer': committer, 'author': author, 'parent-sha1s': revision_parent_sha1s - }) + }) swh_repo.add_person(read_signature(rev.author), author) swh_repo.add_person(read_signature(rev.committer), committer) return swh_repo def walk_revision_from(repo, swh_repo, head_rev): """Walk the rev history log from head_rev. - repo is the current repository - rev is the latest rev to start from. + """ for rev in repo.walk(head_rev.id, GIT_SORT_TOPOLOGICAL): swh_repo = walk_tree(repo, swh_repo, rev) return swh_repo repo = pygit2.Repository(repo_path) # memory model swh_repo = swhrepo.SWHRepo() # add origin origin = {'type': 'git', 'url': 'file://' + repo.path} swh_repo.add_origin(origin) # add references and crawl them for ref_name in repo.listall_references(): logging.info('walk reference %s' % ref_name) ref = repo.lookup_reference(ref_name) head_rev = repo[ref.target] \ if ref.type is GIT_REF_OID \ else ref.peel(GIT_OBJ_COMMIT) # noqa if isinstance(head_rev, pygit2.Tag): head_start = head_rev.get_object() taggerSig = head_rev.tagger author = {'name': taggerSig.name, 'email': taggerSig.email, 'type': storage.Type.person} release = {'id': head_rev.hex, 'type': storage.Type.release, 'revision': head_rev.target.hex, 'name': ref_name, 'date': now(), # FIXME: find the tag's date, 'author': author, 'comment': head_rev.message} swh_repo.add_release(release) swh_repo.add_person(read_signature(taggerSig), author) else: swh_repo.add_occurrence({'id': head_rev.hex, 'revision': head_rev.hex, 'branch': ref_name, 'url-origin': origin['url'], 'type': storage.Type.occurrence}) head_start = head_rev # crawl commits and trees walk_revision_from(repo, swh_repo, head_start) return swh_repo diff --git a/swh/loader/git/loader.py b/swh/loader/git/loader.py index defe4ec..0a6dfeb 100644 --- a/swh/loader/git/loader.py +++ b/swh/loader/git/loader.py @@ -1,57 +1,59 @@ # Copyright (C) 2015 The Software Heritage developers # See the AUTHORS file at the top-level directory of this distribution # License: GNU General Public License version 3, or any later version # See top-level LICENSE file for more information import logging import os from swh.loader.git import git, remote_store, local_store _load_to_back = { 'remote': remote_store.load_to_back, 'local': local_store.prepare_and_load_to_back, } def check_user_conf(conf): """Check the user's configuration and rejects if problems. + """ action = conf['action'] if action != 'load': return 'skip unknown action %s' % action backend_type = conf['backend-type'] if backend_type not in _load_to_back: return ('skip unknown backend-type %s (only ' '`remote`, `local` supported)' % backend_type) repo_path = conf['repo_path'] if not os.path.exists(repo_path): return 'Repository %s does not exist.' % repo_path return None def load(conf): """According to action, load the repo_path. used configuration keys: - action: requested action - repo_path: git repository path ('load' action only) - backend-type: backend access's type (remote or local) - backend: url access to backend api + """ error_msg = check_user_conf(conf) if error_msg: logging.error(error_msg) raise Exception(error_msg) repo_path = conf['repo_path'] logging.info('load repo_path %s' % repo_path) swhrepo = git.parse(repo_path) loader = _load_to_back[conf['backend-type']] loader(conf['backend'], swhrepo) diff --git a/swh/loader/git/local_store.py b/swh/loader/git/local_store.py index eac68bb..d5ecfd7 100644 --- a/swh/loader/git/local_store.py +++ b/swh/loader/git/local_store.py @@ -1,95 +1,108 @@ # Copyright (C) 2015 The Software Heritage developers # See the AUTHORS file at the top-level directory of this distribution # License: GNU General Public License version 3, or any later version # See top-level LICENSE file for more information from swh.loader.git.storage import storage, db, service from swh.loader.git.conf import reader from swh.storage.objstorage import ObjStorage # FIXME: duplicated from bin/swh-backend... # Default configuration file DEFAULT_CONF_FILE = '~/.config/swh/back.ini' # default configuration DEFAULT_CONF = { 'content_storage_dir': ('string', '/tmp/swh-loader-git/content-storage'), 'log_dir': ('string', '/tmp/swh-loader-git/log'), 'db_url': ('string', 'dbname=softwareheritage-dev'), 'folder_depth': ('int', 4), 'debug': ('bool', None), 'host': ('string', '127.0.0.1'), 'port': ('int', 5000) } def store_only_new(db_conn, conf, obj_type, obj): """Store object if not already present. + """ if not storage.find(db_conn, obj['id'], obj_type): storage.add(db_conn, conf, obj) _obj_to_persist_fn = {storage.Type.revision: service.add_revisions} def store_unknown_objects(db_conn, conf, obj_type, swhmap): """Load objects to the backend. + """ sha1s = swhmap.keys() # have: filter unknown obj unknown_obj_sha1s = service.filter_unknowns_type(db_conn, obj_type, sha1s) if not unknown_obj_sha1s: return True # seen: now store in backend persist_fn = _obj_to_persist_fn.get(obj_type, service.add_objects) obj_fulls = map(swhmap.get, unknown_obj_sha1s) return persist_fn(db_conn, conf, obj_type, obj_fulls) def load_to_back(conf, swh_repo): """Load to the backend the repository swh_repo. + """ with db.connect(conf['db_url']) as db_conn: # First, store/retrieve the origin identifier # FIXME: should be done by the cloner worker (which is not yet plugged # on the right swh db ftm) service.add_origin(db_conn, swh_repo.get_origin()) # First reference all unknown persons service.add_persons(db_conn, conf, storage.Type.person, swh_repo.get_persons()) - res = store_unknown_objects(db_conn, conf, storage.Type.content, + res = store_unknown_objects(db_conn, conf, + storage.Type.content, swh_repo.get_contents()) if res: - res = store_unknown_objects(db_conn, conf, storage.Type.directory, + res = store_unknown_objects(db_conn, conf, + storage.Type.directory, swh_repo.get_directories()) if res: - res = store_unknown_objects(db_conn, conf, storage.Type.revision, + res = store_unknown_objects(db_conn, conf, + storage.Type.revision, swh_repo.get_revisions()) if res: # brutally send all remaining occurrences - service.add_objects(db_conn, conf, storage.Type.occurrence, + service.add_objects(db_conn, conf, + storage.Type.occurrence, swh_repo.get_occurrences()) # and releases (the idea here is that compared to existing # objects, the quantity is less) - service.add_objects(db_conn, conf, storage.Type.release, + service.add_objects(db_conn, conf, + storage.Type.release, swh_repo.get_releases()) def prepare_and_load_to_back(backend_setup_file, swh_repo): + """Prepare and load to back the swh_repo. + backend-setup-file is the backend's setup to load to access the db and file + storage. + + """ # Read the configuration file (no check yet) conf = reader.read(backend_setup_file or DEFAULT_CONF_FILE, DEFAULT_CONF) reader.prepare_folders(conf, 'content_storage_dir') conf.update({ 'objstorage': ObjStorage(conf['content_storage_dir'], conf['folder_depth']) }) load_to_back(conf, swh_repo) diff --git a/swh/loader/git/manager.py b/swh/loader/git/manager.py index 8df0a98..fd48ce7 100755 --- a/swh/loader/git/manager.py +++ b/swh/loader/git/manager.py @@ -1,27 +1,28 @@ #!/usr/bin/env python3 # Copyright (C) 2015 The Software Heritage developers # See the AUTHORS file at the top-level directory of this distribution # License: GNU General Public License version 3, or any later version # See top-level LICENSE file for more information import logging from swh.loader.git.storage import db, models def manage(action, db_url): """According to action, load the repository. used configuration keys: - action: requested action [cleandb|initdb] + """ with db.connect(db_url) as db_conn: if action == 'cleandb': logging.info('clean database') models.cleandb(db_conn) elif action == 'initdb': logging.info('initialize database') models.initdb(db_conn) else: logging.warn('skip unknown-action %s' % action) diff --git a/swh/loader/git/protocols/serial.py b/swh/loader/git/protocols/serial.py index f5755f1..b6c232b 100755 --- a/swh/loader/git/protocols/serial.py +++ b/swh/loader/git/protocols/serial.py @@ -1,36 +1,41 @@ #!/usr/bin/env python3 # Copyright (C) 2015 The Software Heritage developers -# See the AUTHORS file_or_handle at the top-level directory of this distribution +# See the AUTHORS file at the top-level directory of this distribution # License: GNU General Public License version 3, or any later version -# See top-level LICENSE file_or_handle for more information +# See top-level LICENSE file for more information import pickle from io import BytesIO -MIMETYPE="application/octet-stream" + +MIMETYPE = "application/octet-stream" def load(file_or_handle): """Read a pickled object from the opened file_or_handle object. + """ return pickle.load(file_or_handle) def loads(obj): """Read a pickled object from bytes object. + """ if obj == b'': return obj return pickle.loads(obj) def dumps(obj): - """Return the pickle representation of the obj. - """ - return pickle.dumps(obj, protocol=pickle.HIGHEST_PROTOCOL) + """Return the pickle representation of the obj. + + """ + return pickle.dumps(obj, protocol=pickle.HIGHEST_PROTOCOL) def dumps_as_stream(obj): """Return the pickle representation of the obj as stream. + """ return pickle.dump(obj, BytesIO(), protocol=pickle.HIGHEST_PROTOCOL) diff --git a/swh/loader/git/remote_store.py b/swh/loader/git/remote_store.py index fbbc6c2..92f3c96 100644 --- a/swh/loader/git/remote_store.py +++ b/swh/loader/git/remote_store.py @@ -1,63 +1,65 @@ # Copyright (C) 2015 The Software Heritage developers # See the AUTHORS file at the top-level directory of this distribution # License: GNU General Public License version 3, or any later version # See top-level LICENSE file for more information from swh.loader.git.storage import storage from swh.loader.git.client import http def store_unknown_objects(back_url, obj_type, swhmap): """Load objects to the backend. + """ sha1s = list(swhmap.keys()) # have: filter unknown obj unknown_obj_sha1s = http.post(back_url, obj_type, sha1s) if not unknown_obj_sha1s: return True # store unknown objects return http.put(back_url, obj_type, map(swhmap.get, unknown_obj_sha1s)) def load_to_back(back_url, swh_repo): """Load to the back_url the repository swh_repo. + """ # First, store/retrieve the origin identifier # FIXME: should be done by the cloner worker (which is not yet plugged on # the right swh db ftm) http.put(back_url, obj_type=storage.Type.origin, obj=swh_repo.get_origin()) http.put(back_url, obj_type=storage.Type.person, obj=list(swh_repo.get_persons())) # let the backend and api discuss what's really needed # - first this worker sends the checksums # - then the backend answers the checksums it does not know # - then the worker sends only what the backend does not know per # object type basis res = store_unknown_objects(back_url, storage.Type.content, swh_repo.get_contents()) if res: res = store_unknown_objects(back_url, storage.Type.directory, swh_repo.get_directories()) if res: res = store_unknown_objects(back_url, storage.Type.revision, swh_repo.get_revisions()) if res: # brutally send all remaining occurrences http.put(back_url, storage.Type.occurrence, swh_repo.get_occurrences()) # and releases (the idea here is that compared to existing # other objects, the quantity is less) http.put(back_url, storage.Type.release, swh_repo.get_releases()) # FIXME: deal with collision failures which should be raised by backend. diff --git a/swh/loader/git/storage/models.py b/swh/loader/git/storage/models.py index bc98dfa..ee2ec60 100644 --- a/swh/loader/git/storage/models.py +++ b/swh/loader/git/storage/models.py @@ -1,324 +1,366 @@ # Copyright (C) 2015 The Software Heritage developers # See the AUTHORS file at the top-level directory of this distribution # License: GNU General Public License version 3, or any later version # See top-level LICENSE file for more information from enum import Enum from . import db class Type(Enum): """Types of git objects. + """ occurrence = 'occurrence' # ~git branch release = 'release' # ~git annotated tag revision = 'revision' # ~git commit directory = 'directory' # ~git tree directory_entry = 'directory_entry' # ~git tree_entry content = 'content' # ~git blob origin = 'origin' person = 'person' # committer, tagger, author def initdb(db_conn): """For retrocompatibility. + """ pass def cleandb(db_conn): - db.queries_execute(db_conn, ['TRUNCATE TABLE content CASCADE;', - 'TRUNCATE TABLE organization CASCADE;', - 'TRUNCATE TABLE list_history CASCADE;', - 'TRUNCATE TABLE origin CASCADE;', - 'TRUNCATE TABLE fetch_history CASCADE;', - 'TRUNCATE TABLE project CASCADE;', - 'TRUNCATE TABLE project_history CASCADE;', - 'TRUNCATE TABLE directory CASCADE;', - 'TRUNCATE TABLE directory_entry_dir CASCADE;', - 'TRUNCATE TABLE directory_list_dir CASCADE;', - 'TRUNCATE TABLE directory_entry_file CASCADE;', - 'TRUNCATE TABLE directory_list_file CASCADE;', - 'TRUNCATE TABLE person CASCADE;', - 'TRUNCATE TABLE revision CASCADE;', - 'TRUNCATE TABLE revision_history CASCADE;', - 'TRUNCATE TABLE occurrence_history CASCADE;', - 'TRUNCATE TABLE occurrence CASCADE;', - 'TRUNCATE TABLE release CASCADE;', - ]) + """Clean up DB. + + """ + db.queries_execute(db_conn, [ + 'TRUNCATE TABLE content CASCADE;', + 'TRUNCATE TABLE organization CASCADE;', + 'TRUNCATE TABLE list_history CASCADE;', + 'TRUNCATE TABLE origin CASCADE;', + 'TRUNCATE TABLE fetch_history CASCADE;', + 'TRUNCATE TABLE project CASCADE;', + 'TRUNCATE TABLE project_history CASCADE;', + 'TRUNCATE TABLE directory CASCADE;', + 'TRUNCATE TABLE directory_entry_dir CASCADE;', + 'TRUNCATE TABLE directory_list_dir CASCADE;', + 'TRUNCATE TABLE directory_entry_file CASCADE;', + 'TRUNCATE TABLE directory_list_file CASCADE;', + 'TRUNCATE TABLE person CASCADE;', + 'TRUNCATE TABLE revision CASCADE;', + 'TRUNCATE TABLE revision_history CASCADE;', + 'TRUNCATE TABLE occurrence_history CASCADE;', + 'TRUNCATE TABLE occurrence CASCADE;', + 'TRUNCATE TABLE release CASCADE;', + ]) def add_origin(db_conn, url, type, parent=None): """Insert origin and returns the newly inserted id. + """ return db.insert(db_conn, ("""INSERT INTO origin (type, url, parent_id) VALUES (%s, %s, %s) RETURNING id""", (type, url, parent))) + def add_person(db_conn, name, email): """Insert author and returns the newly inserted id. + """ return db.insert(db_conn, ("""INSERT INTO person (name, email) VALUES (%s, %s) RETURNING id""", (name, email))) def add_content(db_conn, sha1, sha1_git, sha256_content, size): """Insert a new content. + """ db.query_execute(db_conn, ("""INSERT INTO content (sha1, sha1_git, sha256, length) VALUES (%s, %s, %s, %s)""", (sha1, sha1_git, sha256_content, size))) def add_directory(db_conn, obj_sha): """Insert a new directory. + """ return db.insert(db_conn, ("""INSERT INTO directory (id) VALUES (%s) RETURNING id""", (obj_sha,))) def add_directory_entry_dir(db_conn, name, sha, perms, atime, mtime, ctime, parent_id): """Insert a new directory entry dir. + """ dir_entry_id = db.insert(db_conn, ("""INSERT INTO directory_entry_dir (name, target, perms, atime, mtime, ctime) VALUES (%s, %s, %s, %s, %s, %s) RETURNING id""", (name, sha, perms, atime, mtime, ctime))) db.query_execute(db_conn, ("""INSERT INTO directory_list_dir (dir_id, entry_id) VALUES (%s, %s)""", (parent_id, dir_entry_id))) def add_directory_entry_file(db_conn, name, sha, perms, atime, mtime, ctime, parent_id): """Insert a new directory entry file. + """ dir_entry_id = db.insert(db_conn, ("""INSERT INTO directory_entry_file (name, target, perms, atime, mtime, ctime) VALUES (%s, %s, %s, %s, %s, %s) RETURNING id""", (name, sha, perms, atime, mtime, ctime))) db.query_execute(db_conn, ("""INSERT INTO directory_list_file (dir_id, entry_id) VALUES (%s, %s)""", (parent_id, dir_entry_id))) def add_revision(db_conn, sha, date, directory, message, author, committer, parent_shas=None): """Insert a revision. + """ - db.query_execute(db_conn, - ("""INSERT INTO revision - (id, date, type, directory, message, author, committer) - VALUES (%s, %s, %s, %s, %s, - (select id from person where name=%s and email=%s), - (select id from person where name=%s and email=%s))""", - (sha, date, 'git', directory, message, - author['name'], author['email'], - committer['name'], committer['email']))) + db.query_execute( + db_conn, + ("""INSERT INTO revision + (id, date, type, directory, message, author, committer) + VALUES (%s, %s, %s, %s, %s, + (select id from person where name=%s and email=%s), + (select id from person where name=%s and email=%s))""", + (sha, date, 'git', directory, message, + author['name'], author['email'], + committer['name'], committer['email']))) def add_revision_history(db_conn, tuple_parents): """Store the revision history graph. + """ tuples = ','.join(["('%s','%s', %s)" % t for t in tuple_parents]) query = 'INSERT INTO revision_history ' + \ - '(id, parent_id, parent_rank) VALUES '+ tuples + '(id, parent_id, parent_rank) VALUES ' + tuples db.query_execute(db_conn, query) def add_release(db_conn, obj_sha, revision, date, name, comment, author): """Insert a release. + """ - db.query_execute(db_conn, - ("""INSERT INTO release (id, revision, date, name, comment, author) - VALUES (%s, %s, %s, %s, %s, - (select id from person where name=%s and email=%s))""", - (obj_sha, revision, date, name, comment, author['name'], author['email']))) + db.query_execute( + db_conn, + ("""INSERT INTO release (id, revision, date, name, comment, author) + VALUES (%s, %s, %s, %s, %s, + (select id from person where name=%s and email=%s))""", + (obj_sha, revision, date, name, comment, author['name'], + author['email']))) def add_occurrence(db_conn, url_origin, branch, revision): """Insert an occurrence. Check if occurrence history already present. If present do nothing, otherwise insert + """ with db_conn.cursor() as cur: occ = find_occurrence(cur, branch, revision, url_origin) if not occ: db.execute( cur, ("""INSERT INTO occurrence (origin, branch, revision) VALUES ((select id from origin where url=%s), %s, %s)""", (url_origin, branch, revision))) def find_revision(db_conn, obj_sha): """Find a revision by its obj_sha. + """ return find_object(db_conn, obj_sha, Type.revision) def find_directory(db_conn, obj_sha): """Find a directory by its obj_sha. + """ return find_object(db_conn, obj_sha, Type.directory) def find_content(db_conn, obj_sha): """Find a content by its obj_sha. + """ return find_object(db_conn, obj_sha, Type.content, column='sha1') def find_occurrences_for_revision(db_conn, revision, type): """Find all occurences for a specific revisions. type is not used (implementation detail). + """ return db.query_fetch(db_conn, ("""SELECT * FROM occurrence WHERE revision=%s""", (revision,))) def find_origin(db_conn, origin_url, origin_type): """Find all origins matching an url and an origin type. + """ return db.query_fetchone(db_conn, ("""SELECT * FROM origin WHERE url=%s AND type=%s""", (origin_url, origin_type))) + def find_person(db_conn, email, name): """Find a person uniquely identified by email and name. + """ return db.query_fetchone(db_conn, ("""SELECT id FROM person WHERE email=%s AND name=%s""", (email, name))) def find_occurrence(cur, branch, revision, url_origin): """Find an ocurrence with branch pointing on valid revision for date. + """ return db.fetchone( cur, ("""SELECT * FROM occurrence oc WHERE branch=%s AND revision=%s AND origin = (select id from origin where url = %s)""", (branch, revision, url_origin))) def find_object(db_conn, obj_sha, obj_type, column='id'): """Find an object of obj_type by its obj_sha. + """ table = obj_type if isinstance(obj_type, str) else obj_type.value - query = 'select '+ column + ' from ' + table + ' where ' + column + '=%s' + query = 'select ' + column + ' from ' + table + ' where ' + column + '=%s' return db.query_fetchone(db_conn, (query, (obj_sha,))) def filter_unknown_objects(db_conn, file_sha1s, table_to_filter, tbl_tmp_name, column_to_filter='id', nature_column='sha1_git'): """Given a list of sha1s, filter the unknown object between this list and the content of the table table_to_filter. tbl_tmp_name is the temporary table used to filter. + """ with db_conn.cursor() as cur: # explicit is better than implicit # simply creating the temporary table seems to be enough db.execute(cur, """CREATE TEMPORARY TABLE IF NOT EXISTS %s( %s %s) ON COMMIT DELETE ROWS;""" % (tbl_tmp_name, column_to_filter, nature_column)) db.copy_from(cur, file_sha1s, tbl_tmp_name) db.execute(cur, '(SELECT %s FROM %s) EXCEPT (SELECT %s FROM %s);' % (column_to_filter, tbl_tmp_name, column_to_filter, table_to_filter)) return cur.fetchall() def find_unknown_revisions(db_conn, file_sha1s): """Filter unknown revisions from file_sha1s. + """ return filter_unknown_objects(db_conn, file_sha1s, 'revision', 'filter_sha1_revision') def find_unknown_directories(db_conn, file_sha1s): """Filter unknown directories from file_sha1s. + """ return filter_unknown_objects(db_conn, file_sha1s, 'directory', 'filter_sha1_directory') def find_unknown_contents(db_conn, file_sha1s): """Filter unknown contents from file_sha1s. + """ return filter_unknown_objects(db_conn, file_sha1s, 'content', 'filter_sha1_content', 'sha1', 'sha1') def _count_objects(db_conn, type): + """Count the number of a given type object. + + """ return db.query_fetchone(db_conn, 'SELECT count(*) FROM ' + type.value)[0] def count_revisions(db_conn): """Count the number of revisions. + """ return _count_objects(db_conn, Type.revision) def count_directories(db_conn): """Count the number of directories. + """ return _count_objects(db_conn, Type.directory) def count_contents(db_conn): """Count the number of contents. + """ return _count_objects(db_conn, Type.content) def count_occurrence(db_conn): """Count the number of occurrence. + """ return _count_objects(db_conn, Type.occurrence) def count_release(db_conn): """Count the number of occurrence. + """ return _count_objects(db_conn, Type.release) def count_person(db_conn): """Count the number of occurrence. + """ return _count_objects(db_conn, Type.person) diff --git a/swh/loader/git/storage/service.py b/swh/loader/git/storage/service.py index d634a43..8c3a33f 100644 --- a/swh/loader/git/storage/service.py +++ b/swh/loader/git/storage/service.py @@ -1,98 +1,108 @@ # Copyright (C) 2015 The Software Heritage developers # See the AUTHORS file at the top-level directory of this distribution # License: GNU General Public License version 3, or any later version # See top-level LICENSE file for more information from . import storage filter_unknowns_type = storage.find_unknowns def find_origin(db_conn, origin): """Find origin. + """ - origin_found = storage.find_origin(db_conn, origin) - return None if not origin_found else {'id': origin_found[0]} + orig_found = storage.find_origin(db_conn, origin) + return None if not orig_found else {'id': orig_found[0]} def find_person(db_conn, person): """Find person. + """ person_found = storage.find_person(db_conn, person) return None if not person_found else {'id': person_found[0]} def add_origin(db_conn, origin): """Add origin if not already existing. + """ - origin_found = storage.find_origin(db_conn, origin) - id = origin_found[0] if origin_found else storage.add_origin(db_conn, origin) + orig_found = storage.find_origin(db_conn, origin) + id = orig_found[0] if orig_found else storage.add_origin(db_conn, origin) return {'id': id} def add_revisions(db_conn, conf, obj_type, objs): """Add Revisions. + """ tuple_parents = [] for obj in objs: # iterate over objects of type uri_type obj_id = obj['id'] obj_found = storage.find(db_conn, obj_id, obj_type) if not obj_found: storage.add(db_conn, conf, obj_id, obj_type, obj) # deal with revision history par_shas = obj.get('parent-sha1s', None) if par_shas: - parent_rank = [(obj_id, parent, rank) \ + parent_rank = [(obj_id, parent, rank) for (rank, parent) in enumerate(par_shas)] tuple_parents.extend(parent_rank) storage.add_revision_history(db_conn, tuple_parents) return True def add_persons(db_conn, conf, obj_type, objs): """Add persons. conf, obj_type are not used (implementation detail.) + """ for obj in objs: obj_found = storage.find_person(db_conn, obj) if not obj_found: storage.add_person(db_conn, obj) return True # dispatch map to add in storage with fs or not -_add_fn = {storage.Type.content: storage.add_with_fs_storage} +_add_fn = { + storage.Type.content: storage.add_with_fs_storage +} def add_objects(db_conn, conf, obj_type, objs): """Add objects if not already present in the storage. + """ add_fn = _add_fn.get(obj_type, storage.add) res = [] for obj in objs: # iterate over objects of type uri_type obj_id = obj['id'] obj_found = storage.find(db_conn, obj_id, obj_type) if not obj_found: obj = add_fn(db_conn, conf, obj_id, obj_type, obj) res.append(obj) else: res.append(obj_found) return res -_persist_fn = {storage.Type.person: add_persons, - storage.Type.revision: add_revisions} +_persist_fn = { + storage.Type.person: add_persons, + storage.Type.revision: add_revisions +} def persist(db_conn, conf, obj_type, objs): """Generic call to persist persons, revisions or other objects. """ persist_fn = _persist_fn.get(obj_type, add_objects) return persist_fn(db_conn, conf, obj_type, objs) diff --git a/swh/loader/git/storage/storage.py b/swh/loader/git/storage/storage.py index 8bcc905..ed5734c 100755 --- a/swh/loader/git/storage/storage.py +++ b/swh/loader/git/storage/storage.py @@ -1,218 +1,220 @@ # Copyright (C) 2015 The Software Heritage developers # See the AUTHORS file at the top-level directory of this distribution # License: GNU General Public License version 3, or any later version # See top-level LICENSE file for more information from io import StringIO from . import models Type = models.Type _find_object = {Type.occurrence: models.find_occurrences_for_revision, - Type.content: lambda *args: models.find_object(*args, column='sha1')} + Type.content: lambda *args: models.find_object(*args, + column='sha1')} + def find(db_conn, id, type): """Find an object according to its sha1hex and type. """ return _find_object.get(type, models.find_object)(db_conn, id, type) _find_unknown = {Type.revision: models.find_unknown_revisions, Type.content: models.find_unknown_contents, Type.directory: models.find_unknown_directories} def find_unknowns(db_conn, obj_type, sha1s_hex): """Given a list of sha1s, return the non presents one in storage. """ def row_to_sha1(row): """Convert a row (memoryview) to a string sha1. """ return row[0] vals = '\n'.join(sha1s_hex) cpy_data_buffer = StringIO() cpy_data_buffer.write(vals) cpy_data_buffer.seek(0) # move file cursor back at start of file find_unknown_fn = _find_unknown[obj_type] unknowns = find_unknown_fn(db_conn, cpy_data_buffer) cpy_data_buffer.close() return list(map(row_to_sha1, unknowns)) def _add_content(db_conn, vcs_object, sha1hex): """Add a blob to storage. Designed to be wrapped in a db transaction. Returns: - the sha1 if everything went alright. - None if something went wrong Writing exceptions can also be raised and expected to be handled by the caller. """ models.add_content(db_conn, sha1hex, vcs_object['git-sha1'], vcs_object['content-sha256'], vcs_object['size']) return sha1hex def _add_directory(db_conn, vcs_object, sha1hex): """Add a directory to storage. Designed to be wrapped in a db transaction. """ parent_id = models.add_directory(db_conn, sha1hex) for directory_entry_dir in vcs_object['entry-dirs']: _add_directory_entry_dir(db_conn, parent_id, directory_entry_dir) for directory_entry_file in vcs_object['entry-files']: _add_directory_entry_file(db_conn, parent_id, directory_entry_file) return sha1hex def _add_directory_entry_dir(db_conn, parent_id, vcs_object): """Add a directory entry dir to storage. Designed to be wrapped in a db transaction. Returns: - the sha1 if everything went alright. - None if something went wrong Writing exceptions can also be raised and expected to be handled by the caller. """ name = vcs_object['name'] models.add_directory_entry_dir(db_conn, name, vcs_object['target-sha1'], vcs_object['perms'], vcs_object['atime'], vcs_object['mtime'], vcs_object['ctime'], parent_id) return name, parent_id def _add_directory_entry_file(db_conn, parent_id, vcs_object): """Add a directory to storage. Designed to be wrapped in a db transaction. Returns: - the sha1 if everything went alright. - None if something went wrong Writing exceptions can also be raised and expected to be handled by the caller. """ name = vcs_object['name'] models.add_directory_entry_file(db_conn, name, vcs_object['target-sha1'], vcs_object['perms'], vcs_object['atime'], vcs_object['mtime'], vcs_object['ctime'], parent_id) return name, parent_id def _add_revision(db_conn, vcs_object, sha1hex): """Add a revision to storage. Designed to be wrapped in a db transaction. Returns: - the sha1 if everything went alright. - None if something went wrong Writing exceptions can also be raised and expected to be handled by the caller. """ models.add_revision(db_conn, sha1hex, vcs_object['date'], vcs_object['directory'], vcs_object['message'], vcs_object['author'], vcs_object['committer'], vcs_object['parent-sha1s']) return sha1hex def _add_release(db_conn, vcs_object, sha1hex): """Add a release. """ models.add_release(db_conn, sha1hex, vcs_object['revision'], vcs_object['date'], vcs_object['name'], vcs_object['comment'], vcs_object['author']) return sha1hex def _add_occurrence(db_conn, vcs_object, sha1hex): """Add an occurrence. """ models.add_occurrence(db_conn, vcs_object['url-origin'], vcs_object['branch'], vcs_object['revision']) return sha1hex def add_person(db_conn, vcs_object): """Add an author. """ return models.add_person(db_conn, vcs_object['name'], vcs_object['email']) _store_fn = {Type.directory: _add_directory, Type.revision: _add_revision, Type.release: _add_release, Type.occurrence: _add_occurrence} def add_origin(db_conn, origin): """A a new origin and returns its id. """ return models.add_origin(db_conn, origin['url'], origin['type']) def find_origin(db_conn, origin): """Find an existing origin. """ return models.find_origin(db_conn, origin['url'], origin['type']) def find_person(db_conn, person): """Find an existing person. """ return models.find_person(db_conn, person['email'], person['name']) def add_with_fs_storage(db_conn, config, id, type, vcs_object): """Add vcs_object in the storage - db_conn is the opened connection to the db - config is the map of configuration needed for core layer - type is not used here but represent the type of vcs_object - vcs_object is the object meant to be persisted in fs and db """ config['objstorage'].add_bytes(vcs_object['content'], id) return _add_content(db_conn, vcs_object, id) def add(db_conn, config, id, type, vcs_object): """Given a sha1hex, type and content, store a given object in the store. - db_conn is the opened connection to the db - config is not used here - type is the object's type - vcs_object is the object meant to be persisted in db """ return _store_fn[type](db_conn, vcs_object, id) def add_revision_history(db_conn, tuple_parents): """Given a list of tuple (sha, parent_sha), store in revision_history. """ if len(tuple_parents) > 0: models.add_revision_history(db_conn, tuple_parents) diff --git a/swh/loader/git/tests/test_api_content.py b/swh/loader/git/tests/test_api_content.py index 2b310ec..9d629b1 100644 --- a/swh/loader/git/tests/test_api_content.py +++ b/swh/loader/git/tests/test_api_content.py @@ -1,110 +1,111 @@ # Copyright (C) 2015 The Software Heritage developers # See the AUTHORS file at the top-level directory of this distribution # License: GNU General Public License version 3, or any later version # See top-level LICENSE file for more information import unittest from nose.tools import istest from nose.plugins.attrib import attr from swh.loader.git.storage import db, models from swh.loader.git.protocols import serial from test_utils import app_client, app_client_teardown @attr('slow') class ContentTestCase(unittest.TestCase): def setUp(self): self.app, db_url, self.content_storage_dir = app_client() with db.connect(db_url) as db_conn: self.content_sha1_id = '222222f9dd5dc46ee476a8be155ab049994f717e' content_sha1_id = 'blabliblablo' self.content_sha256_hex = '222222f9dd5dc46ee476a8be155ab049994f717e' models.add_content(db_conn, self.content_sha1_id, content_sha1_id, self.content_sha256_hex, 10) def tearDown(self): app_client_teardown(self.content_storage_dir) @istest def get_content_ok(self): # when rv = self.app.get('/vcs/contents/%s' % self.content_sha1_id) # then assert rv.status_code == 200 - assert serial.loads(rv.data)['id'] == '222222f9dd5dc46ee476a8be155ab049994f717e' + data = serial.loads(rv.data) + assert data['id'] == '222222f9dd5dc46ee476a8be155ab049994f717e' @istest def get_content_not_found(self): # when rv = self.app.get('/vcs/contents/222222f9dd5dc46ee476a8be155ab049994f7170') # then assert rv.status_code == 404 assert rv.data == b'Not found!' @istest def get_content_not_found_with_bad_format(self): # when rv = self.app.get('/vcs/contents/1') # then assert rv.status_code == 404 assert rv.data == b'Not found!' @istest def put_content_create_and_update(self): content_sha1 = '62cdb7020ff920e5aa642c3d4066950dd1f01f4d' # real sha1 of 'bar' # does not exist rv = self.app.get('/vcs/contents/%s' % content_sha1) # then assert rv.status_code == 404 assert rv.data == b'Not found!' # we create it body = {'id': content_sha1, 'git-sha1': 'content-sha1c46ee476a8be155ab03333333333', 'content-sha256': 'content-sha2566ee476a8be155ab03333333333', 'content': b'bar', 'size': '3'} rv = self.app.put('/vcs/contents/%s' % content_sha1, data=serial.dumps(body), headers={'Content-Type': serial.MIMETYPE}) assert rv.status_code == 204 assert rv.data == b'' # now it exists rv = self.app.get('/vcs/contents/%s' % content_sha1) # then assert rv.status_code == 200 assert serial.loads(rv.data)['id'] == content_sha1 # # we update it body = {'id': content_sha1, 'content-sha1': 'content-sha1c46ee476a8be155ab03333333333', 'content-sha256': 'content-sha2566ee476a8be155ab03333333333', 'content': b'bar', 'size': '3'} rv = self.app.put('/vcs/contents/%s' % content_sha1, data=serial.dumps(body), headers={'Content-Type': serial.MIMETYPE}) assert rv.status_code == 204 assert rv.data == b'' # still the same rv = self.app.get('/vcs/contents/%s' % content_sha1) # then assert rv.status_code == 200 assert serial.loads(rv.data)['id'] == content_sha1 diff --git a/swh/loader/git/tests/test_local_loader.py b/swh/loader/git/tests/test_local_loader.py index 220edf8..c6f92dc 100644 --- a/swh/loader/git/tests/test_local_loader.py +++ b/swh/loader/git/tests/test_local_loader.py @@ -1,249 +1,249 @@ # coding: utf-8 # Copyright (C) 2015 The Software Heritage developers # See the AUTHORS file at the top-level directory of this distribution # License: GNU General Public License version 3, or any later version # See top-level LICENSE file for more information + import unittest import pygit2 import tempfile import shutil -import os from nose.plugins.attrib import attr from nose.tools import istest from swh.loader.git.storage import db, models from swh.loader.git import loader from swh.loader.git.conf import reader import test_initdb from test_utils import list_files_from from test_git_utils import create_commit_with_content, create_tag @attr('slow') class TestLocalLoader(unittest.TestCase): def setUp(self): """Initialize a git repository for the remaining test to manipulate. """ tmp_git_folder_path = tempfile.mkdtemp(prefix='test-sgloader.', dir='/tmp') self.tmp_git_repo = pygit2.init_repository(tmp_git_folder_path) self.conf_back = reader.read('./resources/test/back.ini', {'port': ('int', 9999)}) self.db_url = self.conf_back['db_url'] self.conf = { 'action': 'load', 'repo_path': self.tmp_git_repo.workdir, 'backend-type': 'local', 'backend': './resources/test/back.ini' } def init_db_setup(self): """Initialize a git repository for the remaining test to manipulate. """ test_initdb.prepare_db(self.db_url) def tearDown(self): """Destroy the test git repository. """ shutil.rmtree(self.tmp_git_repo.workdir) shutil.rmtree(self.conf_back['content_storage_dir'], ignore_errors=True) @istest def should_fail_on_bad_action(self): # when try: loader.load({'action': 'unknown'}) except: pass @istest def should_fail_on_inexistant_folder(self): # when try: loader.load({'action': 'load', 'repo_path': 'something-that-definitely-does-not-exist'}) except: pass @istest def should_fail_on_inexistant_backend_type(self): # when try: loader.load({'action': 'load', 'repo_path': '.', 'backend-type': 'unknown'}) # only local or remote supported except: pass @istest def local_loader(self): """Trigger loader and make sure everything is ok. """ self.init_db_setup() # given commit0 = create_commit_with_content(self.tmp_git_repo, 'blob 0', 'commit msg 0') commit1 = create_commit_with_content(self.tmp_git_repo, 'blob 1', 'commit msg 1', [commit0.hex]) commit2 = create_commit_with_content(self.tmp_git_repo, 'blob 2', 'commit msg 2', [commit1.hex]) commit3 = create_commit_with_content(self.tmp_git_repo, None, 'commit msg 3', [commit2.hex]) commit4 = create_commit_with_content(self.tmp_git_repo, 'blob 4', 'commit msg 4', [commit3.hex]) # when loader.load(self.conf) # then nb_files = len(list_files_from(self.conf_back['content_storage_dir'])) self.assertEquals(nb_files, 4, "4 blobs.") with db.connect(self.db_url) as db_conn: self.assertEquals( models.count_revisions(db_conn), 5, "Should be 5 commits") self.assertEquals( models.count_directories(db_conn), 5, "Should be 5 trees") self.assertEquals( models.count_contents(db_conn), 4, "Should be 4 blobs as we created one commit without data!") self.assertEquals( models.count_release(db_conn), 0, "No tag created so 0 release.") self.assertEquals( models.count_occurrence(db_conn), 1, "Should be 1 reference (master) so 1 occurrence.") # given commit5 = create_commit_with_content(self.tmp_git_repo, 'new blob 5', 'commit msg 5', [commit4.hex]) commit6 = create_commit_with_content(self.tmp_git_repo, 'new blob and last 6', 'commit msg 6', [commit5.hex]) commit7 = create_commit_with_content(self.tmp_git_repo, 'new blob 7', 'commit msg 7', [commit6.hex]) # when loader.load(self.conf) # then nb_files = len(list_files_from(self.conf_back['content_storage_dir'])) self.assertEquals(nb_files, 4+3, "3 new blobs.") with db.connect(self.db_url) as db_conn: self.assertEquals( models.count_revisions(db_conn), 8, "Should be 5+3 == 8 commits now") self.assertEquals( models.count_directories(db_conn), 8, "Should be 5+3 == 8 trees") self.assertEquals( models.count_contents(db_conn), 7, "Should be 4+3 == 7 blobs") self.assertEquals( models.count_release(db_conn), 0, "No tag created so 0 release.") self.assertEquals( models.count_occurrence(db_conn), 2, "Should be 1 reference which changed twice so 2 occurrences (master changed).") # given create_commit_with_content(self.tmp_git_repo, None, 'commit 8 with parent 2', [commit7.hex]) # when loader.load(self.conf) # then nb_files = len(list_files_from(self.conf_back['content_storage_dir'])) self.assertEquals(nb_files, 7, "no new blob.") with db.connect(self.db_url) as db_conn: self.assertEquals( models.count_revisions(db_conn), 9, "Should be 8+1 == 9 commits now") self.assertEquals( models.count_directories(db_conn), 8, "Should be 8 trees (new commit without blob so no new tree)") self.assertEquals( models.count_contents(db_conn), 7, "Should be 7 blobs (new commit without new blob)") self.assertEquals( models.count_release(db_conn), 0, "No tag created so 0 release.") self.assertEquals( models.count_occurrence(db_conn), 3, "Should be 1 reference which changed thrice so 3 occurrences (master changed again).") self.assertEquals( models.count_person(db_conn), 2, "1 author + 1 committer") # add tag create_tag(self.tmp_git_repo, '0.0.1', commit5, 'bad ass release 0.0.1, towards infinity...') create_tag(self.tmp_git_repo, '0.0.2', commit7, 'release 0.0.2... and beyond') loader.load(self.conf) # then nb_files = len(list_files_from(self.conf_back['content_storage_dir'])) self.assertEquals(nb_files, 7, "no new blob.") with db.connect(self.db_url) as db_conn: self.assertEquals( models.count_revisions(db_conn), 9, "Should be 8+1 == 9 commits now") self.assertEquals( models.count_directories(db_conn), 8, "Should be 8 trees (new commit without blob so no new tree)") self.assertEquals( models.count_contents(db_conn), 7, "Should be 7 blobs (new commit without new blob)") self.assertEquals( models.count_release(db_conn), 2, "Should be 2 annotated tags so 2 releases") self.assertEquals( models.count_occurrence(db_conn), 3, "master did not change this time so still 3 occurrences") self.assertEquals( models.count_person(db_conn), 3, "1 author + 1 committer + 1 tagger")