Exemplo n.º 1
0
    def process(self, session, **kwargs):
        """Implement the behavior for when the action is triggered

        Args:
            session (dict): environment dictionary

        Returns:
            Popen instance of newly spawned process

        """

        with pype.modified_environ(**session):
            # Get executable by name
            app = lib.get_application(self.name)
            executable = lib.which(app["executable"])

            # Run as server
            arguments = []

            tools_env = acre.get_tools([self.name])
            env = acre.compute(tools_env)
            env = acre.merge(env, current_env=dict(os.environ))

            if not env.get('AVALON_WORKDIR', None):
                project_name = env.get("AVALON_PROJECT")
                anatomy = Anatomy(project_name)
                os.environ['AVALON_PROJECT'] = project_name
                io.Session['AVALON_PROJECT'] = project_name

                task_name = os.environ.get("AVALON_TASK",
                                           io.Session["AVALON_TASK"])
                asset_name = os.environ.get("AVALON_ASSET",
                                            io.Session["AVALON_ASSET"])
                application = lib.get_application(
                    os.environ["AVALON_APP_NAME"])

                project_doc = io.find_one({"type": "project"})
                data = {
                    "task": task_name,
                    "asset": asset_name,
                    "project": {
                        "name": project_doc["name"],
                        "code": project_doc["data"].get("code", '')
                    },
                    "hierarchy": pype.get_hierarchy(),
                    "app": application["application_dir"]
                }
                anatomy_filled = anatomy.format(data)
                workdir = anatomy_filled["work"]["folder"]

                os.environ["AVALON_WORKDIR"] = workdir

            env.update(dict(os.environ))

            lib.launch(executable=executable, args=arguments, environment=env)
            return
Exemplo n.º 2
0
    def launch(self, session, event):
        # load shell scripts presets
        presets = config.get_presets()['ftrack'].get("user_assigment_event")
        if not presets:
            return
        for entity in event.get('data', {}).get('entities', []):
            if entity.get('entity_type') != 'Appointment':
                continue

            task, user = self._get_task_and_user(session,
                                                 entity.get('action'),
                                                 entity.get('changes'))

            if not task or not user:
                self.log.error(
                    'Task or User was not found.')
                continue

            data = self._get_template_data(task)
            # format directories to pass to shell script
            anatomy = Anatomy(data["project"]["name"])
            # formatting work dir is easiest part as we can use whole path
            work_dir = anatomy.format(data)['avalon']['work']
            # we also need publish but not whole
            publish = anatomy.format_all(data)['partial']['avalon']['publish']
            # now find path to {asset}
            m = re.search("(^.+?{})".format(data['asset']),
                          publish)

            if not m:
                msg = 'Cannot get part of publish path {}'.format(publish)
                self.log.error(msg)
                return {
                    'success': False,
                    'message': msg
                }
            publish_dir = m.group(1)

            for script in presets.get(entity.get('action')):
                self.log.info(
                    '[{}] : running script for user {}'.format(
                        entity.get('action'), user["username"]))
                self._run_script(script, [user["username"],
                                          work_dir, publish_dir])

        return True
Exemplo n.º 3
0
def test_anatomy(anatomy_file, monkeypatch):
    # TODO add test for `missing_keys` and `invalid_types`
    anatomy_file = os.path.join(anatomy_file, "repos", "pype-config")
    print(anatomy_file)

    monkeypatch.setitem(os.environ, 'PYPE_CONFIG', anatomy_file)
    anatomy = Anatomy()

    filled_all = anatomy.format_all(valid_data)
    filled = anatomy.format(valid_data)

    assert filled_all['work']['file'] == "PRJ_BOB_MODELING_v001_iAmComment.ABC"
    assert filled_all['work']['file2'] == "PRJ_BOB_MODELING_v001.ABC"
    assert filled_all['work'][
        'noDictKey'] == "PRJ_{asset[name]}_MODELING_v001.ABC"

    assert filled['work']['file'] == "PRJ_BOB_MODELING_v001_iAmComment.ABC"
    assert filled['work']['file2'] == "PRJ_BOB_MODELING_v001.ABC"
    assert filled['work'][
        'multiple_optional'] == "PRJ/BOB/asset/characters_v001.ABC"
