Ejemplo n.º 1
0
def _DictFromSubprocess(command, stdin=None):
    """returns a dict based upon a subprocess call with a -plist argument.

  Args:
    command: the command to be executed as a list
    stdin: any standard input required.
  Returns:
    dict: dictionary from command output
  Raises:
    MacDiskError: Error running command
    MacDiskError: Error creating plist from standard output
  """

    task = {}

    if stdin:
        (task["stdout"], task["stderr"],
         task["returncode"]) = gmacpyutil.RunProcess(command, stdin)
    else:
        (task["stdout"], task["stderr"],
         task["returncode"]) = gmacpyutil.RunProcess(command)

    if task["returncode"] is not 0:
        raise MacDiskError("Error running command: %s, stderr: %s" %
                           (command, task["stderr"]))
    else:
        try:
            return plistlib.readPlistFromString(task["stdout"])
        except xml.parsers.expat.ExpatError:
            raise MacDiskError("Error creating plist from output: %s" %
                               task["stdout"])
Ejemplo n.º 2
0
 def testFactsFacterError(self):
     """Test Facts when facter fails."""
     self.mox.StubOutWithMock(gmacpyutil, 'RunProcess')
     puppet_cmd = [
         '/usr/bin/puppet', 'config', '--config', '/etc/puppet/puppet.conf',
         'print', 'factpath'
     ]
     facter_cmd = ['/usr/bin/facter', '-p']
     env = {'RUBYLIB': 'factpath'}
     gmacpyutil.RunProcess(puppet_cmd).AndReturn(('factpath\n', 'err\n', 0))
     gmacpyutil.RunProcess(facter_cmd, env=env).AndReturn(
         ('out\n', 'err\n', 1))
     self.mox.ReplayAll()
     self.assertRaises(gmacpyutil.GmacpyutilException, gmacpyutil.Facts)
     self.mox.VerifyAll()
Ejemplo n.º 3
0
 def Mount(self):
     """Mounts single volumes for partitions, all volumes for whole disks."""
     if self.Mounted():
         raise MacDiskError("%s is already mounted" % self.deviceid)
     else:
         command = ["diskutil", "mount", self.deviceid]
         rc = gmacpyutil.RunProcess(command)[2]
         if rc == 0:
             try:
                 command = ["diskutil", "enableOwnership", self.deviceid]
                 rc = gmacpyutil.RunProcess(command)[2]
             except:
                 pass
             self.Refresh()
             return True
Ejemplo n.º 4
0
 def testRunProcessReturnsATuple(self):
     """Test RunProcess returns a 3-tuple."""
     self.mox.StubOutWithMock(gmacpyutil, '_RunProcess')
     gmacpyutil._RunProcess(['cmd']).AndReturn(('out', 'err', 1))
     self.mox.ReplayAll()
     self.assertEqual(3, len(gmacpyutil.RunProcess(['cmd'])))
     self.mox.VerifyAll()
Ejemplo n.º 5
0
 def testFactsWithMalformedOutput(self):
     """Test Facts with malformed output."""
     self.mox.StubOutWithMock(gmacpyutil, 'RunProcess')
     puppet_cmd = [
         '/usr/bin/puppet', 'config', '--config', '/etc/puppet/puppet.conf',
         'print', 'factpath'
     ]
     facter_cmd = ['/usr/bin/facter', '-p']
     facter_out = 'fact1 => 1\nfact2 => value2\n\nfact3 =>\nfact4\n'
     facts = {'fact1': '1', 'fact2': 'value2', 'fact3': ''}
     env = {'RUBYLIB': 'factpath'}
     gmacpyutil.RunProcess(puppet_cmd).AndReturn(('factpath\n', 'err\n', 0))
     gmacpyutil.RunProcess(facter_cmd, env=env).AndReturn(
         (facter_out, 'err\n', 0))
     self.mox.ReplayAll()
     self.assertEqual(facts, gmacpyutil.Facts())
     self.mox.VerifyAll()
Ejemplo n.º 6
0
 def testPrivateRunProcessWithEnvNoClobber(self):
     """Test _RunProcess, simple cmd, with env, doesn't clobber os.environ."""
     environment = os.environ.copy()
     self.mox.ReplayAll()
     gmacpyutil.RunProcess(['/bin/echo'],
                           env={'added_to_env': 'added_to_env'})
     self.assertEqual(environment, os.environ)
     self.mox.VerifyAll()
Ejemplo n.º 7
0
    def testGetOSVersionMatchFails(self):
        self.mox.StubOutWithMock(gmacpyutil, 'RunProcess')
        cmd = ['sw_vers', '-productVersion']
        gmacpyutil.RunProcess(cmd).AndReturn(('foobar', '', 0))

        self.mox.ReplayAll()
        self.assertRaises(gmacpyutil.GmacpyutilException,
                          gmacpyutil.GetOSVersion)
        self.mox.VerifyAll()
