Example #1
0
    def daemon(self):
        logger.info("Run daemon") 
        #Create lib dir
        if not os.path.isdir(conf.get_lib_dir()):
            fileutil.mkdir(conf.get_lib_dir(), mode=0o700)
            os.chdir(conf.get_lib_dir())

        if conf.get_detect_scvmm_env():
            if self.distro.scvmm_handler.run():
                return

        self.distro.provision_handler.run()
        
        if conf.get_resourcedisk_format():
            self.distro.resource_disk_handler.run()

        try:
            protocol = self.distro.protocol_util.detect_protocol()
        except ProtocolError as e:
            logger.error("Failed to detect protocol, exit", e)
            return
        
        self.distro.event_handler.run()
        self.distro.env_handler.run()
        
        while self.running:
            #Handle extensions
            self.distro.ext_handlers_handler.run()
            time.sleep(25)
Example #2
0
    def deploy_ssh_pubkey(self, username, pubkey):
        """
        Deploy authorized_key
        """
        path, thumbprint, value = pubkey
        if path is None:
            raise OSUtilError("Publich key path is None")

        crytputil = CryptUtil(conf.get_openssl_cmd())

        path = self._norm_path(path)
        dir_path = os.path.dirname(path)
        fileutil.mkdir(dir_path, mode=0o700, owner=username)
        if value is not None:
            if not value.startswith("ssh-"):
                raise OSUtilError("Bad public key: {0}".format(value))
            fileutil.write_file(path, value)
        elif thumbprint is not None:
            lib_dir = conf.get_lib_dir()
            crt_path = os.path.join(lib_dir, thumbprint + '.crt')
            if not os.path.isfile(crt_path):
                raise OSUtilError("Can't find {0}.crt".format(thumbprint))
            pub_path = os.path.join(lib_dir, thumbprint + '.pub')
            pub = crytputil.get_pubkey_from_crt(crt_path)
            fileutil.write_file(pub_path, pub)
            self.set_selinux_context(pub_path, 
                                     'unconfined_u:object_r:ssh_home_t:s0')
            self.openssl_to_openssh(pub_path, path)
            fileutil.chmod(pub_path, 0o600)
        else:
            raise OSUtilError("SSH public key Fingerprint and Value are None")

        self.set_selinux_context(path, 'unconfined_u:object_r:ssh_home_t:s0')
        fileutil.chowner(path, username)
        fileutil.chmod(path, 0o644)
Example #3
0
    def deploy_ssh_pubkey(self, username, pubkey):
        """
        Deploy authorized_key
        """
        path, thumbprint, value = pubkey
        if path is None:
            raise OSUtilError("Publich key path is None")

        crytputil = CryptUtil(conf.get_openssl_cmd())

        path = self._norm_path(path)
        dir_path = os.path.dirname(path)
        fileutil.mkdir(dir_path, mode=0o700, owner=username)
        if value is not None:
            if not value.startswith("ssh-"):
                raise OSUtilError("Bad public key: {0}".format(value))
            fileutil.write_file(path, value)
        elif thumbprint is not None:
            lib_dir = conf.get_lib_dir()
            crt_path = os.path.join(lib_dir, thumbprint + '.crt')
            if not os.path.isfile(crt_path):
                raise OSUtilError("Can't find {0}.crt".format(thumbprint))
            pub_path = os.path.join(lib_dir, thumbprint + '.pub')
            pub = crytputil.get_pubkey_from_crt(crt_path)
            fileutil.write_file(pub_path, pub)
            self.set_selinux_context(pub_path,
                                     'unconfined_u:object_r:ssh_home_t:s0')
            self.openssl_to_openssh(pub_path, path)
            fileutil.chmod(pub_path, 0o600)
        else:
            raise OSUtilError("SSH public key Fingerprint and Value are None")

        self.set_selinux_context(path, 'unconfined_u:object_r:ssh_home_t:s0')
        fileutil.chowner(path, username)
        fileutil.chmod(path, 0o644)