Exemplo n.º 4
0
Arquivo: app.py Projeto: kalisp/pype
    def _get_destination_path(self, asset, project):
        project_name = project["name"]
        hierarchy = ""
        parents = asset['data']['parents']
        if parents and len(parents) > 0:
            hierarchy = os.path.join(*parents)

        template_data = {
            "project": {
                "name": project_name,
                "code": project['data']['code']
            },
            "silo": asset.get('silo'),
            "asset": asset['name'],
            "family": 'texture',
            "subset": 'Main',
            "hierarchy": hierarchy
        }
        anatomy = Anatomy(project_name)
        anatomy_filled = anatomy.format(template_data)
        return anatomy_filled['texture']['path']
Exemplo n.º 5
0
    def _get_destination_path(self, asset, project):
        root = api.registered_root()
        PROJECT = api.Session["AVALON_PROJECT"]
        hierarchy = ""
        parents = asset['data']['parents']
        if parents and len(parents) > 0:
            hierarchy = os.path.join(*parents)

        template_data = {
            "root": root,
            "project": {
                "name": PROJECT,
                "code": project['data']['code']
            },
            "silo": asset.get('silo'),
            "asset": asset['name'],
            "family": 'texture',
            "subset": 'Main',
            "hierarchy": hierarchy
        }
        anatomy = Anatomy()
        anatomy_filled = os.path.normpath(
            anatomy.format(template_data)['texture']['path'])
        return anatomy_filled
