'Copy a file with preserved ownership, permissions and context'

def preserved_copy(self, src, dest):

    shutil.copy2(src, dest)
    if self.selinux_enabled():
        context = self.selinux_context(src)
        self.set_context_if_different(dest, context, False)
    try:
        dest_stat = os.stat(src)
        tmp_stat = os.stat(dest)
        if (dest_stat and ((tmp_stat.st_uid != dest_stat.st_uid) or (tmp_stat.st_gid != dest_stat.st_gid))):
            os.chown(dest, dest_stat.st_uid, dest_stat.st_gid)
    except OSError as e:
        if (e.errno != errno.EPERM):
            raise
    current_attribs = self.get_file_attributes(src)
    current_attribs = current_attribs.get('attr_flags', [])
    current_attribs = ''.join(current_attribs)
    self.set_attributes_if_different(dest, current_attribs, True)