Example #4
0
    def mount_resource_disk(self, mount_point, fs):
        device = self.distro.osutil.device_for_ide_port(1)
        if device is None:
            raise ResourceDiskError("unable to detect disk topology")

        device = "/dev/" + device
        mountlist = shellutil.run_get_output("mount")[1]
        existing = self.distro.osutil.get_mount_point(mountlist, device)

        if(existing):
            logger.info("Resource disk {0}1 is already mounted", device)
            return existing

        fileutil.mkdir(mount_point, mode=0o755)

        logger.info("Detect GPT...")
        partition = device + "1"
        ret = shellutil.run_get_output("parted {0} print".format(device))
        if ret[0]:
            raise ResourceDiskError("({0}) {1}".format(device, ret[1]))

        if "gpt" in ret[1]:
            logger.info("GPT detected")
            logger.info("Get GPT partitions")
            parts = [x for x in ret[1].split("\n") if re.match("^\s*[0-9]+", x)]
            logger.info("Found more than {0} GPT partitions.", len(parts))
            if len(parts) > 1:
                logger.info("Remove old GPT partitions")
                for i in range(1, len(parts) + 1):
                    logger.info("Remove partition: {0}", i)
                    shellutil.run("parted {0} rm {1}".format(device, i))

                logger.info("Create a new GPT partition using entire disk space")
                shellutil.run("parted {0} mkpart primary 0% 100%".format(device))

                logger.info("Format partition: {0} with fstype {1}",partition,fs)
                shellutil.run("mkfs." + fs + " " + partition + " -F")
        else:
            logger.info("GPT not detected")
            logger.info("Check fstype")
            ret = shellutil.run_get_output("sfdisk -q -c {0} 1".format(device))
            if ret[1].rstrip() == "7" and fs != "ntfs":
                logger.info("The partition is formatted with ntfs")
                logger.info("Format partition: {0} with fstype {1}",partition,fs)
                shellutil.run("sfdisk -c {0} 1 83".format(device))
                shellutil.run("mkfs." + fs + " " + partition + " -F")

        logger.info("Mount resource disk")
        ret = shellutil.run("mount {0} {1}".format(partition, mount_point),
                                chk_err=False)
        if ret:
            logger.warn("Failed to mount resource disk. Retry mounting")
            shellutil.run("mkfs." + fs + " " + partition + " -F")
            ret = shellutil.run("mount {0} {1}".format(partition, mount_point))
            if ret:
                raise ResourceDiskError("({0}) {1}".format(partition, ret))

        logger.info("Resource disk ({0}) is mounted at {1} with fstype {2}",
                    device, mount_point, fs)
        return mount_point
Example #5
0
    def download(self):
        self.logger.info("Download extension package")
        self.set_operation(WALAEventOperation.Download)
        if self.pkg is None:
            raise ExtensionError("No package uri found")

        package = None
        for uri in self.pkg.uris:
            try:
                package = self.protocol.download_ext_handler_pkg(uri.uri)
            except ProtocolError as e:
                logger.warn("Failed download extension: {0}", e)

        if package is None:
            raise ExtensionError("Failed to download extension")

        self.logger.info("Unpack extension package")
        pkg_file = os.path.join(conf.get_lib_dir(),
                                os.path.basename(uri.uri) + ".zip")
        try:
            fileutil.write_file(pkg_file, bytearray(package), asbin=True)
            zipfile.ZipFile(pkg_file).extractall(self.get_base_dir())
        except IOError as e:
            raise ExtensionError(u"Failed to write and unzip plugin", e)

        chmod = "find {0} -type f | xargs chmod u+x".format(
            self.get_base_dir())
        shellutil.run(chmod)
        self.report_event(message="Download succeeded")

        self.logger.info("Initialize extension directory")
        #Save HandlerManifest.json
        man_file = fileutil.search_file(self.get_base_dir(),
                                        'HandlerManifest.json')

        if man_file is None:
            raise ExtensionError("HandlerManifest.json not found")

        try:
            man = fileutil.read_file(man_file, remove_bom=True)
            fileutil.write_file(self.get_manifest_file(), man)
        except IOError as e:
            raise ExtensionError(u"Failed to save HandlerManifest.json", e)

        #Create status and config dir
        try:
            status_dir = self.get_status_dir()
            fileutil.mkdir(status_dir, mode=0o700)
            conf_dir = self.get_conf_dir()
            fileutil.mkdir(conf_dir, mode=0o700)
        except IOError as e:
            raise ExtensionError(u"Failed to create status or config dir", e)

        #Save HandlerEnvironment.json
        self.create_handler_env()