Exemplo n.º 6
0
    def run_application(self, app, project, asset, task, tools, arguments):
        """Run application in project/asset/task context.

        With default or specified tools enviornment. This uses pre-defined
        launcher in `pype-config/launchers` where there must be *toml*
        file with definition and in platform directory its launcher shell
        script or binary executables. Arguments will be passed to this script
        or executable.

        :param app: Full application name (`maya_2018`)
        :type app: Str
        :param project: Project name
        :type project: Str
        :param asset: Asset name
        :type asset: Str
        :param task: Task name
        :type task: Str
        :param tools: Comma separated list of tools (`"mtoa_2.1.0,yeti_4"`)
        :type tools: Str
        :param arguments: List of other arguments passed to app
        :type: List
        :rtype: None
        """
        import toml
        import subprocess

        from pypeapp.lib.Terminal import Terminal
        from pypeapp import Anatomy

        t = Terminal()

        self._initialize()
        self._update_python_path()

        import acre
        from avalon import lib
        from pype import lib as pypelib

        abspath = lib.which_app(app)
        if abspath is None:
            t.echo("!!! Application [ {} ] is not registered.".format(app))
            t.echo("*** Please define its toml file.")
            return

        app_toml = toml.load(abspath)

        executable = app_toml['executable']
        app_dir = app_toml['application_dir']
        # description = app_toml.get('description', None)
        # preactions = app_toml.get('preactions', [])

        launchers_path = os.path.join(os.environ["PYPE_CONFIG"], "launchers")

        database = pypelib.get_avalon_database()

        avalon_project = database[project].find_one({"type": "project"})

        if avalon_project is None:
            t.echo(
                "!!! Project [ {} ] doesn't exists in Avalon.".format(project))
            return False

        # get asset from db
        avalon_asset = database[project].find_one({
            "type": "asset",
            "name": asset
        })

        avalon_tools = avalon_project["data"]["tools_env"]
        if tools:
            avalon_tools = tools.split(",") or []

        hierarchy = ""
        parents = avalon_asset["data"]["parents"] or []
        if parents:
            hierarchy = os.path.join(*parents)

        data = {
            "project": {
                "name": project,
                "code": avalon_project['data']['code']
            },
            "task": task,
            "asset": asset,
            "app": app_dir,
            "hierarchy": hierarchy,
        }

        anatomy = Anatomy(project)
        anatomy_filled = anatomy.format(data)
        workdir = os.path.normpath(anatomy_filled["work"]["folder"])

        # set PYPE_ROOT_* environments
        anatomy.set_root_environments()

        # set environments for Avalon
        os.environ["AVALON_PROJECT"] = project
        os.environ["AVALON_SILO"] = None
        os.environ["AVALON_ASSET"] = asset
        os.environ["AVALON_TASK"] = task
        os.environ["AVALON_APP"] = app.split("_")[0]
        os.environ["AVALON_APP_NAME"] = app
        os.environ["AVALON_WORKDIR"] = workdir
        os.environ["AVALON_HIERARCHY"] = hierarchy

        try:
            os.makedirs(workdir)
        except FileExistsError:
            pass

        tools_attr = [os.environ["AVALON_APP"], os.environ["AVALON_APP_NAME"]]
        tools_attr += avalon_tools

        print("TOOLS: {}".format(tools_attr))

        tools_env = acre.get_tools(tools_attr)
        env = acre.compute(tools_env)

        env = acre.merge(env, current_env=dict(os.environ))
        env = {k: str(v) for k, v in env.items()}

        # sanitize slashes in path
        env["PYTHONPATH"] = env["PYTHONPATH"].replace("/", "\\")
        env["PYTHONPATH"] = env["PYTHONPATH"].replace("\\\\", "\\")

        launchers_path = os.path.join(launchers_path,
                                      platform.system().lower())
        execfile = None

        if sys.platform == "win32":
            # test all avaliable executable format, find first and use it
            for ext in os.environ["PATHEXT"].split(os.pathsep):
                fpath = os.path.join(launchers_path.strip('"'),
                                     executable + ext)
                if os.path.isfile(fpath) and os.access(fpath, os.X_OK):
                    execfile = fpath
                    break

                # Run SW if was found executable
            if execfile is not None:
                try:
                    t.echo(">>> Running [ {} {} ]".format(
                        executable, " ".join(arguments)))
                    args = [execfile]
                    args.extend(arguments)
                    subprocess.run(args, env=env)

                except ValueError as e:
                    t.echo("!!! Error while launching application:")
                    t.echo(e)
                    return
            else:
                t.echo(
                    "!!! cannot find application launcher [ {} ]".format(app))
                return

        if sys.platform.startswith('linux'):
            execfile = os.path.join(launchers_path.strip('"'), executable)
            if os.path.isfile(execfile):
                try:
                    fp = open(execfile)
                except PermissionError as p:
                    t.echo("!!! Access denied on launcher [ {} ]".format(app))
                    t.echo(p)
                    return

                fp.close()
            else:
                t.echo("!!! Launcher doesn\'t exist [ {} ]".format(execfile))
                return

            # Run SW if was found executable
            if execfile is not None:
                args = ['/usr/bin/env', 'bash', execfile]
                args.extend(arguments)
                t.echo(">>> Running [ {} ]".format(" ".join(args)))
                try:
                    subprocess.run(args, env=env)
                except ValueError as e:
                    t.echo("!!! Error while launching application:")
                    t.echo(e)
                    return
            else:
                t.echo(
                    "!!! cannot find application launcher [ {} ]".format(app))
                return
    def launch(self, session, entities, event):
        # DEBUG LINE
        # root_path = r"C:\Users\jakub.trllo\Desktop\Tests\ftrack_thumbnails"

        user = session.query(
            "User where username is '{0}'".format(session.api_user)
        ).one()
        action_job = session.create("Job", {
            "user": user,
            "status": "running",
            "data": json.dumps({
                "description": "Storing thumbnails to avalon."
            })
        })
        session.commit()

        project = self.get_project_from_entity(entities[0])
        project_name = project["full_name"]
        anatomy = Anatomy(project_name)

        if "publish" not in anatomy.templates:
            msg = "Anatomy does not have set publish key!"

            action_job["status"] = "failed"
            session.commit()

            self.log.warning(msg)

            return {
                "success": False,
                "message": msg
            }

        if "thumbnail" not in anatomy.templates["publish"]:
            msg = (
                "There is not set \"thumbnail\""
                " template in Antomy for project \"{}\""
            ).format(project_name)

            action_job["status"] = "failed"
            session.commit()

            self.log.warning(msg)

            return {
                "success": False,
                "message": msg
            }

        thumbnail_roots = os.environ.get(self.thumbnail_key)
        if (
            "{thumbnail_root}" in anatomy.templates["publish"]["thumbnail"]
            and not thumbnail_roots
        ):
            msg = "`{}` environment is not set".format(self.thumbnail_key)

            action_job["status"] = "failed"
            session.commit()

            self.log.warning(msg)

            return {
                "success": False,
                "message": msg
            }

        existing_thumbnail_root = None
        for path in thumbnail_roots.split(os.pathsep):
            if os.path.exists(path):
                existing_thumbnail_root = path
                break

        if existing_thumbnail_root is None:
            msg = (
                "Can't access paths, set in `{}` ({})"
            ).format(self.thumbnail_key, thumbnail_roots)

            action_job["status"] = "failed"
            session.commit()

            self.log.warning(msg)

            return {
                "success": False,
                "message": msg
            }

        example_template_data = {
            "_id": "ID",
            "thumbnail_root": "THUBMNAIL_ROOT",
            "thumbnail_type": "THUMBNAIL_TYPE",
            "ext": ".EXT",
            "project": {
                "name": "PROJECT_NAME",
                "code": "PROJECT_CODE"
            },
            "asset": "ASSET_NAME",
            "subset": "SUBSET_NAME",
            "version": "VERSION_NAME",
            "hierarchy": "HIERARCHY"
        }
        tmp_filled = anatomy.format_all(example_template_data)
        thumbnail_result = tmp_filled["publish"]["thumbnail"]
        if not thumbnail_result.solved:
            missing_keys = thumbnail_result.missing_keys
            invalid_types = thumbnail_result.invalid_types
            submsg = ""
            if missing_keys:
                submsg += "Missing keys: {}".format(", ".join(
                    ["\"{}\"".format(key) for key in missing_keys]
                ))

            if invalid_types:
                items = []
                for key, value in invalid_types.items():
                    items.append("{}{}".format(str(key), str(value)))
                submsg += "Invalid types: {}".format(", ".join(items))

            msg = (
                "Thumbnail Anatomy template expects more keys than action"
                " can offer. {}"
            ).format(submsg)

            action_job["status"] = "failed"
            session.commit()

            self.log.warning(msg)

            return {
                "success": False,
                "message": msg
            }

        thumbnail_template = anatomy.templates["publish"]["thumbnail"]

        self.db_con.install()

        for entity in entities:
            # Skip if entity is not AssetVersion (never should happend, but..)
            if entity.entity_type.lower() != "assetversion":
                continue

            # Skip if AssetVersion don't have thumbnail
            thumbnail_ent = entity["thumbnail"]
            if thumbnail_ent is None:
                self.log.debug((
                    "Skipping. AssetVersion don't "
                    "have set thumbnail. {}"
                ).format(entity["id"]))
                continue

            avalon_ents_result = self.get_avalon_entities_for_assetversion(
                entity, self.db_con
            )
            version_full_path = (
                "Asset: \"{project_name}/{asset_path}\""
                " | Subset: \"{subset_name}\""
                " | Version: \"{version_name}\""
            ).format(**avalon_ents_result)

            version = avalon_ents_result["version"]
            if not version:
                self.log.warning((
                    "AssetVersion does not have version in avalon. {}"
                ).format(version_full_path))
                continue

            thumbnail_id = version["data"].get("thumbnail_id")
            if thumbnail_id:
                self.log.info((
                    "AssetVersion skipped, already has thubmanil set. {}"
                ).format(version_full_path))
                continue

            # Get thumbnail extension
            file_ext = thumbnail_ent["file_type"]
            if not file_ext.startswith("."):
                file_ext = ".{}".format(file_ext)

            avalon_project = avalon_ents_result["project"]
            avalon_asset = avalon_ents_result["asset"]
            hierarchy = ""
            parents = avalon_asset["data"].get("parents") or []
            if parents:
                hierarchy = "/".join(parents)

            # Prepare anatomy template fill data
            # 1. Create new id for thumbnail entity
            thumbnail_id = ObjectId()

            template_data = {
                "_id": str(thumbnail_id),
                "thumbnail_root": existing_thumbnail_root,
                "thumbnail_type": "thumbnail",
                "ext": file_ext,
                "project": {
                    "name": avalon_project["name"],
                    "code": avalon_project["data"].get("code")
                },
                "asset": avalon_ents_result["asset_name"],
                "subset": avalon_ents_result["subset_name"],
                "version": avalon_ents_result["version_name"],
                "hierarchy": hierarchy
            }

            anatomy_filled = anatomy.format(template_data)
            thumbnail_path = anatomy_filled["publish"]["thumbnail"]
            thumbnail_path = thumbnail_path.replace("..", ".")
            thumbnail_path = os.path.normpath(thumbnail_path)

            downloaded = False
            for loc in (thumbnail_ent.get("component_locations") or []):
                res_id = loc.get("resource_identifier")
                if not res_id:
                    continue

                thubmnail_url = self.get_thumbnail_url(res_id)
                if self.download_file(thubmnail_url, thumbnail_path):
                    downloaded = True
                    break

            if not downloaded:
                self.log.warning(
                    "Could not download thumbnail for {}".format(
                        version_full_path
                    )
                )
                continue

            # Clean template data from keys that are dynamic
            template_data.pop("_id")
            template_data.pop("thumbnail_root")

            thumbnail_entity = {
                "_id": thumbnail_id,
                "type": "thumbnail",
                "schema": "pype:thumbnail-1.0",
                "data": {
                    "template": thumbnail_template,
                    "template_data": template_data
                }
            }

            # Create thumbnail entity
            self.db_con.insert_one(thumbnail_entity)
            self.log.debug(
                "Creating entity in database {}".format(str(thumbnail_entity))
            )

            # Set thumbnail id for version
            self.db_con.update_one(
                {"_id": version["_id"]},
                {"$set": {"data.thumbnail_id": thumbnail_id}}
            )

            self.db_con.update_one(
                {"_id": avalon_asset["_id"]},
                {"$set": {"data.thumbnail_id": thumbnail_id}}
            )

        action_job["status"] = "done"
        session.commit()

        return True