Ejemplo n.º 8
0
 def ImageScan(self):
     """ASR image scanning."""
     command = ["asr", "imagescan", "--source", self.imagepath]
     stdout, stderr, returncode = gmacpyutil.RunProcess(command)
     if returncode is not 0:
         raise MacDiskError("Cannot imagescan %s, %s" %
                            (self.imagepath, stderr))
     else:
         return stdout
Ejemplo n.º 9
0
    def testGetOSVersion(self):
        self.mox.StubOutWithMock(gmacpyutil, 'RunProcess')
        cmd = ['sw_vers', '-productVersion']
        gmacpyutil.RunProcess(cmd).AndReturn(('10.8.4', '', 0))

        self.mox.ReplayAll()
        os_version = gmacpyutil.GetOSVersion()
        self.assertEqual(os_version, '10.8.4')
        self.mox.VerifyAll()
Ejemplo n.º 10
0
 def SetStartupDisk(self):
     """Sets this disk to be the startup disk."""
     self.Refresh()
     # pylint: disable=no-member
     if not self.Mounted():
         self.EnsureMountedWithRefresh()
     command = ["/usr/sbin/bless", "--mount", self.mountpoint, "--setBoot"]
     rc = gmacpyutil.RunProcess(command)[2]
     if rc == 0:
         return True
Ejemplo n.º 11
0
 def Rename(self, newname):
     """Renames a single volume."""
     if self.wholedisk:  # pylint: disable=no-member
         raise MacDiskError("Cannot rename whole disk %s" % self.deviceid)
     else:
         command = ["diskutil", "renameVolume", self.deviceid, newname]
         rc = gmacpyutil.RunProcess(command)[2]
         if rc == 0:
             self.Refresh()
             return True
Ejemplo n.º 12
0
 def Detach(self, force=False):
     """Detaches a disk image."""
     images = AttachedImages()
     for image in images:
         if image["image"].imagepath == self.imagepath:
             command = ["hdiutil", "detach"]
             command.append(image["disks"][0].deviceid)
             if force:
                 command.append("-force")
             gmacpyutil.RunProcess(command)
Ejemplo n.º 13
0
 def testFactsPuppetError(self):
     """Test Facts when puppet fails."""
     self.mox.StubOutWithMock(gmacpyutil, 'RunProcess')
     puppet_cmd = [
         '/usr/bin/puppet', 'config', '--config', '/etc/puppet/puppet.conf',
         'print', 'factpath'
     ]
     gmacpyutil.RunProcess(puppet_cmd).AndReturn(('out\n', 'err\n', 1))
     self.mox.ReplayAll()
     self.assertRaises(gmacpyutil.GmacpyutilException, gmacpyutil.Facts)
     self.mox.VerifyAll()
Ejemplo n.º 14
0
def InitalizeVDSB():
    """Initializes/updates the Volume Status Database.

  Returns:
    boolean: whether the operation succeeded.
  """
    command = ["vsdbutil", "-i"]
    rc = gmacpyutil.RunProcess(command)[2]
    if rc == 0:
        return True
    else:
        return False
Ejemplo n.º 15
0
 def Mount(self):
     """Mounts single volumes for partitions, all volumes for whole disks."""
     if self.Mounted():
         raise MacDiskError("%s is already mounted" % self.deviceid)
     else:
         command = ["diskutil", "mount", self.deviceid]
         #   if self.wholedisk:  # pylint: disable=no-member
         #     command[1] = "mountDisk"
         rc = gmacpyutil.RunProcess(command)[2]
         if rc == 0:
             self.Refresh()
             return True
Ejemplo n.º 16
0
 def DisableJournal(self):
     """enables journalling."""
     if self.wholedisk:  # pylint: disable=no-member
         raise MacDiskError("Cannot enable journal on whole disk: %s" %
                            self.deviceid)
     if not self.journalsize:  # pylint: disable=no-member
         raise MacDiskError("%s already has no journal." % self.deviceid)
     else:
         command = ["diskutil", "disableJournal", self.deviceid]
         rc = gmacpyutil.RunProcess(command)[2]
         if rc == 0:
             self.Refresh()
             return True
Ejemplo n.º 17
0
 def Unmount(self, force=False):
     """Unounts single volumes for partitions, all volumes for whole disks."""
     if not self.Mounted():
         raise MacDiskError("%s is not mounted" % self.deviceid)
     else:
         command = ["diskutil", "unmount", self.deviceid]
         if force:
             command.insert(2, "force")
         if self.wholedisk:  # pylint: disable=no-member
             command[1] = "unmountDisk"
         rc = gmacpyutil.RunProcess(command)[2]
         if rc == 0:
             self.Refresh()
             return True