Example #6
0
    def download(self):
        self.logger.info("Download extension package")
        self.set_operation(WALAEventOperation.Download)
        if self.pkg is None:
            raise ExtensionError("No package uri found")
        
        package = None
        for uri in self.pkg.uris:
            try:
                package = self.protocol.download_ext_handler_pkg(uri.uri)
            except ProtocolError as e: 
                logger.warn("Failed download extension: {0}", e)
        
        if package is None:
            raise ExtensionError("Failed to download extension")

        self.logger.info("Unpack extension package")
        pkg_file = os.path.join(conf.get_lib_dir(),
                                os.path.basename(uri.uri) + ".zip")
        try:
            fileutil.write_file(pkg_file, bytearray(package), asbin=True)
            zipfile.ZipFile(pkg_file).extractall(self.get_base_dir())
        except IOError as e:
            raise ExtensionError(u"Failed to write and unzip plugin", e)

        chmod = "find {0} -type f | xargs chmod u+x".format(self.get_base_dir())
        shellutil.run(chmod)
        self.report_event(message="Download succeeded")

        self.logger.info("Initialize extension directory")
        #Save HandlerManifest.json
        man_file = fileutil.search_file(self.get_base_dir(),
                                        'HandlerManifest.json')

        if man_file is None:
            raise ExtensionError("HandlerManifest.json not found")
        
        try:
            man = fileutil.read_file(man_file, remove_bom=True)
            fileutil.write_file(self.get_manifest_file(), man)
        except IOError as e:
            raise ExtensionError(u"Failed to save HandlerManifest.json", e)

        #Create status and config dir
        try:
            status_dir = self.get_status_dir()
            fileutil.mkdir(status_dir, mode=0o700)
            conf_dir = self.get_conf_dir()
            fileutil.mkdir(conf_dir, mode=0o700)
        except IOError as e:
            raise ExtensionError(u"Failed to create status or config dir", e)

        #Save HandlerEnvironment.json
        self.create_handler_env()
Example #7
0
 def set_handler_state(self, handler_state):
     state_dir = self.get_handler_state_dir()
     if not os.path.exists(state_dir):
         try:
             fileutil.mkdir(state_dir, 0o700)
         except IOError as e:
             self.logger.error("Failed to create state dir: {0}", e)
     
     try:
         state_file = os.path.join(state_dir, "state")
         fileutil.write_file(state_file, handler_state)
     except IOError as e:
         self.logger.error("Failed to set state: {0}", e)
Example #8
0
    def set_handler_state(self, handler_state):
        state_dir = self.get_handler_state_dir()
        if not os.path.exists(state_dir):
            try:
                fileutil.mkdir(state_dir, 0o700)
            except IOError as e:
                self.logger.error("Failed to create state dir: {0}", e)

        try:
            state_file = os.path.join(state_dir, "state")
            fileutil.write_file(state_file, handler_state)
        except IOError as e:
            self.logger.error("Failed to set state: {0}", e)
