def test_uninstall(self): cmd = [binPath('zenpack'), "--link", "--install", self.zenpack_path] LOG.info(" ".join(cmd)) p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE) out, err = p.communicate() p.wait() LOG.debug("out=%s, err=%s", out, err) self.assertIs( p.returncode, 0, 'Error installing %s zenpack: %s' % (self.zenpack_path, err)) cmd = [binPath('zenpack'), "--remove", self.zenpack_name] LOG.info(" ".join(cmd)) p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE) out, err = p.communicate() p.wait() LOG.debug("out=%s, err=%s", out, err) self.assertIs( p.returncode, 0, 'Error removing %s zenpack: %s' % (self.zenpack_name, err))
def getProcessList(self, deviceGuid): if deviceGuid and len(deviceGuid) > 0: s = '' try: import subprocess from Products.ZenUtils.Utils import binPath device = IGUIDManager(self._dmd).getObject(deviceGuid) s = '# ' + device.id zenmodelerOpts = ['run', '--now', '--debug', '-v10', '-d', device.id] isPerfMonRemote = False zenmodelerName = 'zenmodeler' zenmodelerPath = binPath(zenmodelerName) monitorId = device.perfServer().id if monitorId != 'localhost': zenmodelerName = monitorId + '_' + zenmodelerName zenmodelerPath = binPath(zenmodelerName) if len(zenmodelerPath) == 0: isPerfMonRemote = True if isPerfMonRemote: cmd = "ssh %s %s %s" % (device.perfServer().hostname, zenmodelerName, ' '.join(zenmodelerOpts)) else: cmd = "%s %s" % (zenmodelerPath, ' '.join(zenmodelerOpts)) processList = subprocess.check_output(cmd, shell=True, stderr=subprocess.STDOUT).splitlines() filterProcessLine = re.compile('DEBUG zen\.osprocessmatcher: COMMAND LINE: (?P<process>.*)$') for processListLine in processList: m = filterProcessLine.search(processListLine) if m: s += '\n' + m.group('process') except Exception, e: s += '\n# ' + str(e) yield { 'uid': '0', 'process': s }
class IpServiceMap(PythonPlugin): transport = "python" maptype = "IpServiceMap" compname = "os" relname = "ipservices" modname = "Products.ZenModel.IpService" deviceProperties = PythonPlugin.deviceProperties + ( 'zNmapPortscanOptions', ) def collect(self, device, log): nmapoptions = getattr(device, 'zNmapPortscanOptions', NMAPDEFAULTS) #compile Tales expressions tales = readyopts = None try: tales = talesCompile('string:' + nmapoptions) readyopts = tales(getEngine().getContext({ 'here': device, 'device': device, 'dev': device })) readyopts = readyopts + " " + device.manageIp #if there was an error make a best effort except Exception, e: log.error( "zNmapPortscanOptions contain illegal Tales expression, please review: %s" % e) readyopts = NMAPDEFAULTS + " " + device.manageIp nmapoptions = readyopts.split(" ") log.info("running the following nmap command: %s %s" % \ (binPath('nmap'), " ".join(nmapoptions))) return getProcessOutput(binPath('nmap'), nmapoptions)
def setUp(self): cmd = [binPath('zenpack'), "--list"] LOG.info(" ".join(cmd)) p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE) out, err = p.communicate() p.wait() LOG.debug("out=%s, err=%s", out, err) self.assertIs(p.returncode, 0, 'Error listing installed zenpacks: %s' % err) if self.zenpack_name in out: cmd = [binPath('zenpack'), "--remove", self.zenpack_name] LOG.info(" ".join(cmd)) p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE) out, err = p.communicate() p.wait() LOG.debug("out=%s, err=%s", out, err) self.assertIs( p.returncode, 0, 'Error removing %s zenpack: %s' % (self.zenpack_name, err))
def checkCommandPrefix(self, context, cmd): if not cmd.startswith('/') and not cmd.startswith('$'): if context.zCommandPath and not cmd.startswith(context.zCommandPath): cmd = os.path.join(context.zCommandPath, cmd) elif binPath(cmd.split(" ",1)[0]): #if we get here it is because cmd is not absolute, doesn't #start with $, zCommandPath is not set and we found cmd in #one of the zenoss bin dirs cmdList = cmd.split(" ",1) #split into command and args cmd = binPath(cmdList[0]) if len(cmdList) > 1: cmd = "%s %s" % (cmd, cmdList[1]) return cmd
def getCommand(self, context): if self.useSSL: parts = [binPath('check_nntps')] else: parts = [binPath('check_nntp')] if self.nntpServer: parts.append('-H %s' % self.nntpServer) if self.port: parts.append('-p %d' % self.port) if self.timeout: parts.append('-t %d' % self.timeout) cmd = ' '.join(parts) cmd = RRDDataSource.RRDDataSource.getCommand(self, context, cmd) return cmd
def test_add_template(self): cmd = [binPath('zenpack'), "--link", "--install", self.zenpack_path] LOG.info(" ".join(cmd)) p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE) out, err = p.communicate() p.wait() LOG.debug("out=%s, err=%s", out, err) self.assertIs(p.returncode, 0, 'Error installing %s zenpack: %s' % (self.zenpack_path, err)) # install it a second time, with a different yaml file that simulates # adding a new monitoring template yaml_filename = os.path.join(self.zenpack_path, 'ZenPacks/zenoss/ZPLTest1/zenpack2.yaml') LOG.info("ZPL_YAML_FILENAME=" + yaml_filename + " " + " ".join(cmd)) p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, env=dict(os.environ, ZPL_YAML_FILENAME=yaml_filename)) out, err = p.communicate() p.wait() LOG.debug("out=%s, err=%s", out, err) self.assertIs(p.returncode, 0, 'Error upgrading %s zenpack: %s' % (self.zenpack_name, err)) pass
def _executeZenModelerCommand(self, zenmodelerOpts, *args): """ Execute zenmodeler and return result @param zenmodelerOpts: zenmodeler command-line options @type zenmodelerOpts: string @param REQUEST: Zope REQUEST object @type REQUEST: Zope REQUEST object @return: results of command @rtype: string """ zm = binPath('zenmodeler') zenmodelerCmd = [zm] zenmodelerCmd.extend(zenmodelerOpts) if zenmodelerOpts[3] != 'localhost': zenmodelerCmd.extend(['--hubhost', socket.getfqdn()]) zenmodelerCmd = ['/usr/bin/ssh', zenmodelerOpts[3]] + zenmodelerCmd if len(args) == 3: background, REQUEST, write = args if background: log.info('queued job: %s', " ".join(zenmodelerCmd)) from Products.Jobber.jobs import SubprocessJob result = self.dmd.JobManager.addJob(SubprocessJob, zenmodelerCmd) else: result = executeCommand(zenmodelerCmd, REQUEST, write) else: result = executeCommand(zenmodelerCmd, args[0]) return result
def test_install_upgrade_yaml(self): """ install it a second time, with a different yaml file that simulates adding a new monitoring template """ cmd = [binPath('zenpack'), "--link", "--install", self.zenpack_path] out = self.get_cmd_success(cmd, vars={'ZPL_YAML_FILENAME': 'yes'})
def discoverDevices(self, uid): """ Discover devices on input subnetwork """ ip = '/'.join(self._dmd.restrictedTraverse(uid).getPrimaryPath()[4:]) orgroot = self._root.restrictedTraverse(uid).getNetworkRoot() organizer = orgroot.getOrganizer(ip) if organizer is None: log.error("Couldn't obtain a network entry for '%s' " "-- does it exist?" % ip) return False zDiscCommand = getattr(organizer, "zZenDiscCommand", None) if zDiscCommand: from Products.ZenUtils.ZenTales import talesEval cmd = talesEval('string:' + zDiscCommand, organizer).split(" ") else: cmd = ["zendisc", "run", "--net", organizer.getNetworkName()] if getattr(organizer, "zSnmpStrictDiscovery", False): cmd += ["--snmp-strict-discovery"] if getattr(organizer, "zPreferSnmpNaming", False): cmd += ["--prefer-snmp-naming"] zd = binPath('zendisc') zendiscCmd = [zd] + cmd[1:] return self._dmd.JobManager.addJob( SubprocessJob, description="Discover devices in network %s" % organizer.getNetworkName(), args=(zendiscCmd, ))
def getCommand(self, context, cmd=None): ''' generate the plugin command ''' if self.cmdFile is not None: # this uses an external script cmd = binPath(self.cmdFile) if self.check_file(cmd) is False: cmd = self.cmdFile props = getattr(context,'_properties') data = self.getData(props) parts = [cmd] + self.evalArgs(context, data) + self.addArgs(context, data) cmd = ' '.join(parts) cmd = RRDDataSource.getCommand(self, context, cmd) return cmd else: if cmd is None: cmd = self.commandTemplate if len(cmd) == 0: cmd = self.command compiled = self.getTALES(cmd) d = context.device() environ = {'dev' : d, 'device': d, 'devname': d.id, 'ds': self, 'datasource': self, 'here' : context, 'zCommandPath' : context.zCommandPath, 'nothing' : None, 'now' : DateTime() } res = compiled(getEngine().getContext(environ)) if isinstance(res, Exception): raise res return res
def _executeZenModelerCommand(self, zenmodelerOpts, *args): """ Execute zenmodeler and return result @param zenmodelerOpts: zenmodeler command-line options @type zenmodelerOpts: string @param REQUEST: Zope REQUEST object @type REQUEST: Zope REQUEST object @return: results of command @rtype: string """ zm = binPath("zenmodeler") zenmodelerCmd = [zm] zenmodelerCmd.extend(zenmodelerOpts) if zenmodelerOpts[3] != "localhost": zenmodelerCmd.extend(["--hubhost", socket.getfqdn()]) zenmodelerCmd = ["/usr/bin/ssh", zenmodelerOpts[3]] + zenmodelerCmd if len(args) == 3: background, REQUEST, write = args if background: # log.info('queued job: %s', " ".join(zenmodelerCmd)) result = self.dmd.JobManager.addJob(ShellCommandJob, zenmodelerCmd) else: result = executeCommand(zenmodelerCmd, REQUEST, write) else: result = executeCommand(zenmodelerCmd, args[0]) return result
def addMibPackage(self, package, organizer): args = [binPath('zenmib'), 'run', package, '--path=%s' % organizer] jobStatus = self._dmd.JobManager.addJob( SubprocessJob, description="Add MIB package %s" % package, kwargs=dict(cmd=args)) return jobStatus
def _executeZenModelerCommand( self, zenmodelerOpts, background=False, REQUEST=None, write=None): """ Execute zenmodeler and return result @param zenmodelerOpts: zenmodeler command-line options @type zenmodelerOpts: string @param REQUEST: Zope REQUEST object @type REQUEST: Zope REQUEST object @return: results of command @rtype: string """ zm = binPath('zenmodeler') zenmodelerCmd = [zm] zenmodelerCmd.extend(zenmodelerOpts) if background: log.info('queued job: %s', " ".join(zenmodelerCmd)) result = self.dmd.JobManager.addJob( SubprocessJob, description="Run zenmodeler %s" % ' '.join(zenmodelerOpts), args=(zenmodelerCmd,) ) else: result = executeCommand(zenmodelerCmd, REQUEST, write) return result
def discoverDevices(self, uid): """ Discover devices on input subnetwork """ ip = '/'.join(self._dmd.restrictedTraverse(uid).getPrimaryPath()[4:]) orgroot = self._root.restrictedTraverse(uid).getNetworkRoot() organizer = orgroot.getOrganizer(ip) if organizer is None: log.error("Couldn't obtain a network entry for '%s' " "-- does it exist?" % ip) return False zDiscCommand = getattr(organizer, "zZenDiscCommand", None) if zDiscCommand: from Products.ZenUtils.ZenTales import talesEval cmd = talesEval('string:' + zDiscCommand, organizer).split(" ") else: cmd = ["zendisc", "run", "--net", organizer.getNetworkName()] if getattr(organizer, "zSnmpStrictDiscovery", False): cmd += ["--snmp-strict-discovery"] if getattr(organizer, "zPreferSnmpNaming", False): cmd += ["--prefer-snmp-naming"] zd = binPath('zendisc') zendiscCmd = [zd] + cmd[1:] return self._dmd.JobManager.addJob(SubprocessJob, description="Discover devices in network %s" % organizer.getNetworkName(), args=(zendiscCmd,))
def getCommand(self, context): parts = [binPath('check_http')] if self.hostname: parts.append('-H %s' % self.hostname) if self.ipAddress: parts.append('-I %s' % self.ipAddress) if self.port: parts.append('-p %s' % self.port) if self.timeout: parts.append('-t %s' % self.timeout) if self.useSsl: parts.append('-S') if self.url: parts.append('-u %s' % self.url) if self.regex: if self.caseSensitive: parts.append("-r '%s'" % self.regex) else: parts.append("-R '%s'" % self.regex) if self.invert: parts.append('--invert-regex') if self.basicAuthUser or self.basicAuthPass: parts.append('-a %s:%s' % (self.basicAuthUser, self.basicAuthPass)) if self.onRedirect: parts.append('-f %s' % self.onRedirect) if self.proxyAuthUser and self.proxyAuthPassword: parts.append("-b '%s:%s'" % (self.proxyAuthUser, self.proxyAuthPassword)) cmd = ' '.join(parts) cmd = RRDDataSource.RRDDataSource.getCommand(self, context, cmd) return cmd
def getCommand(self, context): parts = [binPath('check_ftp')] if self.hostname: parts.append('-H %s' % self.hostname) if self.port: parts.append('-p %s' % self.port) if self.timeout: parts.append('-t %s' % self.timeout) if self.warning: parts.append('-w %s' % self.warning) if self.critical: parts.append('-c %s' % self.critical) if self.sendString: parts.append('-s %s' % self.sendString) if self.expectString: parts.append('-e %s' % self.expectString) if self.quitString: parts.append('-q %s' % self.quitString) if self.refuse: parts.append('-r %s' % self.refuse) if self.mismatch: parts.append('-M %s' % self.mismatch) if self.maxBytes: parts.append('-m %s' % self.maxBytes) if self.delay: parts.append('-d %s' % self.delay) if self.certificate: parts.append('-D %s' % self.certificate) if self.useSSL: parts.append('-S %s' % self.useSSL) cmd = ' '.join(parts) cmd = RRDDataSource.RRDDataSource.getCommand(self, context, cmd) return cmd
def addMibPackage(self, package, organizer): args = [binPath('zenmib'), 'run', package, '--path=%s' % organizer] jobStatus = self._dmd.JobManager.addJob(SubprocessJob, description="Add MIB package %s" % package, kwargs=dict(cmd=args)) return jobStatus
def cutover(self, dmd): import os from Products.ZenUtils.Utils import binPath os.system('%s stop >/dev/null 2>&1' % binPath('zenwinmodeler')) conn = dmd.ZenEventManager.connect() curr = conn.cursor() curr.execute("delete from heartbeat where component = 'zenwinmodeler'")
def getProcessList(self, deviceGuid): if deviceGuid and len(deviceGuid) > 0: s = '' try: import subprocess from Products.ZenUtils.Utils import binPath device = IGUIDManager(self._dmd).getObject(deviceGuid) s = '# ' + device.id zenmodelerOpts = [ 'run', '--now', '--debug', '-v10', '-d', device.id ] isPerfMonRemote = False zenmodelerName = 'zenmodeler' zenmodelerPath = binPath(zenmodelerName) monitorId = device.perfServer().id if monitorId != 'localhost': isPerfMonRemote = True if isPerfMonRemote: cmd = 'zminion --minion-name zminion_%s run -- "%s %s"' % ( device.getPerformanceServerName(), zenmodelerName, ' '.join(zenmodelerOpts)) else: cmd = "%s %s" % (zenmodelerPath, ' '.join(zenmodelerOpts)) processList = subprocess.check_output( cmd, shell=True, stderr=subprocess.STDOUT).splitlines() filterProcessLine = re.compile( 'DEBUG zen\.osprocessmatcher: COMMAND LINE: (?P<process>.*)$' ) for processListLine in processList: m = filterProcessLine.search(processListLine) if m: s += '\n' + m.group('process') except Exception, e: s += '\n# ' + str(e) yield {'uid': '0', 'process': s}
def run(self, r): transaction.commit() log = self.getStatus().getLog() # Store zProperties on the job if self.zProperties: self.getStatus().setZProperties(**self.zProperties) transaction.commit() # Build the zendisc command cmd = [binPath('zendisc')] cmd.extend(['run', '--now', '--monitor', 'localhost', '--deviceclass', '/Discovered', '--parallel', '8', '--job', self.getUid() ]) if not self.nets and not self.ranges: # Gotta have something log.write("ERROR: Must pass in a network or a range.") self.finished(FAILURE) elif self.nets and self.ranges: # Can't have both log.write("ERROR: Must pass in either networks or ranges, " "not both.") self.finished(FAILURE) else: if self.nets: for net in self.nets: cmd.extend(['--net', net]) elif self.ranges: for iprange in self.ranges: cmd.extend(['--range', iprange]) self.cmd = cmd super(AutoDiscoveryJob, self).run(r)
def test_upgrade(self): cmd = [binPath('zenpack'), "--link", "--install", self.zenpack_path] LOG.info(" ".join(cmd)) p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE) out, err = p.communicate() p.wait() LOG.debug("out=%s, err=%s", out, err) self.assertIs( p.returncode, 0, 'Error installing %s zenpack: %s' % (self.zenpack_path, err)) # install it a second time. Basically a do-nothign upgrade. LOG.info(" ".join(cmd)) p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE) out, err = p.communicate() p.wait() LOG.debug("out=%s, err=%s", out, err) self.assertIs( p.returncode, 0, 'Error upgrading %s zenpack: %s' % (self.zenpack_name, err)) pass
def getCommand(self, context): # Check if a rpc service is registered and running using # rpcinfo -H host -C rpc_command # # Usage: # check_rpc -H host -C rpc_command [-p port] [-c program_version] [-u|-t] [-v] # check_rpc [-h | --help] # check_rpc [-V | --version] # # <host> The server providing the rpc service # <rpc_command> The program na # [-v] Verbose # [-v -v] Verbose - will print s parts = [binPath('check_rpc')] if self.rpcServer: parts.append('-H %s' % self.rpcServer) if self.rpcCommand: parts.append('-C %s' % self.rpcCommand) if self.port: parts.append('-p %d' % self.port) if self.protocol == 'TCP': parts.append('-t') else: parts.append('-u') cmd = ' '.join(parts) cmd = RRDDataSource.RRDDataSource.getCommand(self, context, cmd) return cmd
def _executeZenModelerCommand(self, zenmodelerOpts, *args): """ Execute zenmodeler and return result @param zenmodelerOpts: zenmodeler command-line options @type zenmodelerOpts: string @param REQUEST: Zope REQUEST object @type REQUEST: Zope REQUEST object @return: results of command @rtype: string """ zm = binPath('zenmodeler') zenmodelerCmd = [zm] zenmodelerCmd.extend(zenmodelerOpts) if zenmodelerOpts[3] != 'localhost': zenmodelerCmd.extend(['--hubhost', socket.getfqdn()]) zenmodelerCmd = ['/usr/bin/ssh', zenmodelerOpts[3]] + zenmodelerCmd if len(args) == 3: background, REQUEST, write = args if background: # log.info('queued job: %s', " ".join(zenmodelerCmd)) if 'SubprocessJob' in locals(): log.info('queued job: %s', " ".join(zenmodelerCmd)) result = self.dmd.JobManager.addJob(SubprocessJob, description="Run zenmodeler %s" % ' '.join(zenmodelerOpts), args=(zenmodelerCmd,)) else: result = self.dmd.JobManager.addJob(ShellCommandJob,zenmodelerCmd) else: result = executeCommand(zenmodelerCmd, REQUEST, write) else: result = executeCommand(zenmodelerCmd, args[0]) return result
def _executeZenModelerCommand(self, zenmodelerOpts, background=False, REQUEST=None, write=None): """ Execute zenmodeler and return result @param zenmodelerOpts: zenmodeler command-line options @type zenmodelerOpts: string @param REQUEST: Zope REQUEST object @type REQUEST: Zope REQUEST object @return: results of command @rtype: string """ zm = binPath('zenmodeler') zenmodelerCmd = [zm] zenmodelerCmd.extend(zenmodelerOpts) if background: log.info('queued job: %s', " ".join(zenmodelerCmd)) result = self.dmd.JobManager.addJob( SubprocessJob, description="Run zenmodeler %s" % ' '.join(zenmodelerOpts), args=(zenmodelerCmd, )) else: result = executeCommand(zenmodelerCmd, REQUEST, write) return result
def InstallEgg(dmd, eggPath, link=False): """ Install the given egg and add to the current working set. This does not install the egg as a ZenPack. Return a list of distributions that should be installed as ZenPacks. """ eggPath = os.path.abspath(eggPath) zenPackDir = zenPath('ZenPacks') # Make sure $ZENHOME/ZenPacks exists CreateZenPacksDir() # Install the egg if link: zenPackDir = varPath('ZenPacks') cmd = ('%s setup.py develop ' % binPath('python') + '--site-dirs=%s ' % zenPackDir + '-d %s' % zenPackDir) returncode, out, err = None, '', '' for attempt in range(3): p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True, cwd=eggPath) out, err = p.communicate() p.wait() returncode = p.returncode if returncode: log.info("Error installing the egg (%s): %s" % (returncode, err)) try: DoEasyUninstall(eggPath) except: pass else: break if returncode: raise ZenPackException('Error installing the egg (%s): %s' % (returncode, err)) zpDists = AddDistToWorkingSet(eggPath) else: try: zpDists = DoEasyInstall(eggPath) except: DoEasyUninstall(eggPath) raise # cmd = 'easy_install --always-unzip --site-dirs=%s -d %s %s' % ( # zenPackDir, # zenPackDir, # eggPath) # p = subprocess.Popen(cmd, # stdout=subprocess.PIPE, # stderr=subprocess.PIPE, # shell=True) # p.wait() # eggName = os.path.split(eggPath)[1] # eggPath = os.path.join(zenPackDir, eggName) return zpDists
def InstallEgg(dmd, eggPath, link=False): """ Install the given egg and add to the current working set. This does not install the egg as a ZenPack. Return a list of distributions that should be installed as ZenPacks. """ eggPath = os.path.abspath(eggPath) zenPackDir = zenPath('ZenPacks') # Make sure $ZENHOME/ZenPacks exists CreateZenPacksDir() # Install the egg if link: zenPackDir = varPath('ZenPacks') cmd = ('%s setup.py develop ' % binPath('python') + '--site-dirs=%s ' % zenPackDir + '-d %s' % zenPackDir) returncode, out, err = None, '', '' for attempt in range(3): p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True, cwd=eggPath) out, err = p.communicate() p.wait() returncode = p.returncode if returncode: log.info("Error installing the egg (%s): %s" % (returncode, err)) try: DoEasyUninstall(eggPath) except Exception: pass else: break if returncode: raise ZenPackException('Error installing the egg (%s): %s' % (returncode, err)) zpDists = AddDistToWorkingSet(eggPath) else: try: zpDists = DoEasyInstall(eggPath) except Exception: DoEasyUninstall(eggPath) raise # cmd = 'easy_install --always-unzip --site-dirs=%s -d %s %s' % ( # zenPackDir, # zenPackDir, # eggPath) # p = subprocess.Popen(cmd, # stdout=subprocess.PIPE, # stderr=subprocess.PIPE, # shell=True) # p.wait() # eggName = os.path.split(eggPath)[1] # eggPath = os.path.join(zenPackDir, eggName) return zpDists
def _getDaemonList(self): """ Get the list of supported Zenoss daemons. """ masterScript = binPath('zenoss') daemons = [] for line in os.popen("%s list" % masterScript).readlines(): if 'zenrrdcache' not in line: daemons.append(line.strip()) return daemons
def _getZenModelerCommand( self, deviceName, performanceMonitor, REQUEST=None): zm = binPath('zenmodeler') cmd = [zm] options = [ 'run', '--now', '-d', deviceName, '--monitor', performanceMonitor ] cmd.extend(options) log.info('local zenmodelerCmd is "%s"' % ' '.join(cmd)) return cmd
def manage_removeZenPacks(self, ids=(), REQUEST=None): """ Uninstall the given zenpacks. Uninstall the zenpack egg. If not in development mode then also delete the egg from the filesystem. """ import Products.ZenUtils.ZenPackCmd as ZenPackCmd # avoid circular imports from Products.ZenMessaging.queuemessaging.schema import removeZenPackQueuesExchanges # see ZEN-2682 only allow one zenpack to be removed at a time. This is because you # can select a zenpack and its dependent. If the dependent is removed first # you will get an error removing the zenpack if len(ids) > 1: msg = 'You can only remove one zenpack at a time.' if REQUEST: messaging.IMessageSender(self).sendToBrowser( 'Error', msg, priority=messaging.WARNING) return self.callZenScreen(REQUEST) raise ZenPackDependentsException(msg) if not getattr(self.dmd, 'ZenPackManager'): msg = 'Your Zenoss database appears to be out of date. Try ' \ 'running zenmigrate to update.' if REQUEST: messaging.IMessageSender(self).sendToBrowser( 'Error', msg, priority=messaging.WARNING) return self.callZenScreen(REQUEST) from ZenPack import ZenPackNeedMigrateException raise ZenPackNeedMigrateException(msg) canRemove, dependents = ZenPackCmd.CanRemoveZenPacks(self.dmd, ids) if not canRemove: msg = 'The following ZenPacks depend on one or more of the ' + \ ' ZenPacks you are trying to remove: %s' % ','.join(dependents) if REQUEST: messaging.IMessageSender(self).sendToBrowser( 'Error', msg, priority=messaging.WARNING) return self.callZenScreen(REQUEST) from ZenPack import ZenPackDependentsException raise ZenPackDependentsException(msg) for zpId in ids: zp = self.packs._getOb(zpId, None) if zp: if zp.isEggPack(): ZenPackCmd.RemoveZenPack(self.dmd, zpId, skipDepsCheck=True) audit('UI.ZenPack.Remove', zpId) else: os.system('%s --remove %s' % (binPath('zenpack'), zpId)) self._p_jar.sync() removeZenPackQueuesExchanges(zp.path()) if REQUEST: return self.callZenScreen(REQUEST)
def getCommand(self, context): parts = [binPath('check_dns')] if self.hostname: parts.append('-H "%s"' % self.hostname) if self.dnsServer: parts.append('-s "%s"' % self.dnsServer) if self.expectedIpAddress: parts.append('-a %s' % self.expectedIpAddress) cmd = ' '.join(parts) cmd = RRDDataSource.RRDDataSource.getCommand(self, context, cmd) return cmd
def manage_removeZenPacks(self, ids=(), REQUEST=None): """ Uninstall the given zenpacks. Uninstall the zenpack egg. If not in development mode then also delete the egg from the filesystem. """ import Products.ZenUtils.ZenPackCmd as ZenPackCmd # avoid circular imports from Products.ZenMessaging.queuemessaging.schema import removeZenPackQueuesExchanges # see ZEN-2682 only allow one zenpack to be removed at a time. This is because you # can select a zenpack and its dependent. If the dependent is removed first # you will get an error removing the zenpack if len(ids) > 1: msg = "You can only remove one zenpack at a time." if REQUEST: messaging.IMessageSender(self).sendToBrowser("Error", msg, priority=messaging.WARNING) return self.callZenScreen(REQUEST) raise ZenPackDependentsException(msg) if not getattr(self.dmd, "ZenPackManager"): msg = "Your Zenoss database appears to be out of date. Try " "running zenmigrate to update." if REQUEST: messaging.IMessageSender(self).sendToBrowser("Error", msg, priority=messaging.WARNING) return self.callZenScreen(REQUEST) from ZenPack import ZenPackNeedMigrateException raise ZenPackNeedMigrateException(msg) canRemove, dependents = ZenPackCmd.CanRemoveZenPacks(self.dmd, ids) if not canRemove: msg = ( "The following ZenPacks depend on one or more of the " + " ZenPacks you are trying to remove: %s" % ",".join(dependents) ) if REQUEST: messaging.IMessageSender(self).sendToBrowser("Error", msg, priority=messaging.WARNING) return self.callZenScreen(REQUEST) from ZenPack import ZenPackDependentsException raise ZenPackDependentsException(msg) for zpId in ids: zp = self.packs._getOb(zpId, None) if zp: if zp.isEggPack(): ZenPackCmd.RemoveZenPack(self.dmd, zpId, skipDepsCheck=True) audit("UI.ZenPack.Remove", zpId) else: os.system("%s --remove %s" % (binPath("zenpack"), zpId)) self._p_jar.sync() removeZenPackQueuesExchanges(zp.path()) if REQUEST: return self.callZenScreen(REQUEST)
def test_install(self): cmd = [binPath('zenpack'), "--link", "--install", self.zenpack_path] LOG.info(" ".join(cmd)) p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE) out, err = p.communicate() p.wait() LOG.debug("out=%s, err=%s", out, err) self.assertIs(p.returncode, 0, 'Error installing %s zenpack: %s' % (self.zenpack_name, err))
def _getZenModelerCommand(self, deviceName, performanceMonitor, REQUEST=None): zm = binPath('zenmodeler') cmd = [zm] options = [ 'run', '--now', '-d', deviceName, '--monitor', performanceMonitor ] cmd.extend(options) log.info('local zenmodelerCmd is "%s"' % ' '.join(cmd)) return cmd
def _getZenModelerCommand( self, deviceName, performanceMonitor, collectPlugins='', REQUEST=None): zm = binPath('zenmodeler') cmd = [zm] deviceName = self._escapeParentheses(deviceName) options = [ 'run', '--now', '-d', deviceName, '--monitor', performanceMonitor, '--collect={}'.format(collectPlugins) ] cmd.extend(options) log.info('local zenmodelerCmd is "%s"' % ' '.join(cmd)) return cmd
def _genConfFile(self, pack): """ Attempt to generate a conf file for any daemons. Wait for completion. """ try: p = subprocess.Popen(binPath('create_sample_config.sh'), stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=pack.path()) p.wait() except OSError: pass
def show_daemon_xml_configs(self, daemon, REQUEST=None ): """ Display the daemon configuration options in an XML format. Merges the defaults with options in the config file. """ # Sanity check if not daemon or daemon == '': messaging.IMessageSender(self).sendToBrowser( 'Internal Error', 'Called without a daemon name', priority=messaging.WARNING ) return [] if daemon in [ 'zeoctl', 'zopectl', 'zeneventserver', 'zredis' ]: return [] # sanitize the input if daemon not in self._getDaemonList(): return [] if not self.isValidDaemon(daemon): messaging.IMessageSender(self).sendToBrowser( 'Internal Error', '%s is not a valid daemon name' % daemon, priority=messaging.WARNING ) return [] xml_default_name = zenPath( "etc", daemon + ".xml" ) try: # Always recreate the defaults file in order to avoid caching issues log.debug("Creating XML config file for %s" % daemon) make_xml = ' '.join([binPath(daemon), "genxmlconfigs", ">", xml_default_name]) proc = Popen(make_xml, shell=True, stdout=PIPE, stderr=PIPE) output, errors = proc.communicate() proc.wait() if proc.returncode != 0: log.error(errors) messaging.IMessageSender(self).sendToBrowser( 'Internal Error', errors, priority=messaging.CRITICAL ) return [["Output", output, errors, make_xml, "string"]] except Exception, ex: msg = "Unable to execute '%s'\noutput='%s'\nerrors='%s'\nex=%s" % ( make_xml, output, errors, ex) log.error(msg) messaging.IMessageSender(self).sendToBrowser( 'Internal Error', msg, priority=messaging.CRITICAL ) return [["Error in command", output, errors, make_xml, "string"]]
def getCommand(self, context): parts = [binPath('check_jabber')] if self.hostname: parts.append('-H %s' % self.hostname) if self.port: parts.append('-p %s' % self.port) if self.sendString: parts.append('-s %s ' % safeQuote(self.sendString)) if self.expectString: parts.append('-e %s ' % safeQuote(self.expectString)) cmd = ' '.join(parts) cmd = RRDDataSource.RRDDataSource.getCommand(self, context, cmd) return cmd
def getCommand(self, context): parts = [binPath('check_jabber')] if self.hostname: parts.append('-H %s' % self.hostname) if self.port: parts.append('-p %s' % self.port) if self.sendString: parts.append('-s %s ' % safeQuote( self.sendString ) ) if self.expectString: parts.append('-e %s ' % safeQuote( self.expectString ) ) cmd = ' '.join(parts) cmd = RRDDataSource.RRDDataSource.getCommand(self, context, cmd) return cmd
def getCommand(self, context): parts = [binPath('check_ntp')] if self.hostname: parts.append('-H %s' % self.hostname) if self.timeout: parts.append('-t %s' % self.timeout) if self.warning: parts.append('-w %s' % self.warning) if self.critical: parts.append('-c %s' % self.critical) cmd = ' '.join(parts) cmd = RRDDataSource.RRDDataSource.getCommand(self, context, cmd) return cmd
def _getZenDiscCommand(self, deviceName, devicePath, performanceMonitor, REQUEST=None): zm = binPath("zendisc") zendiscCmd = [zm] zendiscOptions = ["run", "--now", "-d", deviceName, "--monitor", performanceMonitor, "--deviceclass", devicePath] if REQUEST: zendiscOptions.append("--weblog") zendiscCmd.extend(zendiscOptions) if performanceMonitor != "localhost": zendiscCmd.extend(["--hubhost", socket.getfqdn()]) zendiscCmd = ["/usr/bin/ssh", performanceMonitor] + zendiscCmd # log.info('local zendiscCmd is "%s"' % ' '.join(zendiscCmd)) return zendiscCmd
def _getZenDiscCommand(self, deviceName, devicePath, performanceMonitor, productionState, REQUEST=None): zm = binPath('zendisc') zendiscCmd = [zm] zendiscOptions = ['run', '--now','-d', deviceName, '--monitor', performanceMonitor, '--deviceclass', devicePath, '--prod_state', str(productionState)] if REQUEST: zendiscOptions.append("--weblog") zendiscCmd.extend(zendiscOptions) log.info('local zendiscCmd is "%s"' % ' '.join(zendiscCmd)) return zendiscCmd
def getCommand(self, context): if self.useSSL: parts = [binPath('check_ldaps')] else: parts = [binPath('check_ldap')] if self.ldapServer: parts.append('-H %s' % self.ldapServer) if self.ldapBaseDN: parts.append('-b %s' % self.ldapBaseDN) if self.ldapBindDN: parts.append('-D "%s"' % self.ldapBindDN) if self.ldapBindPassword: parts.append('-P "%s"' % self.ldapBindPassword) if self.ldapBindVersion: parts.append('--ver%s' % str(self.ldapBindVersion)) if self.port: parts.append('-p %s' % self.port) if self.timeout: parts.append('-t %s' % self.timeout) cmd = ' '.join(parts) cmd = RRDDataSource.RRDDataSource.getCommand(self, context, cmd) return cmd
def setUp(self): cmd = [binPath('zenpack'), "--list"] LOG.info(" ".join(cmd)) p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE) out, err = p.communicate() p.wait() LOG.debug("out=%s, err=%s", out, err) self.assertIs(p.returncode, 0, 'Error listing installed zenpacks: %s' % err) if self.zenpack_name in out: cmd = [binPath('zenpack'), "--remove", self.zenpack_name] LOG.info(" ".join(cmd)) p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE) out, err = p.communicate() p.wait() LOG.debug("out=%s, err=%s", out, err) self.assertIs(p.returncode, 0, 'Error removing %s zenpack: %s' % (self.zenpack_name, err))
def openPrivilegedPort(self, *address): """ Execute under zensocket, providing the args to zensocket """ socketOptions = [] for optString in set(self.options.socketOption): arg = self.convertSocketOption(optString) if arg: socketOptions.append(arg) zensocket = binPath('zensocket') cmd = [zensocket, zensocket] + list(address) + socketOptions \ + ['--', sys.executable] + sys.argv \ + ['--useFileDescriptor=$privilegedSocket'] self.log.debug(cmd) os.execlp(*cmd)
def _getZenModelerCommand(self, deviceName, performanceMonitor, collectPlugins='', REQUEST=None): zm = binPath('zenmodeler') cmd = [zm] deviceName = self._escapeParentheses(deviceName) options = [ 'run', '--now', '-d', deviceName, '--monitor', performanceMonitor, '--collect={}'.format(collectPlugins) ] cmd.extend(options) log.info('local zenmodelerCmd is "%s"' % ' '.join(cmd)) return cmd
def test_getCommand(self): ds = LDAPMonitorDataSource(None) context = lambda: 0 dev = lambda: 0 dev.id = 'adsf' context.device = lambda: dev context.zCommandPath = 'adsf' context.zLDAPBaseDN = 'DN=base' context.zLDAPBindDN = 'DN=bind' context.zLDAPBindPassword = '******' res = ds.getCommand(context) self.assertEquals(res, binPath('check_ldap') + ' -H adsf -b DN=base -D "DN=bind" -P "password" --ver2 -p 389 -t 60' )
def getCommand(self, context): parts = [binPath('check_dig')] if self.dnsServer: parts.append('-H %s' % self.dnsServer) if self.port: parts.append('-p %d' % self.port) if self.recordName: parts.append('-l %s' % self.recordName) if self.recordType: parts.append('-T %s' % self.recordType) if self.timeout: parts.append('-t %d' % self.timeout) cmd = ' '.join(parts) cmd = RRDDataSource.RRDDataSource.getCommand(self, context, cmd) return cmd
def _getZenDiscCommand(self, deviceName, devicePath, performanceMonitor, REQUEST=None): zm = binPath('zendisc') zendiscCmd = [zm] zendiscOptions = ['run', '--now','-d', deviceName, '--monitor', performanceMonitor, '--deviceclass', devicePath] if REQUEST: zendiscOptions.append("--weblog") zendiscCmd.extend(zendiscOptions) if performanceMonitor != 'localhost': zendiscCmd.extend(['--hubhost', socket.getfqdn()]) zendiscCmd = ['/usr/bin/ssh', performanceMonitor] + zendiscCmd # log.info('local zendiscCmd is "%s"' % ' '.join(zendiscCmd)) return zendiscCmd