def finalize(self):
        """
        This method is called when the flow is completed.
        Return 0 if success
        """
        if self.finalized:
            self.history.warning("Calling finalize on an already finalized flow.")
            return 1

        self.history.info("Calling flow.finalize.")
        self.finalized = True

        if self.has_db:
            self.history.info("Saving results in database.")
            try:
                self.flow.db_insert()
                self.finalized = True
            except Exception:
                 logger.critical("MongoDb insertion failed.")
                 return 2

        # Here we remove the big output files if we have the garbage collector
        # and the policy is set to "flow."
        if self.gc is not None and self.gc.policy == "flow":
            self.history.info("gc.policy set to flow. Will clean task output files.")
            for task in self.iflat_tasks():
                task.clean_output_files()

        return 0