Example #9
0
    def __init__(self, ext_handler, protocol):
        self.ext_handler = ext_handler
        self.protocol = protocol
        self.operation = None
        self.pkg = None

        prefix = "[{0}]".format(self.get_full_name())
        self.logger = logger.Logger(logger.DEFAULT_LOGGER, prefix)
        
        try:
            fileutil.mkdir(self.get_log_dir(), mode=0o744)
        except IOError as e:
            self.logger.error(u"Failed to create extension log dir: {0}", e)

        log_file = os.path.join(self.get_log_dir(), "CommandExecution.log")
        self.logger.add_appender(logger.AppenderType.FILE,
                                 logger.LogLevel.INFO, log_file)
Example #10
0
    def __init__(self, ext_handler, protocol):
        self.ext_handler = ext_handler
        self.protocol = protocol
        self.operation = None
        self.pkg = None

        prefix = "[{0}]".format(self.get_full_name())
        self.logger = logger.Logger(logger.DEFAULT_LOGGER, prefix)

        try:
            fileutil.mkdir(self.get_log_dir(), mode=0o744)
        except IOError as e:
            self.logger.error(u"Failed to create extension log dir: {0}", e)

        log_file = os.path.join(self.get_log_dir(), "CommandExecution.log")
        self.logger.add_appender(logger.AppenderType.FILE,
                                 logger.LogLevel.INFO, log_file)
Example #11
0
    def set_handler_status(self, status="NotReady", message="", code=0):
        state_dir = self.get_handler_state_dir()
        if not os.path.exists(state_dir):
            try:
                fileutil.mkdir(state_dir, 0o700)
            except IOError as e:
                self.logger.error("Failed to create state dir: {0}", e)

        handler_status = ExtHandlerStatus()
        handler_status.name = self.ext_handler.name
        handler_status.version = self.ext_handler.properties.version
        handler_status.message = message
        handler_status.code = code
        handler_status.status = status
        status_file = os.path.join(state_dir, "status")

        try:
            fileutil.write_file(status_file,
                                json.dumps(get_properties(handler_status)))
        except (IOError, ValueError, ProtocolError) as e:
            self.logger.error("Failed to save handler status: {0}", e)
Example #12
0
 def deploy_ssh_keypair(self, username, keypair):
     """
     Deploy id_rsa and id_rsa.pub
     """
     path, thumbprint = keypair
     path = self._norm_path(path)
     dir_path = os.path.dirname(path)
     fileutil.mkdir(dir_path, mode=0o700, owner=username)
     lib_dir = conf.get_lib_dir()
     prv_path = os.path.join(lib_dir, thumbprint + '.prv')
     if not os.path.isfile(prv_path):
         raise OSUtilError("Can't find {0}.prv".format(thumbprint))
     shutil.copyfile(prv_path, path)
     pub_path = path + '.pub'
     crytputil = CryptUtil(conf.get_openssl_cmd())
     pub = crytputil.get_pubkey_from_prv(prv_path)
     fileutil.write_file(pub_path, pub)
     self.set_selinux_context(pub_path, 'unconfined_u:object_r:ssh_home_t:s0')
     self.set_selinux_context(path, 'unconfined_u:object_r:ssh_home_t:s0')
     os.chmod(path, 0o644)
     os.chmod(pub_path, 0o600)
Example #13
0
    def set_handler_status(self, status="NotReady", message="", 
                           code=0):
        state_dir = self.get_handler_state_dir()
        if not os.path.exists(state_dir):
            try:
                fileutil.mkdir(state_dir, 0o700)
            except IOError as e:
                self.logger.error("Failed to create state dir: {0}", e)
        
        handler_status = ExtHandlerStatus()
        handler_status.name = self.ext_handler.name
        handler_status.version = self.ext_handler.properties.version
        handler_status.message = message
        handler_status.code = code
        handler_status.status = status
        status_file = os.path.join(state_dir, "status")

        try:
            fileutil.write_file(status_file, 
                                json.dumps(get_properties(handler_status)))
        except (IOError, ValueError, ProtocolError) as e:
            self.logger.error("Failed to save handler status: {0}", e)
