def _doCCLogin(self): """ The daemons page makes calls to logstash's elasticsearch, which is protected via CC credentials. This is a helper method to authenticate with CC, and set a cookie in the user's browser. """ cpClient = ControlPlaneClient(**getConnectionSettings()) self.cc_version = cpClient.cc_version cookies = None try: cookies = cpClient.cookies() except Exception as e: log.warn( 'Unable to log into Control Center, log viewing functionality may be impacted' ) return for cookie in cookies: self.request.response.setCookie( name=cookie['name'], value=cookie['value'], quoted=True, domain=self.request.environ['HTTP_HOST'].split(':') [0], # Don't include the port path='/', secure=cookie['secure'])
def migrate(self, pack): if pack.prevZenPackVersion is None: # Do nothing if this is a fresh install of self.version. return if not CONTROL_CENTER: return sm.require("1.0.0") try: ctx = sm.ServiceContext() except Exception as e: LOG.warn("failed to replace %s service: %s", SERVICE_NAME, e) return service = get_service_id(ctx) if not service: return client = ControlPlaneClient(**getConnectionSettings()) # Stop and remove the old service. remove_service(client, service) # Install the new service. pack.installServices()
def zenopenstack_url(self, https=False): try: from Products.ZenUtils.controlplane.application import getConnectionSettings from Products.ZenUtils.controlplane import ControlPlaneClient except ImportError: return if https: protocol = "https" endpoint_name = "proxy-zenopenstack_https" else: protocol = "http" endpoint_name = "proxy-zenopenstack_http" collector = self.perfServer().id client = ControlPlaneClient(**getConnectionSettings()) for svc_id in [x.id for x in client.queryServices() if x.name == 'proxy-zenopenstack']: svc = client.getService(svc_id) for endpoint in filter(lambda s: s['Name'] == endpoint_name, svc.getRawData()['Endpoints']): try: if endpoint['AddressAssignment']['IPAddr'] is None or endpoint['AddressAssignment']['IPAddr'] == "": continue if endpoint['AddressAssignment']['Port'] is None or int(endpoint['AddressAssignment']['Port']) == 0: continue if client.getService(svc.parentId).name == collector: return "{protocol}://{ip}:{port}".format( protocol=protocol, ip=endpoint['AddressAssignment']['IPAddr'], port=endpoint['AddressAssignment']['Port']) except Exception: # no ip assignment or error determining what collector this is. pass
def __init__(self, filename=None): """ Initializes the ServiceContext. Input precedence is: 1. The filename argument passed to this function. 2. The MIGRATE_INPUTFILE, which is an environment variable indicating the path to a json-formatted file containing the services to load. 3. Acquisition of the services from serviced via the ZenUtils library. If 1 is not available, 2 will be used. If 1 & 2 are not available, 3 will be used. If none are available, an error will be thrown. Requires that servicemigration.require() has been called. """ infile = None if filename is not None: infile = filename else: infile = os.environ["MIGRATE_INPUTFILE"] if "MIGRATE_INPUTFILE" in os.environ else None if ZenUtils: self._client = ControlPlaneClient(**getConnectionSettings()) else: self._client = None if infile is not None: data = json.loads(open(infile, 'r').read()) elif ZenUtils and "CONTROLPLANE_TENANT_ID" in os.environ: data = self._client.getServicesForMigration(os.environ["CONTROLPLANE_TENANT_ID"]) else: raise exceptions.ServiceMigrationError("Can't find migration input data.") self.services = [] self.__deploy = [] if type(data) is dict: # Handle the case wherein we are reading from SDK output. for datum in data["Modified"]: self.services.append(service.deserialize(datum)) for datum in data["Added"]: self.services.append(service.deserialize(datum)) for datum in data["Deploy"]: self.__deploy.append(datum) elif type(data) is list: # Handle the case wherein we are reading from Serviced output. for datum in data: self.services.append(service.deserialize(datum)) else: raise exceptions.ServiceMigrationError("Can't read migration input data.") if len(self.services) == 0: self.version = "" else: self.version = self.services[0]._Service__data["Version"]
def _doCCLogin(self): """ The daemons page makes calls to logstash's elasticsearch, which is protected via CC credentials. This is a helper method to authenticate with CC, and set a cookie in the user's browser. """ cpClient = ControlPlaneClient(**getConnectionSettings()) self.cc_version = cpClient.cc_version cookies = None try: cookies = cpClient.cookies() except Exception as e: log.warn('Unable to log into Control Center, log viewing functionality may be impacted') return for cookie in cookies: self.request.response.setCookie( name = cookie['name'], value = cookie['value'], quoted = True, domain = self.request.environ['HTTP_HOST'].split(':')[0], # Don't include the port path = '/', secure = cookie['secure'] )
def login(self): """ Perform a login. This actually logs us in to both zauth (so that we can use zproxy) and CC (so that we can hit elastic). Note that a new session is created here. """ self.session = requests.Session() gConf = globalConfToDict() # log into zauth if not (gConf.get('zauth-username', None) and gConf.get('zauth-password', None)): raise ElasticClientException( 'Unable to determine zauth credentials') resp = self.session.post(_ZPROXY_URL + _ZAUTH_LOGIN_URI, auth=(gConf['zauth-username'], gConf['zauth-password'])) if resp.status_code != 200: raise ElasticClientException('Unable to authenticate with zauth') if not resp.headers.get('X-Zauth-Tokenid', None): raise ElasticClientException( 'Did not recieve X-Zauth-Tokenid, cannot authenticate') self.session.headers['X-Zauth-Token'] = resp.headers['X-Zauth-Tokenid'] # log into CC (for elastic quesries) connSettings = getConnectionSettings() if not all(param in connSettings for param in ('user', 'password')): raise ElasticClientException( 'Unable to determine Control Center credentials') ccLoginBody = json.dumps({ 'username': connSettings['user'], 'password': connSettings['password'] }) self.session.verify = False resp = self.session.post(self.ccURL + _CC_LOGIN_URI, data=ccLoginBody) if resp.status_code != 200: raise ElasticClientException( 'Unable to authenticate with Control Center', resp)
script.connect() dmd = script.dmd except Exception, e: sys.exit("Unable to connect to ZODB: %s" % e) create_default_credentials(dmd) if not VERSION5: provision_user(dmd) rabbit_ip = {} if VERSION5: from Products.ZenUtils.controlplane.application import getConnectionSettings from Products.ZenUtils.controlplane import ControlPlaneClient client = ControlPlaneClient(**getConnectionSettings()) for svc_id in [x.id for x in client.queryServices() if x.name == 'RabbitMQ-Ceilometer']: svc = client.getService(svc_id) for ceil_endpoint in filter(lambda s: s['Name'] == 'rabbitmq_ceil', svc.getRawData()['Endpoints']): try: ip = ceil_endpoint['AddressAssignment']['IPAddr'] collector = client.getService(svc.parentId).name rabbit_ip[collector] = ip except Exception: # no ip assignment or error determining what collector this is. pass dc = dmd.getObjByPath("Devices/OpenStack/Infrastructure") transaction.commit()
def __init__(self, filename=None): """ Initializes the ServiceContext. Input precedence is: 1. The filename argument passed to this function. 2. The MIGRATE_INPUTFILE, which is an environment variable indicating the path to a json-formatted file containing the services to load. 3. Acquisition of the services from serviced via the ZenUtils library. If 1 is not available, 2 will be used. If 1 & 2 are not available, 3 will be used. If none are available, an error will be thrown. Requires that servicemigration.require() has been called. """ infile = None if filename is not None: infile = filename else: infile = os.environ[ "MIGRATE_INPUTFILE"] if "MIGRATE_INPUTFILE" in os.environ else None if ZenUtils: self._client = ControlPlaneClient(**getConnectionSettings()) else: self._client = None if infile is not None: data = json.loads(open(infile, 'r').read()) elif ZenUtils and "CONTROLPLANE_TENANT_ID" in os.environ: data = self._client.getServicesForMigration( os.environ["CONTROLPLANE_TENANT_ID"]) else: raise exceptions.ServiceMigrationError( "Can't find migration input data.") def _addService(datum): svc = service.deserialize(datum) self.services.append(svc) self._original[datum["ID"]] = json.dumps(service.serialize(svc), sort_keys=True) self.services = [] self.__deploy = [] self.__logFilters = dict() self._dirty = set() self._original = dict() if type(data) is dict: # Handle the case wherein we are reading from SDK output. for datum in data["Modified"]: _addService(datum) self._dirty.add(datum["ID"]) for datum in data["Unmodified"]: _addService(datum) for datum in data["Added"]: _addService(datum) for datum in data["Deploy"]: self.__deploy.append(datum) self.__logFilters = data["LogFilters"] elif type(data) is list: # Handle the case wherein we are reading from Serviced output. for datum in data: _addService(datum) else: raise exceptions.ServiceMigrationError( "Can't read migration input data.") if len(self.services) == 0: self.version = "" else: self.version = self.services[0]._Service__data["Version"]