Exemplo n.º 8
0
    def launch(self, session, entities, event):
        '''Callback method for the custom action.

        return either a bool ( True if successful or False if the action failed )
        or a dictionary with they keys `message` and `success`, the message should be a
        string and will be displayed as feedback to the user, success should be a bool,
        True if successful or False if the action failed.

        *session* is a `ftrack_api.Session` instance

        *entities* is a list of tuples each containing the entity type and the entity id.
        If the entity is a hierarchical you will always get the entity
        type TypedContext, once retrieved through a get operation you
        will have the "real" entity type ie. example Shot, Sequence
        or Asset Build.

        *event* the unmodified original event

        '''

        entity = entities[0]
        project_name = entity['project']['full_name']

        database = pypelib.get_avalon_database()

        # Get current environments
        env_list = [
            'AVALON_PROJECT', 'AVALON_SILO', 'AVALON_ASSET', 'AVALON_TASK',
            'AVALON_APP', 'AVALON_APP_NAME'
        ]
        env_origin = {}
        for env in env_list:
            env_origin[env] = os.environ.get(env, None)

        # set environments for Avalon
        os.environ["AVALON_PROJECT"] = project_name
        os.environ["AVALON_SILO"] = entity['ancestors'][0]['name']
        os.environ["AVALON_ASSET"] = entity['parent']['name']
        os.environ["AVALON_TASK"] = entity['name']
        os.environ["AVALON_APP"] = self.identifier.split("_")[0]
        os.environ["AVALON_APP_NAME"] = self.identifier

        anatomy = Anatomy()

        hierarchy = ""
        parents = database[project_name].find_one({
            "type":
            'asset',
            "name":
            entity['parent']['name']
        })['data']['parents']

        if parents:
            hierarchy = os.path.join(*parents)

        application = avalonlib.get_application(os.environ["AVALON_APP_NAME"])

        data = {
            "root": os.environ.get("PYPE_STUDIO_PROJECTS_MOUNT"),
            "project": {
                "name": entity['project']['full_name'],
                "code": entity['project']['name']
            },
            "task": entity['name'],
            "asset": entity['parent']['name'],
            "app": application["application_dir"],
            "hierarchy": hierarchy,
        }

        av_project = database[project_name].find_one({"type": 'project'})
        templates = None
        if av_project:
            work_template = av_project.get('config',
                                           {}).get('template',
                                                   {}).get('work', None)
        work_template = None
        try:
            work_template = work_template.format(**data)
        except Exception:
            try:
                anatomy = anatomy.format(data)
                work_template = anatomy["work"]["folder"]

            except Exception as exc:
                msg = "{} Error in anatomy.format: {}".format(
                    __name__, str(exc))
                self.log.error(msg, exc_info=True)
                return {'success': False, 'message': msg}

        workdir = os.path.normpath(work_template)
        os.environ["AVALON_WORKDIR"] = workdir
        try:
            os.makedirs(workdir)
        except FileExistsError:
            pass

        # collect all parents from the task
        parents = []
        for item in entity['link']:
            parents.append(session.get(item['type'], item['id']))

        # collect all the 'environment' attributes from parents
        tools_attr = [os.environ["AVALON_APP"], os.environ["AVALON_APP_NAME"]]
        for parent in reversed(parents):
            # check if the attribute is empty, if not use it
            if parent['custom_attributes']['tools_env']:
                tools_attr.extend(parent['custom_attributes']['tools_env'])
                break

        tools_env = acre.get_tools(tools_attr)
        env = acre.compute(tools_env)
        env = acre.merge(env, current_env=dict(os.environ))
        env = acre.append(dict(os.environ), env)

        #
        # tools_env = acre.get_tools(tools)
        # env = acre.compute(dict(tools_env))
        # env = acre.merge(env, dict(os.environ))
        # os.environ = acre.append(dict(os.environ), env)
        # os.environ = acre.compute(os.environ)

        # Get path to execute
        st_temp_path = os.environ['PYPE_CONFIG']
        os_plat = platform.system().lower()

        # Path to folder with launchers
        path = os.path.join(st_temp_path, 'launchers', os_plat)
        # Full path to executable launcher
        execfile = None

        if sys.platform == "win32":

            for ext in os.environ["PATHEXT"].split(os.pathsep):
                fpath = os.path.join(path.strip('"'), self.executable + ext)
                if os.path.isfile(fpath) and os.access(fpath, os.X_OK):
                    execfile = fpath
                    break
                pass

            # Run SW if was found executable
            if execfile is not None:
                avalonlib.launch(executable=execfile, args=[], environment=env)
            else:
                return {
                    'success':
                    False,
                    'message':
                    "We didn't found launcher for {0}".format(self.label)
                }
                pass

        if sys.platform.startswith('linux'):
            execfile = os.path.join(path.strip('"'), self.executable)
            if os.path.isfile(execfile):
                try:
                    fp = open(execfile)
                except PermissionError as p:
                    self.log.exception('Access denied on {0} - {1}'.format(
                        execfile, p))
                    return {
                        'success':
                        False,
                        'message':
                        "Access denied on launcher - {}".format(execfile)
                    }
                fp.close()
                # check executable permission
                if not os.access(execfile, os.X_OK):
                    self.log.error(
                        'No executable permission on {}'.format(execfile))
                    return {
                        'success': False,
                        'message':
                        "No executable permission - {}".format(execfile)
                    }
                    pass
            else:
                self.log.error('Launcher doesn\'t exist - {}'.format(execfile))
                return {
                    'success': False,
                    'message': "Launcher doesn't exist - {}".format(execfile)
                }
                pass
            # Run SW if was found executable
            if execfile is not None:
                avalonlib.launch('/usr/bin/env',
                                 args=['bash', execfile],
                                 environment=env)
            else:
                return {
                    'success':
                    False,
                    'message':
                    "We didn't found launcher for {0}".format(self.label)
                }
                pass

        # Change status of task to In progress
        presets = config.get_presets()["ftrack"]["ftrack_config"]

        if 'status_update' in presets:
            statuses = presets['status_update']

            actual_status = entity['status']['name'].lower()
            next_status_name = None
            for key, value in statuses.items():
                if actual_status in value or '_any_' in value:
                    if key != '_ignore_':
                        next_status_name = key
                    break

            if next_status_name is not None:
                try:
                    query = 'Status where name is "{}"'.format(
                        next_status_name)
                    status = session.query(query).one()
                    entity['status'] = status
                    session.commit()
                except Exception:
                    msg = ('Status "{}" in presets wasn\'t found on Ftrack'
                           ).format(next_status_name)
                    self.log.warning(msg)

        # Set origin avalon environments
        for key, value in env_origin.items():
            if value == None:
                value = ""
            os.environ[key] = value

        return {'success': True, 'message': "Launching {0}".format(self.label)}