Example #14
0
 def deploy_ssh_keypair(self, username, keypair):
     """
     Deploy id_rsa and id_rsa.pub
     """
     path, thumbprint = keypair
     path = self._norm_path(path)
     dir_path = os.path.dirname(path)
     fileutil.mkdir(dir_path, mode=0o700, owner=username)
     lib_dir = conf.get_lib_dir()
     prv_path = os.path.join(lib_dir, thumbprint + '.prv')
     if not os.path.isfile(prv_path):
         raise OSUtilError("Can't find {0}.prv".format(thumbprint))
     shutil.copyfile(prv_path, path)
     pub_path = path + '.pub'
     crytputil = CryptUtil(conf.get_openssl_cmd())
     pub = crytputil.get_pubkey_from_prv(prv_path)
     fileutil.write_file(pub_path, pub)
     self.set_selinux_context(pub_path,
                              'unconfined_u:object_r:ssh_home_t:s0')
     self.set_selinux_context(path, 'unconfined_u:object_r:ssh_home_t:s0')
     os.chmod(path, 0o644)
     os.chmod(pub_path, 0o600)
    def mount_resource_disk(self, mount_point, fs):
        device = self.distro.osutil.device_for_ide_port(1)
        if device is None:
            raise ResourceDiskError("unable to detect disk topology")

        device = "/dev/" + device
        mountlist = shellutil.run_get_output("mount")[1]
        existing = self.distro.osutil.get_mount_point(mountlist, device)

        if (existing):
            logger.info("Resource disk {0}1 is already mounted", device)
            return existing

        fileutil.mkdir(mount_point, mode=0o755)

        logger.info("Detect GPT...")
        partition = device + "1"
        ret = shellutil.run_get_output("parted {0} print".format(device))
        if ret[0]:
            raise ResourceDiskError("({0}) {1}".format(device, ret[1]))

        if "gpt" in ret[1]:
            logger.info("GPT detected")
            logger.info("Get GPT partitions")
            parts = [
                x for x in ret[1].split("\n") if re.match("^\s*[0-9]+", x)
            ]
            logger.info("Found more than {0} GPT partitions.", len(parts))
            if len(parts) > 1:
                logger.info("Remove old GPT partitions")
                for i in range(1, len(parts) + 1):
                    logger.info("Remove partition: {0}", i)
                    shellutil.run("parted {0} rm {1}".format(device, i))

                logger.info(
                    "Create a new GPT partition using entire disk space")
                shellutil.run(
                    "parted {0} mkpart primary 0% 100%".format(device))

                logger.info("Format partition: {0} with fstype {1}", partition,
                            fs)
                shellutil.run("mkfs." + fs + " " + partition + " -F")
        else:
            logger.info("GPT not detected")
            logger.info("Check fstype")
            ret = shellutil.run_get_output("sfdisk -q -c {0} 1".format(device))
            if ret[1].rstrip() == "7" and fs != "ntfs":
                logger.info("The partition is formatted with ntfs")
                logger.info("Format partition: {0} with fstype {1}", partition,
                            fs)
                shellutil.run("sfdisk -c {0} 1 83".format(device))
                shellutil.run("mkfs." + fs + " " + partition + " -F")

        logger.info("Mount resource disk")
        ret = shellutil.run("mount {0} {1}".format(partition, mount_point),
                            chk_err=False)
        if ret:
            logger.warn("Failed to mount resource disk. Retry mounting")
            shellutil.run("mkfs." + fs + " " + partition + " -F")
            ret = shellutil.run("mount {0} {1}".format(partition, mount_point))
            if ret:
                raise ResourceDiskError("({0}) {1}".format(partition, ret))

        logger.info("Resource disk ({0}) is mounted at {1} with fstype {2}",
                    device, mount_point, fs)
        return mount_point