Ejemplo n.º 18
0
    def EnsureMountedWithRefresh(self):
        """Mounts single volumes for partitions, all volumes for whole disks.

    Convenience method so you don't have to test if it's mounted already.

    Returns:
      boolean for success.
    """
        if self.Mounted():
            self.Refresh()
            return True
        else:
            command = ["diskutil", "mount", self.deviceid]
            #   if self.wholedisk:  # pylint: disable=no-member
            #     command[1] = "mountDisk"
            rc = gmacpyutil.RunProcess(command)[2]
            if rc == 0:
                try:
                    command = ["diskutil", "enableOwnership", self.deviceid]
                    rc = gmacpyutil.RunProcess(command)[2]
                except:
                    pass
                self.Refresh()
                return True
Ejemplo n.º 19
0
    def testGetPowerStateOnACNoBattery(self):
        """Test GetPowerState when on AC power and no battery."""
        self.mox.StubOutWithMock(gmacpyutil, 'RunProcess')
        cmd = ['/usr/bin/pmset', '-g', 'ps']
        stdout = "Currently drawing from 'AC Power'\n"
        mock_power_info = {
            'ac_power': True,
            'battery_percent': '-1',
            'battery_state': '-1',
            'minutes_remaining': '-1'
        }

        gmacpyutil.RunProcess(cmd).AndReturn((stdout, None, 0))

        self.mox.ReplayAll()
        self.assertEqual(mock_power_info, gmacpyutil.GetPowerState())
        self.mox.VerifyAll()
Ejemplo n.º 20
0
    def testGetPowerStateBothRegexFail(self):
        """Test GetPowerState when regular expression matching fails."""
        self.mox.StubOutWithMock(gmacpyutil, 'RunProcess')
        cmd = ['/usr/bin/pmset', '-g', 'ps']
        stdout = ('foo')
        mock_power_info = {
            'ac_power': '-1',
            'battery_percent': '-1',
            'battery_state': '-1',
            'minutes_remaining': '-1'
        }

        gmacpyutil.RunProcess(cmd).AndReturn((stdout, None, 0))

        self.mox.ReplayAll()
        self.assertEqual(mock_power_info, gmacpyutil.GetPowerState())
        self.mox.VerifyAll()
Ejemplo n.º 21
0
    def testGetPowerStateOnACFull(self):
        """Test GetPowerState when on AC power and battery is full."""
        self.mox.StubOutWithMock(gmacpyutil, 'RunProcess')
        cmd = ['/usr/bin/pmset', '-g', 'ps']
        stdout = ("Currently drawing from 'AC Power'\n "
                  "-InternalBattery-0\t100%; charged; 0:00 remaining\n")
        mock_power_info = {
            'ac_power': True,
            'battery_percent': 100,
            'battery_state': 'charged',
            'minutes_remaining': 0
        }

        gmacpyutil.RunProcess(cmd).AndReturn((stdout, None, 0))

        self.mox.ReplayAll()
        self.assertEqual(mock_power_info, gmacpyutil.GetPowerState())
        self.mox.VerifyAll()
Ejemplo n.º 22
0
    def testGetPowerStateDischarging(self):
        """Test GetPowerState when battery is discharging."""
        self.mox.StubOutWithMock(gmacpyutil, 'RunProcess')
        cmd = ['/usr/bin/pmset', '-g', 'ps']
        stdout = ("Currently drawing from 'Battery Power'\n "
                  "-InternalBattery-0\t50%; discharging; 3:42 remaining\n")
        mock_power_info = {
            'ac_power': False,
            'battery_percent': 50,
            'battery_state': 'discharging',
            'minutes_remaining': 222
        }

        gmacpyutil.RunProcess(cmd).AndReturn((stdout, None, 0))

        self.mox.ReplayAll()
        self.assertEqual(mock_power_info, gmacpyutil.GetPowerState())
        self.mox.VerifyAll()
Ejemplo n.º 23
0
    def testGetPowerStateBatteryRegexFail(self):
        """Test GetPowerState when regular expression matching fails."""
        self.mox.StubOutWithMock(gmacpyutil, 'RunProcess')
        cmd = ['/usr/bin/pmset', '-g', 'ps']
        stdout = ("Currently drawing from 'Battery Power'\n "
                  "-InternalBattery-0\t99%; discharging; (no estimate)\n")
        mock_power_info = {
            'ac_power': False,
            'battery_percent': '-1',
            'battery_state': '-1',
            'minutes_remaining': '-1'
        }

        gmacpyutil.RunProcess(cmd).AndReturn((stdout, None, 0))

        self.mox.ReplayAll()
        self.assertEqual(mock_power_info, gmacpyutil.GetPowerState())
        self.mox.VerifyAll()
Ejemplo n.º 24
0
 def testRunProcessFailsWithBackground(self):
     """Test RunProcess fails when called with background=True."""
     self.mox.ReplayAll()
     with self.assertRaises(gmacpyutil.GmacpyutilException):
         gmacpyutil.RunProcess(['foo'], background=True)
     self.mox.VerifyAll()