Exemplo n.º 9
0
    def launch(self, session, entities, event):
        """Callback method for the custom action.

        return either a bool (True if successful or False if the action failed)
        or a dictionary with they keys `message` and `success`, the message
        should be a string and will be displayed as feedback to the user,
        success should be a bool, True if successful or False if the action
        failed.

        *session* is a `ftrack_api.Session` instance

        *entities* is a list of tuples each containing the entity type and
        the entity id. If the entity is a hierarchical you will always get
        the entity type TypedContext, once retrieved through a get operation
        you will have the "real" entity type ie. example Shot, Sequence
        or Asset Build.

        *event* the unmodified original event
        """

        entity = entities[0]
        project_name = entity["project"]["full_name"]

        database = pypelib.get_avalon_database()

        asset_name = entity["parent"]["name"]
        asset_document = database[project_name].find_one({
            "type": "asset",
            "name": asset_name
        })

        hierarchy = ""
        asset_doc_parents = asset_document["data"].get("parents")
        if len(asset_doc_parents) > 0:
            hierarchy = os.path.join(*asset_doc_parents)

        application = avalon.lib.get_application(self.identifier)
        data = {
            "project": {
                "name": entity["project"]["full_name"],
                "code": entity["project"]["name"]
            },
            "task": entity["name"],
            "asset": asset_name,
            "app": application["application_dir"],
            "hierarchy": hierarchy
        }

        try:
            anatomy = Anatomy(project_name)
            anatomy_filled = anatomy.format(data)
            workdir = os.path.normpath(anatomy_filled["work"]["folder"])

        except Exception as exc:
            msg = "Error in anatomy.format: {}".format(str(exc))
            self.log.error(msg, exc_info=True)
            return {"success": False, "message": msg}

        try:
            os.makedirs(workdir)
        except FileExistsError:
            pass

        # set environments for Avalon
        prep_env = copy.deepcopy(os.environ)
        prep_env.update({
            "AVALON_PROJECT": project_name,
            "AVALON_ASSET": asset_name,
            "AVALON_TASK": entity["name"],
            "AVALON_APP": self.identifier.split("_")[0],
            "AVALON_APP_NAME": self.identifier,
            "AVALON_HIERARCHY": hierarchy,
            "AVALON_WORKDIR": workdir
        })
        prep_env.update(anatomy.roots_obj.root_environments())

        # collect all parents from the task
        parents = []
        for item in entity['link']:
            parents.append(session.get(item['type'], item['id']))

        # collect all the 'environment' attributes from parents
        tools_attr = [prep_env["AVALON_APP"], prep_env["AVALON_APP_NAME"]]
        tools_env = asset_document["data"].get("tools_env") or []
        tools_attr.extend(tools_env)

        tools_env = acre.get_tools(tools_attr)
        env = acre.compute(tools_env)
        env = acre.merge(env, current_env=dict(prep_env))
        env = acre.append(dict(prep_env), env)

        # Get path to execute
        st_temp_path = os.environ["PYPE_CONFIG"]
        os_plat = platform.system().lower()

        # Path to folder with launchers
        path = os.path.join(st_temp_path, "launchers", os_plat)

        # Full path to executable launcher
        execfile = None

        if application.get("launch_hook"):
            hook = application.get("launch_hook")
            self.log.info("launching hook: {}".format(hook))
            ret_val = pypelib.execute_hook(application.get("launch_hook"),
                                           env=env)
            if not ret_val:
                return {
                    'success':
                    False,
                    'message':
                    "Hook didn't finish successfully {0}".format(self.label)
                }

        if sys.platform == "win32":
            for ext in os.environ["PATHEXT"].split(os.pathsep):
                fpath = os.path.join(path.strip('"'), self.executable + ext)
                if os.path.isfile(fpath) and os.access(fpath, os.X_OK):
                    execfile = fpath
                    break

            # Run SW if was found executable
            if execfile is None:
                return {
                    "success": False,
                    "message":
                    "We didn't find launcher for {0}".format(self.label)
                }

            popen = avalon.lib.launch(executable=execfile,
                                      args=[],
                                      environment=env)

        elif (sys.platform.startswith("linux")
              or sys.platform.startswith("darwin")):
            execfile = os.path.join(path.strip('"'), self.executable)
            if not os.path.isfile(execfile):
                msg = "Launcher doesn't exist - {}".format(execfile)

                self.log.error(msg)
                return {"success": False, "message": msg}

            try:
                fp = open(execfile)
            except PermissionError as perm_exc:
                msg = "Access denied on launcher {} - {}".format(
                    execfile, perm_exc)

                self.log.exception(msg, exc_info=True)
                return {"success": False, "message": msg}

            fp.close()
            # check executable permission
            if not os.access(execfile, os.X_OK):
                msg = "No executable permission - {}".format(execfile)

                self.log.error(msg)
                return {"success": False, "message": msg}

            # Run SW if was found executable
            if execfile is None:
                return {
                    "success":
                    False,
                    "message":
                    "We didn't found launcher for {0}".format(self.label)
                }

            popen = avalon.lib.launch(  # noqa: F841
                "/usr/bin/env",
                args=["bash", execfile],
                environment=env)

        # Change status of task to In progress
        presets = config.get_presets()["ftrack"]["ftrack_config"]

        if "status_update" in presets:
            statuses = presets["status_update"]

            actual_status = entity["status"]["name"].lower()
            already_tested = []
            ent_path = "/".join([ent["name"] for ent in entity["link"]])
            while True:
                next_status_name = None
                for key, value in statuses.items():
                    if key in already_tested:
                        continue
                    if actual_status in value or "_any_" in value:
                        if key != "_ignore_":
                            next_status_name = key
                            already_tested.append(key)
                        break
                    already_tested.append(key)

                if next_status_name is None:
                    break

                try:
                    query = "Status where name is \"{}\"".format(
                        next_status_name)
                    status = session.query(query).one()

                    entity["status"] = status
                    session.commit()
                    self.log.debug("Changing status to \"{}\" <{}>".format(
                        next_status_name, ent_path))
                    break

                except Exception:
                    session.rollback()
                    msg = ("Status \"{}\" in presets wasn't found"
                           " on Ftrack entity type \"{}\"").format(
                               next_status_name, entity.entity_type)
                    self.log.warning(msg)

        return {"success": True, "message": "Launching {0}".format(self.label)}