<commit_before>#!/usr/bin/python
#-*- coding: iso-8859-15 -*-
# INDUINO METEOSTATION
# http://induino.wordpress.com
#
# NACHO MAS 2013

import urllib
import tidy
import datetime,time
import locale
from PIL import Image
from string import upper
from meteollskyconfig import *

class uwyoClass:
    YEAR=""
    MONTH=""
    FROM=""
    def __init__(self):
        pass

    def __init__(self,date_time):
	self.set_date(date_time)

    def set_date(self,date_time):
        self.YEAR=datetime.datetime.strftime(date_time,"%Y")
        self.MONTH=datetime.datetime.strftime(date_time,"%m")
        if (date_time.hour >13):
	        self.FROM=datetime.datetime.strftime(date_time,"%d")+"12"
	else:
	        self.FROM=datetime.datetime.strftime(date_time,"%d")+"00"
	print self.YEAR,self.MONTH,self.FROM

    def get_sounding_skewt(self):
        data=urllib.urlencode({"region":"europe","TYPE":"GIF:SKEWT","YEAR":self.YEAR,"MONTH":self.MONTH,"FROM":self.FROM,"TO":self.FROM,"STNM":SOUNDINGSTATION})
        #print data
        s = urllib.urlopen("http://weather.uwyo.edu/cgi-bin/sounding?",data)
        o=s.read()
        s.close()
        document=tidy.parseString(o)
        urllib.urlretrieve("http://weather.uwyo.edu/upperair/images/"+self.YEAR+self.MONTH+self.FROM+".08221.skewt.gif", CHARTPATH+"skewt.gif")
        #print document

    def get_sounding_data(self):
        data=urllib.urlencode({"region":"europe","TYPE":"TEXT:LIST","YEAR":self.YEAR,"MONTH":self.MONTH,"FROM":self.FROM,"TO":self.FROM,"STNM":SOUNDINGSTATION})
        #print data
        s = urllib.urlopen("http://weather.uwyo.edu/cgi-bin/sounding?",data)
        o=s.read()
        s.close()
        document=tidy.parseString(o)
        fi=open(CHARTPATH+"sounding.html","w")
        fi.write(str(document))
        fi.close()

if __name__=='__main__':
   print "Starting internet data downloader"
   #try:
 	#print "Retriving SKEW-T diagrams from:",SOUNDINGSTATION
   #except:
	#print "NO sounding station define in meteoconfig.py"
	#exit(0)

   while (True):
        #today=datetime.datetime.utcnow()
        #s=uwyoClass(today)
	try:
	        #s.get_sounding_skewt()
        	#s.get_sounding_data()
		#urllib.urlretrieve(EUMETSAT_LAST, CHARTPATH+"meteosat.jpg")
                urllib.urlretrieve("https://www.gemini.edu/sciops/telescopes-and-sites/weather/cerro-pachon/cameras/img.png", CHARTPATH+"allsky_gemini.png")
                im = Image.open(CHARTPATH+"allsky_gemini.png")
                im.save("allsky_gemini.jpg")
	except:
		print "Fail to retrive internet data"
	#del s
	time.sleep(600)

<commit_msg>fix error save path jpg file<commit_after>#!/usr/bin/python
#-*- coding: iso-8859-15 -*-
# INDUINO METEOSTATION
# http://induino.wordpress.com
#
# NACHO MAS 2013

import urllib
import tidy
import datetime,time
import locale
from PIL import Image
from string import upper
from meteollskyconfig import *

class uwyoClass:
    YEAR=""
    MONTH=""
    FROM=""
    def __init__(self):
        pass

    def __init__(self,date_time):
	self.set_date(date_time)

    def set_date(self,date_time):
        self.YEAR=datetime.datetime.strftime(date_time,"%Y")
        self.MONTH=datetime.datetime.strftime(date_time,"%m")
        if (date_time.hour >13):
	        self.FROM=datetime.datetime.strftime(date_time,"%d")+"12"
	else:
	        self.FROM=datetime.datetime.strftime(date_time,"%d")+"00"
	print self.YEAR,self.MONTH,self.FROM

    def get_sounding_skewt(self):
        data=urllib.urlencode({"region":"europe","TYPE":"GIF:SKEWT","YEAR":self.YEAR,"MONTH":self.MONTH,"FROM":self.FROM,"TO":self.FROM,"STNM":SOUNDINGSTATION})
        #print data
        s = urllib.urlopen("http://weather.uwyo.edu/cgi-bin/sounding?",data)
        o=s.read()
        s.close()
        document=tidy.parseString(o)
        urllib.urlretrieve("http://weather.uwyo.edu/upperair/images/"+self.YEAR+self.MONTH+self.FROM+".08221.skewt.gif", CHARTPATH+"skewt.gif")
        #print document

    def get_sounding_data(self):
        data=urllib.urlencode({"region":"europe","TYPE":"TEXT:LIST","YEAR":self.YEAR,"MONTH":self.MONTH,"FROM":self.FROM,"TO":self.FROM,"STNM":SOUNDINGSTATION})
        #print data
        s = urllib.urlopen("http://weather.uwyo.edu/cgi-bin/sounding?",data)
        o=s.read()
        s.close()
        document=tidy.parseString(o)
        fi=open(CHARTPATH+"sounding.html","w")
        fi.write(str(document))
        fi.close()

if __name__=='__main__':
   print "Starting internet data downloader"
   #try:
 	#print "Retriving SKEW-T diagrams from:",SOUNDINGSTATION
   #except:
	#print "NO sounding station define in meteoconfig.py"
	#exit(0)

   while (True):
        #today=datetime.datetime.utcnow()
        #s=uwyoClass(today)
	try:
	        #s.get_sounding_skewt()
        	#s.get_sounding_data()
		#urllib.urlretrieve(EUMETSAT_LAST, CHARTPATH+"meteosat.jpg")
                urllib.urlretrieve("https://www.gemini.edu/sciops/telescopes-and-sites/weather/cerro-pachon/cameras/img.png", CHARTPATH+"allsky_gemini.png")
                im = Image.open(CHARTPATH+"allsky_gemini.png")
                im.save(CHARTPATH+"allsky_gemini.jpg")
	except:
		print "Fail to retrive internet data"
	#del s
	time.sleep(600)

<|endoftext|>


<commit_before>from matplotlib import pyplot as plt

__author__ = 'ronny'

# ==============================================================================
#                                                                    ARRAY2IMAGE
# ==============================================================================
def array2image(x, cmap="gray"):
    """
    Takes a 2D array and converts it to an image.

    :param x: {2D array}
        The 2D array to create an image from.
    :param cmap: {string} (default="gray")
        Colormap to use. This value is passed on to  matplotlib.pyplot.imshow()
        So whatever values are valid for that function can be used here.
        Some possible values:
            "gray"     = grayscale (default)
            "spectral" = reverse rainbow heatmap from black to VIBGYOR to white
            "hot"      = heatmap (black, red, yellow, white)
    """
    # ==========================================================================
    plt.figure()
    plt.imshow(x, cmap=cmap)

    plt.show()

<commit_msg>Add colorbar option in array2image()<commit_after>from matplotlib import pyplot as plt

__author__ = 'ronny'

# ==============================================================================
#                                                                    ARRAY2IMAGE
# ==============================================================================
def array2image(x, cmap="gray", colorbar=False):
    """
    Takes a 2D array and converts it to an image.

    :param x: {2D array}
        The 2D array to create an image from.
    :param cmap: {string} (default="gray")
        Colormap to use. This value is passed on to  matplotlib.pyplot.imshow()
        So whatever values are valid for that function can be used here.
        Some possible values:
            "gray"     = grayscale (default)
            "spectral" = reverse rainbow heatmap from black to VIBGYOR to white
            "hot"      = heatmap (black, red, yellow, white)
    :param colorbar: {boolean}(default=False)
        Should it display a colorbar to interpret values of the image colors?
    """
    # ==========================================================================
    plt.figure()
    plt.imshow(x, cmap=cmap)

    # Show a colorbar if it was asked for.
    if colorbar:
        plt.colorbar()

    plt.show()

<|endoftext|>


<commit_before># Copyright (c) 2010 Advanced Micro Devices, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met: redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer;
# redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution;
# neither the name of the copyright holders nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# Authors: Lisa Hsu

# Configure the M5 cache hierarchy config in one place
#

import m5
from m5.objects import *
from Caches import *
from O3_ARM_v7a import *

class L3Config(object):
    def __init__( self, options, system ):
        self.options = options
        self.system = system
        self.latencies = {
            '4096kB' : '8.48ns',
            '3072kB' : '7.5',
            '2048kB' : '6.5ns',
            '1792kB' : '6.5ns',
            '1536kB' : '6.5ns',
            '1280kB' : '6.5ns',
            '1024kB' : '6.5ns',
            '768kB'  : '6.5ns',
            '512kB'  : '6.5ns',
            '256kB'  : '6.5ns',
            '1920kB' : '6.5ns',
            '1664kB' : '6.5ns',
            '1408kB' : '6.5ns',
            '1152kB' : '6.5ns',
            '896kB' : '6.5ns',
            '640kB'  : '6.5ns',
            '384kB'  : '6.5ns',
            '128kB'  : '6.5ns',
            '1kB'    : '6.5ns',
        }

    def connect_l2( self ): return

class L3Shared( L3Config ):
    def __init__( self, options, system ):
        super( L3Shared, self ).__init__( options, system )
        system.l3 = L3Cache(size = options.l3_size,
                            latency=self.latencies[options.l3_size],
                            assoc = options.l3_assoc,
                            block_size=options.cacheline_size,
                            num_tcs = options.numpids,
                            c_dynamic_cache = options.c_dynamic_cache,
                            f_dynamic_cache = options.f_dynamic_cache,
                            static_cache = options.static_cache,
                            L_assoc = options.L_assoc,
                            H_min = options.H_min,
                            threshold_inc = options.th_inc,
                            threshold_dec = options.th_dec)

        # system.tol3bus = (
        #         RR_NoncoherentBus(num_pids = options.numpids,
        #                     save_trace = options.do_bus_trace,
        #                     bus_trace_file = options.l2l3bustracefile ,
        #                     req_tl = options.l2l3req_tl,
        #                     req_offset = options.l2l3req_offset,
        #                     resp_tl = options.l2l3resp_tl,
        #                     resp_offset = options.l2l3resp_offset) if options.rr_l2l3
        #         else NoncoherentBus()
        #         )
        system.tol3bus = NoncoherentBus()
        system.l3.cpu_side = system.tol3bus.master
        system.l3.mem_side = system.membus.slave

    def connect_l2( self ):
        for i in xrange( self.options.num_cpus ):
            self.system.l2[i].mem_side = self.system.tol3bus.slave

class L3Private( L3Config ):
    def __init__( self, options, system ):
        super( L3Private , self ).__init__( options, system )
        system.l3 = [
                L3Cache(
                    size = options.l3_size,
                    latency = self.latencies[options.l3_size],
                    assoc = options.l3_assoc,
                    block_size = options.cacheline_size,
                    print_misses = options.print_misses,
                    print_perSet_misses = options.print_perSet_misses
                )
                for i in xrange( options.num_cpus )
            ]

        system.tol3bus = [NoncoherentBus() for i in xrange( options.num_cpus ) ]

        for i in xrange( options.num_cpus ):
            system.l3[i].cpu_side = system.tol3bus[i].master
            system.l3[i].mem_side = system.membus.slave

    def connect_l2( self ):
        for i in xrange( self.options.num_cpus ):
            self.system.l2[i].mem_side = self.system.tol3bus[i].slave

def config_cache(options, system):

    #-------------------------------------------------------------------------
    # L3
    #-------------------------------------------------------------------------
    if options.l3cache:
        if options.l3config == "shared":
            l3config = L3Shared( options, system )
        else:
            l3config = L3Private( options, system )

    #-------------------------------------------------------------------------
    # L1
    #-------------------------------------------------------------------------
    for i in xrange(options.num_cpus):
        if options.caches:
            icache = L1Cache(size = options.l1i_size,
                             assoc = options.l1i_assoc,
                             block_size=options.cacheline_size,
                             dirty_cache=options.dirty_cache)
            dcache = L1Cache(size = options.l1d_size,
                             assoc = options.l1d_assoc,
                             block_size=options.cacheline_size,
                             dirty_cache=options.dirty_cache)

            if buildEnv['TARGET_ISA'] == 'x86':
                system.cpu[i].addPrivateSplitL1Caches(icache, dcache,
                                                      PageTableWalkerCache(),
                                                      PageTableWalkerCache())
            else:
                system.cpu[i].addPrivateSplitL1Caches(icache, dcache)
        system.cpu[i].createInterruptController()

    #-------------------------------------------------------------------------
    # L2
    #-------------------------------------------------------------------------
    system.l2 = [
            L2Cache(
                size = options.l2_size,
                assoc = options.l2_assoc,
                block_size=options.cacheline_size,
                print_misses = options.l2trace
            )
            for i in xrange( options.num_cpus )
        ]
    system.tol2bus = [NoncoherentBus() for i in xrange( options.num_cpus )]

    for i in xrange(options.num_cpus):
        if options.l2cache:
            system.cpu[i].connectAllPorts(system.tol2bus[i])
            system.l2[i].cpu_side = system.tol2bus[i].master
            if not options.l3cache:
                system.l2[i].mem_side = system.membus.slave
        else:
            system.cpu[i].connectAllPorts(system.membus)

    if options.l3cache:
        l3config.connect_l2()

    return system
<commit_msg>fixed a bug of static_curve option<commit_after># Copyright (c) 2010 Advanced Micro Devices, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met: redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer;
# redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution;
# neither the name of the copyright holders nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# Authors: Lisa Hsu

# Configure the M5 cache hierarchy config in one place
#

import m5
from m5.objects import *
from Caches import *
from O3_ARM_v7a import *

class L3Config(object):
    def __init__( self, options, system ):
        self.options = options
        self.system = system
        self.latencies = {
            '4096kB' : '8.48ns',
            '3072kB' : '7.5',
            '2048kB' : '6.5ns',
            '1792kB' : '6.5ns',
            '1536kB' : '6.5ns',
            '1280kB' : '6.5ns',
            '1024kB' : '6.5ns',
            '768kB'  : '6.5ns',
            '512kB'  : '6.5ns',
            '256kB'  : '6.5ns',
            '1920kB' : '6.5ns',
            '1664kB' : '6.5ns',
            '1408kB' : '6.5ns',
            '1152kB' : '6.5ns',
            '896kB' : '6.5ns',
            '640kB'  : '6.5ns',
            '384kB'  : '6.5ns',
            '128kB'  : '6.5ns',
            '1kB'    : '6.5ns',
        }

    def connect_l2( self ): return

class L3Shared( L3Config ):
    def __init__( self, options, system ):
        super( L3Shared, self ).__init__( options, system )
        system.l3 = L3Cache(size = options.l3_size,
                            latency=self.latencies[options.l3_size],
                            assoc = options.l3_assoc,
                            block_size=options.cacheline_size,
                            num_tcs = options.numpids,
                            c_dynamic_cache = options.c_dynamic_cache,
                            f_dynamic_cache = options.f_dynamic_cache,
                            static_cache = options.static_cache,
                            L_assoc = options.L_assoc,
                            H_min = options.H_min,
                            threshold_inc = options.th_inc,
                            threshold_dec = options.th_dec,
                            static_curve = options.static_curve)

        # system.tol3bus = (
        #         RR_NoncoherentBus(num_pids = options.numpids,
        #                     save_trace = options.do_bus_trace,
        #                     bus_trace_file = options.l2l3bustracefile ,
        #                     req_tl = options.l2l3req_tl,
        #                     req_offset = options.l2l3req_offset,
        #                     resp_tl = options.l2l3resp_tl,
        #                     resp_offset = options.l2l3resp_offset) if options.rr_l2l3
        #         else NoncoherentBus()
        #         )
        system.tol3bus = NoncoherentBus()
        system.l3.cpu_side = system.tol3bus.master
        system.l3.mem_side = system.membus.slave

    def connect_l2( self ):
        for i in xrange( self.options.num_cpus ):
            self.system.l2[i].mem_side = self.system.tol3bus.slave

class L3Private( L3Config ):
    def __init__( self, options, system ):
        super( L3Private , self ).__init__( options, system )
        system.l3 = [
                L3Cache(
                    size = options.l3_size,
                    latency = self.latencies[options.l3_size],
                    assoc = options.l3_assoc,
                    block_size = options.cacheline_size,
                    print_misses = options.print_misses,
                    print_perSet_misses = options.print_perSet_misses
                )
                for i in xrange( options.num_cpus )
            ]

        system.tol3bus = [NoncoherentBus() for i in xrange( options.num_cpus ) ]

        for i in xrange( options.num_cpus ):
            system.l3[i].cpu_side = system.tol3bus[i].master
            system.l3[i].mem_side = system.membus.slave

    def connect_l2( self ):
        for i in xrange( self.options.num_cpus ):
            self.system.l2[i].mem_side = self.system.tol3bus[i].slave

def config_cache(options, system):

    #-------------------------------------------------------------------------
    # L3
    #-------------------------------------------------------------------------
    if options.l3cache:
        if options.l3config == "shared":
            l3config = L3Shared( options, system )
        else:
            l3config = L3Private( options, system )

    #-------------------------------------------------------------------------
    # L1
    #-------------------------------------------------------------------------
    for i in xrange(options.num_cpus):
        if options.caches:
            icache = L1Cache(size = options.l1i_size,
                             assoc = options.l1i_assoc,
                             block_size=options.cacheline_size,
                             dirty_cache=options.dirty_cache)
            dcache = L1Cache(size = options.l1d_size,
                             assoc = options.l1d_assoc,
                             block_size=options.cacheline_size,
                             dirty_cache=options.dirty_cache)

            if buildEnv['TARGET_ISA'] == 'x86':
                system.cpu[i].addPrivateSplitL1Caches(icache, dcache,
                                                      PageTableWalkerCache(),
                                                      PageTableWalkerCache())
            else:
                system.cpu[i].addPrivateSplitL1Caches(icache, dcache)
        system.cpu[i].createInterruptController()

    #-------------------------------------------------------------------------
    # L2
    #-------------------------------------------------------------------------
    system.l2 = [
            L2Cache(
                size = options.l2_size,
                assoc = options.l2_assoc,
                block_size=options.cacheline_size,
                print_misses = options.l2trace
            )
            for i in xrange( options.num_cpus )
        ]
    system.tol2bus = [NoncoherentBus() for i in xrange( options.num_cpus )]

    for i in xrange(options.num_cpus):
        if options.l2cache:
            system.cpu[i].connectAllPorts(system.tol2bus[i])
            system.l2[i].cpu_side = system.tol2bus[i].master
            if not options.l3cache:
                system.l2[i].mem_side = system.membus.slave
        else:
            system.cpu[i].connectAllPorts(system.membus)

    if options.l3cache:
        l3config.connect_l2()

    return system
<|endoftext|>


<commit_before># All rights reserved.
#
#    Licensed under the Apache License, Version 2.0 (the "License"); you may
#    not use this file except in compliance with the License. You may obtain
#    a copy of the License at
#
#         http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#    License for the specific language governing permissions and limitations
#    under the License.

from neutron_lib.api.definitions import segment
from neutron_lib.api.definitions import subnet

# The alias of the extension.
ALIAS = 'subnet-segmentid-writable'

# Whether or not this extension is simply signaling behavior to the user
# or it actively modifies the attribute map.
IS_SHIM_EXTENSION = False

# Whether the extension is marking the adoption of standardattr model for
# legacy resources, or introducing new standardattr attributes. False or
# None if the standardattr model is adopted since the introduction of
# resource extension.
# If this is True, the alias for the extension should be prefixed with
# 'standard-attr-'.
IS_STANDARD_ATTR_EXTENSION = False

# The name of the extension.
NAME = 'Subnet SegmentID (writable)'

# A prefix for API resources. An empty prefix means that the API is going
# to be exposed at the v2/ level as any other core resource.
API_PREFIX = ''

# The description of the extension.
DESCRIPTION = (
    "Provides a writable segment_id attribute for a subnet resource.")

# A timestamp of when the extension was introduced.
UPDATED_TIMESTAMP = "2018-03-12T00:00:00-00:00"

RESOURCE_ATTRIBUTE_MAP = {
    subnet.COLLECTION_NAME: {
        segment.SEGMENT_ID: {'allow_post': True, 'allow_put': True,
                             'default': None,
                             'validate': {'type:uuid_or_none': None},
                             'is_visible': True}
    }
}

# The subresource attribute map for the extension. It adds child resources
# to main extension's resource. The subresource map must have a parent and
# a parameters entry. If an extension does not need such a map, None can
# be specified (mandatory).
SUB_RESOURCE_ATTRIBUTE_MAP = {}

# The action map: it associates verbs with methods to be performed on
# the API resource.
ACTION_MAP = {}

# The action status.
ACTION_STATUS = {
}

# The list of required extensions.
REQUIRED_EXTENSIONS = [segment.ALIAS]

# The list of optional extensions.
OPTIONAL_EXTENSIONS = []
<commit_msg>API "subnet-segmentid-writable" should inherit field definition<commit_after># All rights reserved.
#
#    Licensed under the Apache License, Version 2.0 (the "License"); you may
#    not use this file except in compliance with the License. You may obtain
#    a copy of the License at
#
#         http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#    License for the specific language governing permissions and limitations
#    under the License.

import copy

from neutron_lib.api.definitions import segment
from neutron_lib.api.definitions import subnet

# The alias of the extension.
ALIAS = 'subnet-segmentid-writable'

# Whether or not this extension is simply signaling behavior to the user
# or it actively modifies the attribute map.
IS_SHIM_EXTENSION = False

# Whether the extension is marking the adoption of standardattr model for
# legacy resources, or introducing new standardattr attributes. False or
# None if the standardattr model is adopted since the introduction of
# resource extension.
# If this is True, the alias for the extension should be prefixed with
# 'standard-attr-'.
IS_STANDARD_ATTR_EXTENSION = False

# The name of the extension.
NAME = 'Subnet SegmentID (writable)'

# A prefix for API resources. An empty prefix means that the API is going
# to be exposed at the v2/ level as any other core resource.
API_PREFIX = ''

# The description of the extension.
DESCRIPTION = (
    "Provides a writable segment_id attribute for a subnet resource.")

# A timestamp of when the extension was introduced.
UPDATED_TIMESTAMP = "2018-03-12T00:00:00-00:00"

segment_id_attr_info = copy.deepcopy(
    segment.RESOURCE_ATTRIBUTE_MAP[
        subnet.COLLECTION_NAME][segment.SEGMENT_ID])
segment_id_attr_info['allow_put'] = True

RESOURCE_ATTRIBUTE_MAP = {
    subnet.COLLECTION_NAME: {
        segment.SEGMENT_ID: segment_id_attr_info
    }
}

# The subresource attribute map for the extension. It adds child resources
# to main extension's resource. The subresource map must have a parent and
# a parameters entry. If an extension does not need such a map, None can
# be specified (mandatory).
SUB_RESOURCE_ATTRIBUTE_MAP = {}

# The action map: it associates verbs with methods to be performed on
# the API resource.
ACTION_MAP = {}

# The action status.
ACTION_STATUS = {
}

# The list of required extensions.
REQUIRED_EXTENSIONS = [segment.ALIAS]

# The list of optional extensions.
OPTIONAL_EXTENSIONS = []
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
__author__ = 'Alex Dzul'
from pyql.geo.generics import GenericGeoPlace
from pyql.interface import YQLConector

__all__ = ('Continent', )

YQL_TABLE = "geo.districts"

class District(GenericGeoPlace):

    @staticmethod
    def get(**kwargs):
        """
        Realiza una consulta a la base de datos de Yahoo utilizando YQL.
        El valor retornado un solo elemento. Si la consulta retorna más entonces
        se presentará un error de múltiples resultados encontrados.
        """
        connect = YQLConector()
        query = connect.make_query(YQL_TABLE, **kwargs)
        response = connect.request(query)
        if response["query"]["count"] > 0:
            return District.generic_get(response)
        else:
            raise Exception("No se encontraron resultados con los criterios especificados")

    @staticmethod
    def filter(**kwargs):
        """
        Realiza una consulta a la base de datos de Yahoo utilizando YQL.
        El valor retornado siempre será una lista de objetos tipo "District"
        """
        connect = YQLConector()
        query = connect.make_query(YQL_TABLE, **kwargs)
        response = connect.request(query)
        return District.generic_get(response)<commit_msg>#BUGFIX. Se cambia generic_get por generic_filter<commit_after># -*- coding: utf-8 -*-
__author__ = 'Alex Dzul'
from pyql.geo.generics import GenericGeoPlace
from pyql.interface import YQLConector

__all__ = ('Continent', )

YQL_TABLE = "geo.districts"

class District(GenericGeoPlace):

    @staticmethod
    def get(**kwargs):
        """
        Realiza una consulta a la base de datos de Yahoo utilizando YQL.
        El valor retornado un solo elemento. Si la consulta retorna más entonces
        se presentará un error de múltiples resultados encontrados.
        """
        connect = YQLConector()
        query = connect.make_query(YQL_TABLE, **kwargs)
        response = connect.request(query)
        if response["query"]["count"] > 0:
            return District.generic_get(response)
        else:
            raise Exception("No se encontraron resultados con los criterios especificados")

    @staticmethod
    def filter(**kwargs):
        """
        Realiza una consulta a la base de datos de Yahoo utilizando YQL.
        El valor retornado siempre será una lista de objetos tipo "District"
        """
        connect = YQLConector()
        query = connect.make_query(YQL_TABLE, **kwargs)
        response = connect.request(query)
        return District.generic_filter(response)<|endoftext|>


<commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-
##############################################################################
#
#     This file is part of connector, an Odoo module.
#
#     Author: Stéphane Bidoul <stephane.bidoul@acsone.eu>
#     Copyright (c) 2015 ACSONE SA/NV (<http://acsone.eu>)
#
#     connector is free software: you can redistribute it and/or
#     modify it under the terms of the GNU Affero General Public License
#     as published by the Free Software Foundation, either version 3 of
#     the License, or (at your option) any later version.
#
#     connector is distributed in the hope that it will be useful,
#     but WITHOUT ANY WARRANTY; without even the implied warranty of
#     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#     GNU Affero General Public License for more details.
#
#     You should have received a copy of the
#     GNU Affero General Public License
#     along with connector.
#     If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
"""
What is the job runner?
-----------------------
This is an alternative to connector workers, with the goal
of resolving issues due to the polling nature of workers:

* jobs do not start immediately even if there is a free connector worker,
* connector workers may starve while other workers have too many jobs enqueued,
* connector workers require another startup script,
  making deployment more difficult

It is fully compatible with the connector mechanism and only
replaces workers.

How does it work?
-----------------

* It starts as a thread in the Odoo main process
* It receives postgres NOTIFY messages each time jobs are
  added or updated in the queue_job table.
* It maintains an in-memory priority queue of jobs that
  is populated from the queue_job tables in all databases.
* It does not run jobs itself, but asks Odoo to run them through an
  anonymous ``/connector/runjob`` HTTP request. [1]_

How to use it?
--------------

* Set the following environment variables:

  - ``ODOO_CONNECTOR_CHANNELS=root:4`` (or any other channels configuration)
  - optional if ``xmlrpc_port`` is not set: ``ODOO_CONNECTOR_PORT=8069``

* Start Odoo with ``--load=web,web_kanban,connector``
  and ``--workers`` greater than 1. [2]_

* Confirm the runner is starting correctly by checking the odoo log file:

.. code-block:: none

  ...INFO...connector.jobrunner.runner: starting
  ...INFO...connector.jobrunner.runner: initializing database connections
  ...INFO...connector.jobrunner.runner: connector runner ready for db <dbname>
  ...INFO...connector.jobrunner.runner: database connections ready

* Disable the "Enqueue Jobs" cron.

* Do NOT start openerp-connector-worker.

* Create jobs (eg using base_import_async) and observe they
  start immediately and in parallel.

* Tip: to enable debug logging for the connector, use
  ``--log-handler=openerp.addons.connector:DEBUG``

Caveat
------

* After creating a new database or installing connector on an
  existing database, Odoo must be restarted for the runner to detect it.

* When Odoo shuts down normally, it waits for running jobs to finish.
  However, when the Odoo server crashes or is otherwise force-stopped,
  running jobs are interrupted while the runner has no chance to know
  they have been aborted. In such situations, jobs may remain in
  ``started`` or ``enqueued`` state after the Odoo server is halted.
  Since the runner has no way to know if they are actually running or
  not, and does not know for sure if it is safe to restart the jobs,
  it does not attempt to restart them automatically. Such stale jobs
  therefore fill the running queue and prevent other jobs to start.
  You must therefore requeue them manually, either from the Jobs view,
  or by running the following SQL statement *before starting Odoo*:

.. code-block:: sql

  update queue_job set state='pending' where state in ('started', 'enqueued')

.. rubric:: Footnotes

.. [1] From a security standpoint, it is safe to have an anonymous HTTP
       request because this request only accepts to run jobs that are
       enqueued.
.. [2] It works with the threaded Odoo server too, although this way
       of running Odoo is obviously not for production purposes.
"""

from contextlib import closing
import logging
import os
import re
import select
import threading
import time

import psycopg2
from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT
import requests

import openerp

from .channels import ChannelManager, ENQUEUED, NOT_DONE

SELECT_TIMEOUT = 60
ERROR_RECOVERY_DELAY = 5

_logger = logging.getLogger(__name__)

def _async_http_get(url):
    # TODO: better way to HTTP GET asynchronously (grequest, ...)?
    #       if this was python3 I would be doing this with
    #       asyncio, aiohttp and aiopg
    def urlopen():
        try:
            # we are not interested in the result, so we set a short timeout
            # but not too short so we trap and log hard configuration errors
            requests.get(url, timeout=1)
        except requests.Timeout:
            pass
        except:
            _logger.exception("exception in GET %s", url)
    thread = threading.Thread(target=urlopen)
    thread.daemon = True
    thread.start()

class Database(object):

    def __init__(self, db_name):
        self.db_name = db_name
        self.conn = psycopg2.connect(openerp.sql_db.dsn(db_name)[1])
        self.conn.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT)
        self.has_connector = self._has_connector()
        if self.has_connector:
            self.has_channel = self._has_queue_job_column('channel')
            self._initialize()

    def close(self):
        try:
            self.conn.close()
        except:
            pass
        self.conn = None

    def _has_connector(self):
        with closing(self.conn.cursor()) as cr:
            try:
                cr.execute("SELECT 1 FROM ir_module_module "
                           "WHERE name=%s AND state=%s",
                           ('connector', 'installed'))
            except psycopg2.ProgrammingError as err:
                if unicode(err).startswith('relation "ir_module_module" '
                                           'does not exist'):
                    return False
                else:
                    raise
            return cr.fetchone()

    def _has_queue_job_column(self, column):
        if not self.has_connector:
            return False
        with closing(self.conn.cursor()) as cr:
            cr.execute("SELECT 1 FROM information_schema.columns "
                       "WHERE table_name=%s AND column_name=%s",
                       ('queue_job', column))
            return cr.fetchone()

    def _initialize(self):
        with closing(self.conn.cursor()) as cr:
            # this is the trigger that sends notifications when jobs change
            cr.execute("""
                DROP TRIGGER IF EXISTS queue_job_notify ON queue_job;

                CREATE OR REPLACE
                    FUNCTION queue_job_notify() RETURNS trigger AS $$
                BEGIN
                    IF TG_OP = 'DELETE' THEN
                        IF OLD.state != 'done' THEN
                            PERFORM pg_notify('connector', OLD.uuid);
                        END IF;
                    ELSE
                        PERFORM pg_notify('connector', NEW.uuid);
                    END IF;
                    RETURN NULL;
                END;
                $$ LANGUAGE plpgsql;

                CREATE TRIGGER queue_job_notify
                    AFTER INSERT OR UPDATE OR DELETE
                    ON queue_job
                    FOR EACH ROW EXECUTE PROCEDURE queue_job_notify();
            """)
            cr.execute("LISTEN connector")

    def select_jobs(self, where, args):
        query = "SELECT %s, uuid, id as seq, date_created, priority, eta, state " \
                "FROM queue_job WHERE %s" % \
                ('channel' if self.has_channel else 'NULL',
                 where)
        with closing(self.conn.cursor()) as cr:
            cr.execute(query, args)
            return list(cr.fetchall())

    def set_job_enqueued(self, uuid):
        with closing(self.conn.cursor()) as cr:
            cr.execute("UPDATE queue_job SET state=%s, "
                       "date_enqueued=date_trunc('seconds', "
                       "                         now() at time zone 'utc') "
                       "WHERE uuid=%s",
                       (ENQUEUED, uuid))

class ConnectorRunner(object):

    def __init__(self, port=8069, channel_config_string='root:1'):
        self.port = port
        self.channel_manager = ChannelManager()
        self.channel_manager.simple_configure(channel_config_string)
        self.db_by_name = {}
        self._stop = False
        self._stop_pipe = os.pipe()

    def get_db_names(self):
        if openerp.tools.config['db_name']:
            db_names = openerp.tools.config['db_name'].split(',')
        else:
            db_names = openerp.service.db.exp_list()
        dbfilter = openerp.tools.config['dbfilter']
        if dbfilter:
            db_names = [d for d in db_names if re.match(dbfilter, d)]
        return db_names

    def close_databases(self, remove_jobs=True):
        for db_name, db in self.db_by_name.items():
            try:
                if remove_jobs:
                    self.channel_manager.remove_db(db_name)
                db.close()
            except:
                _logger.warning('error closing database %s',
                                db_name, exc_info=True)
        self.db_by_name = {}

    def initialize_databases(self):
        for db_name in self.get_db_names():
            db = Database(db_name)
            if not db.has_connector:
                _logger.debug('connector is not installed for db %s', db_name)
            else:
                self.db_by_name[db_name] = db
                for job_data in db.select_jobs('state in %s', (NOT_DONE,)):
                    self.channel_manager.notify(db_name, *job_data)
                _logger.info('connector runner ready for db %s', db_name)

    def run_jobs(self):
        now = openerp.fields.Datetime.now()
        for job in self.channel_manager.get_jobs_to_run(now):
            if self._stop:
                break
            _logger.info("asking Odoo to run job %s on db %s",
                         job.uuid, job.db_name)
            self.db_by_name[job.db_name].set_job_enqueued(job.uuid)
            _async_http_get('http://localhost:%s'
                            '/connector/runjob?db=%s&job_uuid=%s' %
                            (self.port, job.db_name, job.uuid))

    def process_notifications(self):
        for db in self.db_by_name.values():
            while db.conn.notifies:
                if self._stop:
                    break
                notification = db.conn.notifies.pop()
                uuid = notification.payload
                job_datas = db.select_jobs('uuid = %s', (uuid,))
                if job_datas:
                    self.channel_manager.notify(db.db_name, *job_datas[0])
                else:
                    self.channel_manager.remove_job(uuid)

    def wait_notification(self):
        for db in self.db_by_name.values():
            if db.conn.notifies:
                return
        # wait for something to happen in the queue_job tables
        conns = [db.conn for db in self.db_by_name.values()]
        conns.append(self._stop_pipe[0])
        conns, _, _ = select.select(conns, [], [], SELECT_TIMEOUT)
        if conns and not self._stop:
            for conn in conns:
                conn.poll()

    def stop(self):
        _logger.info("graceful stop requested")
        self._stop = True
        # wakeup the select() in wait_notification
        os.write(self._stop_pipe[1], '.')

    def run(self):
        _logger.info("starting")
        while not self._stop:
            # outer loop does exception recovery
            try:
                _logger.info("initializing database connections")
                # TODO: how to detect new databases or databases
                #       on which connector is installed after server start?
                self.initialize_databases()
                _logger.info("database connections ready")
                # inner loop does the normal processing
                while not self._stop:
                    self.process_notifications()
                    self.run_jobs()
                    self.wait_notification()
            except KeyboardInterrupt:
                self.stop()
            except:
                _logger.exception("exception: sleeping %ds and retrying",
                                  ERROR_RECOVERY_DELAY)
                self.close_databases()
                time.sleep(ERROR_RECOVERY_DELAY)
        self.close_databases(remove_jobs=False)
        _logger.info("stopped")
<commit_msg>Set job back to 'pending' in case of exception<commit_after>#!/usr/bin/env python
# -*- coding: utf-8 -*-
##############################################################################
#
#     This file is part of connector, an Odoo module.
#
#     Author: Stéphane Bidoul <stephane.bidoul@acsone.eu>
#     Copyright (c) 2015 ACSONE SA/NV (<http://acsone.eu>)
#
#     connector is free software: you can redistribute it and/or
#     modify it under the terms of the GNU Affero General Public License
#     as published by the Free Software Foundation, either version 3 of
#     the License, or (at your option) any later version.
#
#     connector is distributed in the hope that it will be useful,
#     but WITHOUT ANY WARRANTY; without even the implied warranty of
#     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#     GNU Affero General Public License for more details.
#
#     You should have received a copy of the
#     GNU Affero General Public License
#     along with connector.
#     If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
"""
What is the job runner?
-----------------------
This is an alternative to connector workers, with the goal
of resolving issues due to the polling nature of workers:

* jobs do not start immediately even if there is a free connector worker,
* connector workers may starve while other workers have too many jobs enqueued,
* connector workers require another startup script,
  making deployment more difficult

It is fully compatible with the connector mechanism and only
replaces workers.

How does it work?
-----------------

* It starts as a thread in the Odoo main process
* It receives postgres NOTIFY messages each time jobs are
  added or updated in the queue_job table.
* It maintains an in-memory priority queue of jobs that
  is populated from the queue_job tables in all databases.
* It does not run jobs itself, but asks Odoo to run them through an
  anonymous ``/connector/runjob`` HTTP request. [1]_

How to use it?
--------------

* Set the following environment variables:

  - ``ODOO_CONNECTOR_CHANNELS=root:4`` (or any other channels configuration)
  - optional if ``xmlrpc_port`` is not set: ``ODOO_CONNECTOR_PORT=8069``

* Start Odoo with ``--load=web,web_kanban,connector``
  and ``--workers`` greater than 1. [2]_

* Confirm the runner is starting correctly by checking the odoo log file:

.. code-block:: none

  ...INFO...connector.jobrunner.runner: starting
  ...INFO...connector.jobrunner.runner: initializing database connections
  ...INFO...connector.jobrunner.runner: connector runner ready for db <dbname>
  ...INFO...connector.jobrunner.runner: database connections ready

* Disable the "Enqueue Jobs" cron.

* Do NOT start openerp-connector-worker.

* Create jobs (eg using base_import_async) and observe they
  start immediately and in parallel.

* Tip: to enable debug logging for the connector, use
  ``--log-handler=openerp.addons.connector:DEBUG``

Caveat
------

* After creating a new database or installing connector on an
  existing database, Odoo must be restarted for the runner to detect it.

* When Odoo shuts down normally, it waits for running jobs to finish.
  However, when the Odoo server crashes or is otherwise force-stopped,
  running jobs are interrupted while the runner has no chance to know
  they have been aborted. In such situations, jobs may remain in
  ``started`` or ``enqueued`` state after the Odoo server is halted.
  Since the runner has no way to know if they are actually running or
  not, and does not know for sure if it is safe to restart the jobs,
  it does not attempt to restart them automatically. Such stale jobs
  therefore fill the running queue and prevent other jobs to start.
  You must therefore requeue them manually, either from the Jobs view,
  or by running the following SQL statement *before starting Odoo*:

.. code-block:: sql

  update queue_job set state='pending' where state in ('started', 'enqueued')

.. rubric:: Footnotes

.. [1] From a security standpoint, it is safe to have an anonymous HTTP
       request because this request only accepts to run jobs that are
       enqueued.
.. [2] It works with the threaded Odoo server too, although this way
       of running Odoo is obviously not for production purposes.
"""

from contextlib import closing
import logging
import os
import re
import select
import threading
import time

import psycopg2
from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT
import requests

import openerp

from .channels import ChannelManager, PENDING, ENQUEUED, NOT_DONE

SELECT_TIMEOUT = 60
ERROR_RECOVERY_DELAY = 5

_logger = logging.getLogger(__name__)

def _async_http_get(port, db_name, job_uuid):
    # Method to set failed job (due to timeout, etc) as pending,
    # to avoid keeping it as enqueued.
    def set_job_pending():
        conn = psycopg2.connect(openerp.sql_db.dsn(db_name))
        conn.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT)
        with closing(conn.cursor()) as cr:
            cr.execute(
                "UPDATE queue_job SET state=%s, "
                "date_enqueued=NULL, date_started=NULL "
                "WHERE uuid=%s and state=%s", (PENDING, job_uuid, ENQUEUED)
            )

    # TODO: better way to HTTP GET asynchronously (grequest, ...)?
    #       if this was python3 I would be doing this with
    #       asyncio, aiohttp and aiopg
    def urlopen():
        url = ('http://localhost:%s/connector/runjob?db=%s&job_uuid=%s' %
               (port, db_name, job_uuid))
        try:
            # we are not interested in the result, so we set a short timeout
            # but not too short so we trap and log hard configuration errors
            requests.get(url, timeout=1)
        except requests.Timeout:
            set_job_pending()
        except:
            _logger.exception("exception in GET %s", url)
            set_job_pending()
    thread = threading.Thread(target=urlopen)
    thread.daemon = True
    thread.start()

class Database(object):

    def __init__(self, db_name):
        self.db_name = db_name
        self.conn = psycopg2.connect(openerp.sql_db.dsn(db_name)[1])
        self.conn.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT)
        self.has_connector = self._has_connector()
        if self.has_connector:
            self.has_channel = self._has_queue_job_column('channel')
            self._initialize()

    def close(self):
        try:
            self.conn.close()
        except:
            pass
        self.conn = None

    def _has_connector(self):
        with closing(self.conn.cursor()) as cr:
            try:
                cr.execute("SELECT 1 FROM ir_module_module "
                           "WHERE name=%s AND state=%s",
                           ('connector', 'installed'))
            except psycopg2.ProgrammingError as err:
                if unicode(err).startswith('relation "ir_module_module" '
                                           'does not exist'):
                    return False
                else:
                    raise
            return cr.fetchone()

    def _has_queue_job_column(self, column):
        if not self.has_connector:
            return False
        with closing(self.conn.cursor()) as cr:
            cr.execute("SELECT 1 FROM information_schema.columns "
                       "WHERE table_name=%s AND column_name=%s",
                       ('queue_job', column))
            return cr.fetchone()

    def _initialize(self):
        with closing(self.conn.cursor()) as cr:
            # this is the trigger that sends notifications when jobs change
            cr.execute("""
                DROP TRIGGER IF EXISTS queue_job_notify ON queue_job;

                CREATE OR REPLACE
                    FUNCTION queue_job_notify() RETURNS trigger AS $$
                BEGIN
                    IF TG_OP = 'DELETE' THEN
                        IF OLD.state != 'done' THEN
                            PERFORM pg_notify('connector', OLD.uuid);
                        END IF;
                    ELSE
                        PERFORM pg_notify('connector', NEW.uuid);
                    END IF;
                    RETURN NULL;
                END;
                $$ LANGUAGE plpgsql;

                CREATE TRIGGER queue_job_notify
                    AFTER INSERT OR UPDATE OR DELETE
                    ON queue_job
                    FOR EACH ROW EXECUTE PROCEDURE queue_job_notify();
            """)
            cr.execute("LISTEN connector")

    def select_jobs(self, where, args):
        query = "SELECT %s, uuid, id as seq, date_created, priority, eta, state " \
                "FROM queue_job WHERE %s" % \
                ('channel' if self.has_channel else 'NULL',
                 where)
        with closing(self.conn.cursor()) as cr:
            cr.execute(query, args)
            return list(cr.fetchall())

    def set_job_enqueued(self, uuid):
        with closing(self.conn.cursor()) as cr:
            cr.execute("UPDATE queue_job SET state=%s, "
                       "date_enqueued=date_trunc('seconds', "
                       "                         now() at time zone 'utc') "
                       "WHERE uuid=%s",
                       (ENQUEUED, uuid))

class ConnectorRunner(object):

    def __init__(self, port=8069, channel_config_string='root:1'):
        self.port = port
        self.channel_manager = ChannelManager()
        self.channel_manager.simple_configure(channel_config_string)
        self.db_by_name = {}
        self._stop = False
        self._stop_pipe = os.pipe()

    def get_db_names(self):
        if openerp.tools.config['db_name']:
            db_names = openerp.tools.config['db_name'].split(',')
        else:
            db_names = openerp.service.db.exp_list()
        dbfilter = openerp.tools.config['dbfilter']
        if dbfilter:
            db_names = [d for d in db_names if re.match(dbfilter, d)]
        return db_names

    def close_databases(self, remove_jobs=True):
        for db_name, db in self.db_by_name.items():
            try:
                if remove_jobs:
                    self.channel_manager.remove_db(db_name)
                db.close()
            except:
                _logger.warning('error closing database %s',
                                db_name, exc_info=True)
        self.db_by_name = {}

    def initialize_databases(self):
        for db_name in self.get_db_names():
            db = Database(db_name)
            if not db.has_connector:
                _logger.debug('connector is not installed for db %s', db_name)
            else:
                self.db_by_name[db_name] = db
                for job_data in db.select_jobs('state in %s', (NOT_DONE,)):
                    self.channel_manager.notify(db_name, *job_data)
                _logger.info('connector runner ready for db %s', db_name)

    def run_jobs(self):
        now = openerp.fields.Datetime.now()
        for job in self.channel_manager.get_jobs_to_run(now):
            if self._stop:
                break
            _logger.info("asking Odoo to run job %s on db %s",
                         job.uuid, job.db_name)
            self.db_by_name[job.db_name].set_job_enqueued(job.uuid)
            _async_http_get(self.port, job.db_name, job.uuid)

    def process_notifications(self):
        for db in self.db_by_name.values():
            while db.conn.notifies:
                if self._stop:
                    break
                notification = db.conn.notifies.pop()
                uuid = notification.payload
                job_datas = db.select_jobs('uuid = %s', (uuid,))
                if job_datas:
                    self.channel_manager.notify(db.db_name, *job_datas[0])
                else:
                    self.channel_manager.remove_job(uuid)

    def wait_notification(self):
        for db in self.db_by_name.values():
            if db.conn.notifies:
                return
        # wait for something to happen in the queue_job tables
        conns = [db.conn for db in self.db_by_name.values()]
        conns.append(self._stop_pipe[0])
        conns, _, _ = select.select(conns, [], [], SELECT_TIMEOUT)
        if conns and not self._stop:
            for conn in conns:
                conn.poll()

    def stop(self):
        _logger.info("graceful stop requested")
        self._stop = True
        # wakeup the select() in wait_notification
        os.write(self._stop_pipe[1], '.')

    def run(self):
        _logger.info("starting")
        while not self._stop:
            # outer loop does exception recovery
            try:
                _logger.info("initializing database connections")
                # TODO: how to detect new databases or databases
                #       on which connector is installed after server start?
                self.initialize_databases()
                _logger.info("database connections ready")
                # inner loop does the normal processing
                while not self._stop:
                    self.process_notifications()
                    self.run_jobs()
                    self.wait_notification()
            except KeyboardInterrupt:
                self.stop()
            except:
                _logger.exception("exception: sleeping %ds and retrying",
                                  ERROR_RECOVERY_DELAY)
                self.close_databases()
                time.sleep(ERROR_RECOVERY_DELAY)
        self.close_databases(remove_jobs=False)
        _logger.info("stopped")
<|endoftext|>


<commit_before>"""
Class to create an atom object

>>> h = atom(1,0,0,0)
>>> h
1 H     0.000000     0.000000     0.000000
>>> h.r
array([ 0.,  0.,  0.])

 Copyright (c) 2004, Richard P. Muller. All Rights Reserved.

 PyQuante version 2.0 and later is covered by the GPL
 license. Please see the file LICENSE that is part of this
 distribution.
"""
import numpy as np
from pyquante2.constants import ang2bohr
from pyquante2.utils import norm2

class atom:
    def __init__(self,atno,x,y,z,**kwargs):
        self.atno = atno
        self.r = np.array([x,y,z],'d')
        self.units = kwargs.get('units','bohr').lower()
        assert self.units[:4] in ['bohr','angs']
        if not self.units == 'bohr':
            self.r *= ang2bohr
        return

    def atuple(self): return (self.atno,self.r[0],self.r[1],self.r[2])
    def nsxyz(self):
        from pyquante2.geo.elements import symbol
        return (self.atno,symbol[self.atno],self.r[0],self.r[1],self.r[2])
    def __repr__(self): return "%d %s %12.6f %12.6f %12.6f" % self.nsxyz()
    def __getitem__(self, i): return self.r[i]

    def xyz(self):
        from pyquante2.geo.elements import symbol
        return "%4s %12.6f %12.6f %12.6f" % (symbol[self.atno],self.r[0],self.r[1],self.r[2])

    def distance(self,other): return np.sqrt(norm2(self.r-other.r))

if __name__ == '__main__':
    import doctest
    doctest.testmod()
<commit_msg>Added color and vdw radius to atoms<commit_after>"""
Class to create an atom object

>>> h = atom(1,0,0,0)
>>> h
1 H     0.000000     0.000000     0.000000
>>> h.r
array([ 0.,  0.,  0.])

 Copyright (c) 2004, Richard P. Muller. All Rights Reserved.

 PyQuante version 2.0 and later is covered by the GPL
 license. Please see the file LICENSE that is part of this
 distribution.
"""
import numpy as np
from pyquante2.geo.elements import color,radius
from pyquante2.constants import ang2bohr
from pyquante2.utils import norm2

class atom:
    def __init__(self,atno,x,y,z,**kwargs):
        self.atno = atno
        self.r = np.array([x,y,z],'d')
        self.units = kwargs.get('units','bohr').lower()
        assert self.units[:4] in ['bohr','angs']
        if not self.units == 'bohr':
            self.r *= ang2bohr
        return

    def atuple(self): return (self.atno,self.r[0],self.r[1],self.r[2])
    def nsxyz(self):
        from pyquante2.geo.elements import symbol
        return (self.atno,symbol[self.atno],self.r[0],self.r[1],self.r[2])
    def __repr__(self): return "%d %s %12.6f %12.6f %12.6f" % self.nsxyz()
    def __getitem__(self, i): return self.r[i]

    def xyz(self):
        from pyquante2.geo.elements import symbol
        return "%4s %12.6f %12.6f %12.6f" % (symbol[self.atno],self.r[0],self.r[1],self.r[2])

    def distance(self,other): return np.sqrt(norm2(self.r-other.r))
    def color(self): return color[self.atno]
    def radius(self): return radius[self.atno]

if __name__ == '__main__':
    import doctest
    doctest.testmod()
<|endoftext|>


<commit_before>#
# Copyright (c) 2010 rPath, Inc.
#
# This program is distributed under the terms of the Common Public License,
# version 1.0. A copy of this license should have been distributed with this
# source file in a file called LICENSE. If it is not present, the license
# is always available at http://www.rpath.com/permanent/licenses/CPL-1.0.
#
# This program is distributed in the hope that it will be useful, but
# without any warranty; without even the implied warranty of merchantability
# or fitness for a particular purpose. See the Common Public License for
# full details.
#
"""
Implements the abstract system model, including the canonical
file representation of the model.  This system model is written
explicitly in terms of labels and versions, and is interpreted
relative to system configuration items such as installLabelPath,
flavor, pinTroves, excludeTroves, and so forth.

If an installLabelPath is provided in the configuration, it is
implicitly added to the end of the search path.
"""

import os
import shlex
import tempfile

import conary.errors
from conary.conaryclient.update import UpdateError

from conary import conaryclient
from conary import trovetup
from conary import versions
from conary.lib import log, util
from conary.repository import searchsource

# The schema for a system model is, roughly:
#
# searchPath := list of troveTuples|labels
# systemItems := list of troveOperations
# troveOperations := updateTroves | eraseTroves | installTroves | replaceTroves
# updateTroves := list of troveTuples
# eraseTroves := list of troveTuples
# installTroves := list of troveTuples
# replaceTroves := list of troveTuples

def shellStr(s):
    if len(shlex.split(s)) > 1:
        return "'%s'" % s
    return s

class SystemModelError(UpdateError):
    pass

class _SystemModelItem:
    def __init__(self, text=None, item=None, modified=True, index=None):
        self.modified = modified
        self.index = index
        assert(text is not None or item is not None)
        assert(not(text is None and item is None))
        if item:
            self.item = item
        else:
            self.parse(text=text)

    def update(self, item, modified=True):
        self.parse(item)
        self.modified = modified

    def parse(self, text=None):
        raise NotImplementedError

    def __str__(self):
        return self.key + ' ' + self.asString()

    def __repr__(self):
        return "%s(text='%s', modified=%s, index=%s)" % (
            str(self.__class__).split('.')[-1],
            self.asString(), self.modified, self.index)

    def __eq__(self, other):
        # index and modified explicitly not compared, because this is
        # used to compare new items to previously-existing items
        return self.item == other.item

class SearchElement(_SystemModelItem):
    key = 'search'

class SearchTrove(SearchElement):
    def parse(self, text):
        self.item = trovetup.TroveSpec(text)

    def asString(self):
        return shellStr(str(self.item))

class SearchLabel(SearchElement):
    def parse(self, text):
        self.item = versions.Label(text)

    def asString(self):
        return shellStr(str(self.item))

class TroveOperation(_SystemModelItem):
    def parse(self, text):
        if isinstance(text, str):
            text = [text]
        self.item = [trovetup.TroveSpec(x) for x in text]

    def __repr__(self):
        return "%s(text=['%s'], modified=%s, index=%s)" % (
            str(self.__class__).split('.')[-1],
            "', '".join(str(x) for x in self.item),
            self.modified, self.index)

    def __iter__(self):
        return iter(self.item)

    def asString(self):
        return ' '.join(shellStr(str(x)) for x in self.item)

class UpdateTroveOperation(TroveOperation):
    key = 'update'

class EraseTroveOperation(TroveOperation):
    key = 'erase'

class InstallTroveOperation(TroveOperation):
    key = 'install'

class ReplaceTroveOperation(TroveOperation):
    key = 'replace'

troveOpMap = {
    UpdateTroveOperation.key  : UpdateTroveOperation,
    EraseTroveOperation.key   : EraseTroveOperation,
    InstallTroveOperation.key : InstallTroveOperation,
    ReplaceTroveOperation.key : ReplaceTroveOperation,
}

class SystemModel:
    # Make the operation objects available via models, avoiding the
    # need to import this module when a model is provided
    SearchTrove = SearchTrove
    SearchLabel = SearchLabel
    UpdateTroveOperation = UpdateTroveOperation
    EraseTroveOperation = EraseTroveOperation
    InstallTroveOperation = InstallTroveOperation
    ReplaceTroveOperation = ReplaceTroveOperation

    def __init__(self, cfg):
        self.searchPath = []
        self.systemItems = []
        self.indexes = {}
        self.cfg = cfg

    def _addIndex(self, item):
        # normally, this list is one item long except for index None
        l = self.indexes.setdefault(item.index, [])
        if item not in l:
            l.append(item)

    def _removeIndex(self, item):
        l = self.indexes.get(item.index, [])
        while item in l:
            l.remove(item)
        if not l:
            self.indexes.pop(item.index)

    def modified(self):
        return bool([x for x in self.searchPath + self.systemItems
                     if x.modified])

    def appendToSearchPath(self, item):
        self.searchPath.append(item)
        self._addIndex(item)

    def appendTroveOp(self, op):
        # First, remove trivially obvious duplication -- more
        # complex duplicates may be removed after building the graph
        if isinstance(op, EraseTroveOperation) and self.systemItems:
            otherOp = self.systemItems[-1]
            if op == otherOp:
                if isinstance(otherOp, (UpdateTroveOperation,
                                        InstallTroveOperation)):
                    # erasing exactly the immediately-previous
                    # update or install item should remove that
                    # immediately-previous item, rather than add
                    # an explicit "erase" trove operation to the list
                    self.systemItems.pop()
                    self._removeIndex(op)
                    return
                elif (isinstance(otherOp, EraseTroveOperation)):
                    # do not add identical adjacent erase operations
                    return

        self.systemItems.append(op)
        self._addIndex(op)

    def removeTroveOp(self, op):
        self._removeIndex(op)
        while op in self.systemItems:
            self.systemItems.remove(op)

    def appendTroveOpByName(self, key, *args, **kwargs):
        op = troveOpMap[key](*args, **kwargs)
        self.appendTroveOp(op)

    def refreshSearchPath(self):
        cfg = self.cfg
        cclient = conaryclient.ConaryClient(cfg)
        repos = cclient.getRepos()

        # Find SearchTroves with any version specified, and remove any
        # trailingRevision
        # {oldTroveKey: index}
        searchItemsOld = dict((y.item, x) for x, y in enumerate(self.searchPath)
                           if isinstance(y, SearchTrove)
                              and y.item[1] is not None)
        # {newTroveKey: oldTroveKey}
        searchItemsNew = dict(((x[0], x[1].rsplit('/', 1)[0], x[2]), x)
                              for x in searchItemsOld.keys())
        searchTroves = searchItemsOld.keys() + searchItemsNew.keys()

        foundTroves = repos.findTroves(cfg.installLabelPath,
            searchTroves, defaultFlavor = cfg.flavor)

        for troveKey in foundTroves.keys():
            if troveKey in searchItemsNew:
                oldTroveKey = searchItemsNew[troveKey]
                if foundTroves[troveKey] != foundTroves[oldTroveKey]:
                    # found a new version, replace
                    foundTrove = foundTroves[troveKey][0]
                    newVersion = foundTrove[1]
                    newverstr = '%s/%s' %(newVersion.trailingLabel(),
                                          newVersion.trailingRevision())
                    item = (oldTroveKey[0], newverstr, oldTroveKey[2])
                    index = searchItemsOld[oldTroveKey]
                    self.searchPath[index].update(item)

class SystemModelText(SystemModel):
    '''
    Implements the abstract system model persisting in a text format,
    which is intended to be human-readable and human-editable.

    The format is::
        search troveSpec|label
        update troveSpec+
        erase troveSpec+
        install troveSpec+
        replace troveSpec+

    C{search} lines take a single troveSpec or label, which B{may} be
    enclosed in single or double quote characters.  Each C{search}
    item B{appends} to the search path.  The C{installLabelPath}}
    configuration item is implicitly appended to the specified
    C{searchPath}.

    C{update}, C{erase}, C{install}, and C{replace} lines take
    one or more troveSpecs, which B{may} be enclosed in single
    or double quote characters, unless they contain characters
    that may be specially interpreted by a POSIX shell, in
    which case they B{must} be enclosed in quotes.  Each item
    updated, installed, or replaced is C{prepended} to the search
    path used for C{subsequent} items, if it is not found explicitly
    via previous search path items.

    Whole-line comments are retained, and ordering is preserved
    with respect to non-comment lines.

    Partial-line comments are ignored, and not retained when a
    line is modified.
    '''

    def __init__(self, cfg):
        SystemModel.__init__(self, cfg)
        self.commentLines = []
        self.filedata = []

    def parse(self, fileData=None, fileName='(internal)'):
        if fileData is not None:
            self.filedata = fileData

        for index, line in enumerate(self.filedata):
            line = line.strip()

            if line.startswith('#') or not line:
                # empty lines are handled just like comments, and empty
                # lines and comments are always looked up in the
                # unmodified filedata, so we store only the index
                self.commentLines.append(index)
                continue

            # non-empty, non-comment lines must be parsed
            try:
                verb, nouns = line.split(None, 1)
            except:
                raise SystemModelError('%s: Invalid statement on line %d' %(
                                       fileName, index))

            if verb == 'search':
                if self.systemItems:
                    # If users provide a "search" line after a trove
                    # operation, they may expect it to be evaluated
                    # later.  Warn them that this is not actually
                    # going to happen.  (When adding "include", then
                    # this warning should apply only to the outmost
                    # file, not to included files.)
                    log.syslog('warning: %s line %d:'
                        ' "search" entry follows operations:'
                        ' but will still be honored for prior'
                        ' operations' %fileName, index)
                # Handle it if quoted, but it doesn't need to be
                nouns = ' '.join(shlex.split(nouns, comments=True))
                try:
                    searchItem = SearchLabel(text=nouns,
                                             modified=False, index=index)
                except conary.errors.ParseError:
                    searchItem = SearchTrove(text=nouns,
                                             modified=False, index=index)
                self.appendToSearchPath(searchItem)

            elif verb in troveOpMap:
                self.appendTroveOpByName(verb,
                    text=shlex.split(nouns, comments=True),
                    modified=False, index=index)

            else:
                raise SystemModelError(
                    '%s: Unrecognized command "%s" on line %d' %(
                    fileName, verb, index))

    def iterFormat(self):
        '''
        Serialize the current model, including preserved comments.
        '''
        commentLines = list(self.commentLines) # copy

        lastSearchLine = max([x.index for x in self.searchPath] + [0])
        lastOpLine = max([x.index for x in self.systemItems] + [0])
        newSearchItems = [x for x in self.searchPath if x.index is None]
        newOperations = [x for x in self.systemItems if x.index is None]
        lastIndexLine = max(lastSearchLine, lastOpLine, max(commentLines + [0]))

        for i in range(lastIndexLine+1):
            # First, emit all prior comments in order
            while commentLines and commentLines[0] <= i:
                yield self.filedata[commentLines.pop(0)]

            if i in self.indexes:
                # Next, emit all the specified lines
                for item in self.indexes[i]:
                    # normally, this list is one item long
                    if item.modified:
                        yield str(item) + '\n'
                    else:
                        yield self.filedata[i]
                        # handle models lacking trailing newlines
                        if self.filedata[i] and self.filedata[i][-1] != '\n':
                            yield '\n'

            # Last, emit any remaining lines
            if i == lastSearchLine:
                for item in (x for x in self.searchPath
                             if x.index is None):
                    yield str(item) + '\n'
            if i == lastOpLine:
                for item in (x for x in self.systemItems
                             if x.index is None):
                    yield str(item) + '\n'

        # Finally, emit any trailing comments
        while commentLines:
            yield self.filedata[commentLines.pop(0)]

    def format(self):
        return ''.join(self.iterFormat())

#class SystemModelXML(SystemModel):
#    '''
#    Implements the abstract system model persisting in an XML format,
#    which is intended to be machine-readable and machine-editable.
#    ...
#    '''

class SystemModelFile(object):
    def __init__(self, model, fileName='/etc/conary/system-model'):
        self.fileName = fileName
        self.root = model.cfg.root
        self.model = model

        self.fileFullName = self.root+fileName
        if self.exists():
            self.parse()

    def exists(self):
        return util.exists(self.fileFullName)

    def read(self):
        self.model.filedata = open(self.fileFullName, 'r').readlines()
        return self.model.filedata

    def parse(self, fileData=None):
        if fileData is None:
            self.read()
        else:
            self.model.filedata = fileData
        self.model.parse(fileData=self.model.filedata,
                         fileName=self.fileFullName)

    def write(self, fileName=None):
        '''
        Writes the current system model to the specified file (relative
        to the configured root), or overwrites the previously-specified
        file if no filename is provided.
        '''
        if fileName == None:
            fileName = self.fileName
        fileFullName = self.model.cfg.root+fileName

        dirName = os.path.dirname(fileFullName)
        fd, tmpName = tempfile.mkstemp(prefix='system-model', dir=dirName)
        f = os.fdopen(fd, 'w')
        f.write(self.model.format())
        os.rename(tmpName, fileFullName)
<commit_msg>added mkj patch for writing system model to a file<commit_after>#
# Copyright (c) 2010 rPath, Inc.
#
# This program is distributed under the terms of the Common Public License,
# version 1.0. A copy of this license should have been distributed with this
# source file in a file called LICENSE. If it is not present, the license
# is always available at http://www.rpath.com/permanent/licenses/CPL-1.0.
#
# This program is distributed in the hope that it will be useful, but
# without any warranty; without even the implied warranty of merchantability
# or fitness for a particular purpose. See the Common Public License for
# full details.
#
"""
Implements the abstract system model, including the canonical
file representation of the model.  This system model is written
explicitly in terms of labels and versions, and is interpreted
relative to system configuration items such as installLabelPath,
flavor, pinTroves, excludeTroves, and so forth.

If an installLabelPath is provided in the configuration, it is
implicitly added to the end of the search path.
"""

import os
import shlex
import tempfile

import conary.errors
from conary.conaryclient.update import UpdateError

from conary import conaryclient
from conary import trovetup
from conary import versions
from conary.lib import log, util
from conary.repository import searchsource

# The schema for a system model is, roughly:
#
# searchPath := list of troveTuples|labels
# systemItems := list of troveOperations
# troveOperations := updateTroves | eraseTroves | installTroves | replaceTroves
# updateTroves := list of troveTuples
# eraseTroves := list of troveTuples
# installTroves := list of troveTuples
# replaceTroves := list of troveTuples

def shellStr(s):
    if len(shlex.split(s)) > 1:
        return "'%s'" % s
    return s

class SystemModelError(UpdateError):
    pass

class _SystemModelItem:
    def __init__(self, text=None, item=None, modified=True, index=None):
        self.modified = modified
        self.index = index
        assert(text is not None or item is not None)
        assert(not(text is None and item is None))
        if item:
            self.item = item
        else:
            self.parse(text=text)

    def update(self, item, modified=True):
        self.parse(item)
        self.modified = modified

    def parse(self, text=None):
        raise NotImplementedError

    def __str__(self):
        return self.key + ' ' + self.asString()

    def __repr__(self):
        return "%s(text='%s', modified=%s, index=%s)" % (
            str(self.__class__).split('.')[-1],
            self.asString(), self.modified, self.index)

    def __eq__(self, other):
        # index and modified explicitly not compared, because this is
        # used to compare new items to previously-existing items
        return self.item == other.item

class SearchElement(_SystemModelItem):
    key = 'search'

class SearchTrove(SearchElement):
    def parse(self, text):
        self.item = trovetup.TroveSpec(text)

    def asString(self):
        return shellStr(str(self.item))

class SearchLabel(SearchElement):
    def parse(self, text):
        self.item = versions.Label(text)

    def asString(self):
        return shellStr(str(self.item))

class TroveOperation(_SystemModelItem):
    def parse(self, text):
        if isinstance(text, str):
            text = [text]
        self.item = [trovetup.TroveSpec(x) for x in text]

    def __repr__(self):
        return "%s(text=['%s'], modified=%s, index=%s)" % (
            str(self.__class__).split('.')[-1],
            "', '".join(str(x) for x in self.item),
            self.modified, self.index)

    def __iter__(self):
        return iter(self.item)

    def asString(self):
        return ' '.join(shellStr(str(x)) for x in self.item)

class UpdateTroveOperation(TroveOperation):
    key = 'update'

class EraseTroveOperation(TroveOperation):
    key = 'erase'

class InstallTroveOperation(TroveOperation):
    key = 'install'

class ReplaceTroveOperation(TroveOperation):
    key = 'replace'

troveOpMap = {
    UpdateTroveOperation.key  : UpdateTroveOperation,
    EraseTroveOperation.key   : EraseTroveOperation,
    InstallTroveOperation.key : InstallTroveOperation,
    ReplaceTroveOperation.key : ReplaceTroveOperation,
}

class SystemModel:
    # Make the operation objects available via models, avoiding the
    # need to import this module when a model is provided
    SearchTrove = SearchTrove
    SearchLabel = SearchLabel
    UpdateTroveOperation = UpdateTroveOperation
    EraseTroveOperation = EraseTroveOperation
    InstallTroveOperation = InstallTroveOperation
    ReplaceTroveOperation = ReplaceTroveOperation

    def __init__(self, cfg):
        self.searchPath = []
        self.systemItems = []
        self.indexes = {}
        self.cfg = cfg

    def _addIndex(self, item):
        # normally, this list is one item long except for index None
        l = self.indexes.setdefault(item.index, [])
        if item not in l:
            l.append(item)

    def _removeIndex(self, item):
        l = self.indexes.get(item.index, [])
        while item in l:
            l.remove(item)
        if not l:
            self.indexes.pop(item.index)

    def modified(self):
        return bool([x for x in self.searchPath + self.systemItems
                     if x.modified])

    def appendToSearchPath(self, item):
        self.searchPath.append(item)
        self._addIndex(item)

    def appendTroveOp(self, op):
        # First, remove trivially obvious duplication -- more
        # complex duplicates may be removed after building the graph
        if isinstance(op, EraseTroveOperation) and self.systemItems:
            otherOp = self.systemItems[-1]
            if op == otherOp:
                if isinstance(otherOp, (UpdateTroveOperation,
                                        InstallTroveOperation)):
                    # erasing exactly the immediately-previous
                    # update or install item should remove that
                    # immediately-previous item, rather than add
                    # an explicit "erase" trove operation to the list
                    self.systemItems.pop()
                    self._removeIndex(op)
                    return
                elif (isinstance(otherOp, EraseTroveOperation)):
                    # do not add identical adjacent erase operations
                    return

        self.systemItems.append(op)
        self._addIndex(op)

    def removeTroveOp(self, op):
        self._removeIndex(op)
        while op in self.systemItems:
            self.systemItems.remove(op)

    def appendTroveOpByName(self, key, *args, **kwargs):
        op = troveOpMap[key](*args, **kwargs)
        self.appendTroveOp(op)

    def refreshSearchPath(self):
        cfg = self.cfg
        cclient = conaryclient.ConaryClient(cfg)
        repos = cclient.getRepos()

        # Find SearchTroves with any version specified, and remove any
        # trailingRevision
        # {oldTroveKey: index}
        searchItemsOld = dict((y.item, x) for x, y in enumerate(self.searchPath)
                           if isinstance(y, SearchTrove)
                              and y.item[1] is not None)
        # {newTroveKey: oldTroveKey}
        searchItemsNew = dict(((x[0], x[1].rsplit('/', 1)[0], x[2]), x)
                              for x in searchItemsOld.keys())
        searchTroves = searchItemsOld.keys() + searchItemsNew.keys()

        foundTroves = repos.findTroves(cfg.installLabelPath,
            searchTroves, defaultFlavor = cfg.flavor)

        for troveKey in foundTroves.keys():
            if troveKey in searchItemsNew:
                oldTroveKey = searchItemsNew[troveKey]
                if foundTroves[troveKey] != foundTroves[oldTroveKey]:
                    # found a new version, replace
                    foundTrove = foundTroves[troveKey][0]
                    newVersion = foundTrove[1]
                    newverstr = '%s/%s' %(newVersion.trailingLabel(),
                                          newVersion.trailingRevision())
                    item = (oldTroveKey[0], newverstr, oldTroveKey[2])
                    index = searchItemsOld[oldTroveKey]
                    self.searchPath[index].update(item)

class SystemModelText(SystemModel):
    '''
    Implements the abstract system model persisting in a text format,
    which is intended to be human-readable and human-editable.

    The format is::
        search troveSpec|label
        update troveSpec+
        erase troveSpec+
        install troveSpec+
        replace troveSpec+

    C{search} lines take a single troveSpec or label, which B{may} be
    enclosed in single or double quote characters.  Each C{search}
    item B{appends} to the search path.  The C{installLabelPath}}
    configuration item is implicitly appended to the specified
    C{searchPath}.

    C{update}, C{erase}, C{install}, and C{replace} lines take
    one or more troveSpecs, which B{may} be enclosed in single
    or double quote characters, unless they contain characters
    that may be specially interpreted by a POSIX shell, in
    which case they B{must} be enclosed in quotes.  Each item
    updated, installed, or replaced is C{prepended} to the search
    path used for C{subsequent} items, if it is not found explicitly
    via previous search path items.

    Whole-line comments are retained, and ordering is preserved
    with respect to non-comment lines.

    Partial-line comments are ignored, and not retained when a
    line is modified.
    '''

    def __init__(self, cfg):
        SystemModel.__init__(self, cfg)
        self.commentLines = []
        self.filedata = []

    def parse(self, fileData=None, fileName='(internal)'):
        if fileData is not None:
            self.filedata = fileData

        for index, line in enumerate(self.filedata):
            line = line.strip()

            if line.startswith('#') or not line:
                # empty lines are handled just like comments, and empty
                # lines and comments are always looked up in the
                # unmodified filedata, so we store only the index
                self.commentLines.append(index)
                continue

            # non-empty, non-comment lines must be parsed
            try:
                verb, nouns = line.split(None, 1)
            except:
                raise SystemModelError('%s: Invalid statement on line %d' %(
                                       fileName, index))

            if verb == 'search':
                if self.systemItems:
                    # If users provide a "search" line after a trove
                    # operation, they may expect it to be evaluated
                    # later.  Warn them that this is not actually
                    # going to happen.  (When adding "include", then
                    # this warning should apply only to the outmost
                    # file, not to included files.)
                    log.syslog('warning: %s line %d:'
                        ' "search" entry follows operations:'
                        ' but will still be honored for prior'
                        ' operations' %fileName, index)
                # Handle it if quoted, but it doesn't need to be
                nouns = ' '.join(shlex.split(nouns, comments=True))
                try:
                    searchItem = SearchLabel(text=nouns,
                                             modified=False, index=index)
                except conary.errors.ParseError:
                    searchItem = SearchTrove(text=nouns,
                                             modified=False, index=index)
                self.appendToSearchPath(searchItem)

            elif verb in troveOpMap:
                self.appendTroveOpByName(verb,
                    text=shlex.split(nouns, comments=True),
                    modified=False, index=index)

            else:
                raise SystemModelError(
                    '%s: Unrecognized command "%s" on line %d' %(
                    fileName, verb, index))

    def iterFormat(self):
        '''
        Serialize the current model, including preserved comments.
        '''
        commentLines = list(self.commentLines) # copy

        lastSearchLine = max([x.index for x in self.searchPath] + [0])
        lastOpLine = max([x.index for x in self.systemItems] + [0])
        newSearchItems = [x for x in self.searchPath if x.index is None]
        newOperations = [x for x in self.systemItems if x.index is None]
        lastIndexLine = max(lastSearchLine, lastOpLine, max(commentLines + [0]))

        for i in range(lastIndexLine+1):
            # First, emit all prior comments in order
            while commentLines and commentLines[0] <= i:
                yield self.filedata[commentLines.pop(0)]

            if i in self.indexes:
                # Next, emit all the specified lines
                for item in self.indexes[i]:
                    # normally, this list is one item long
                    if item.modified:
                        yield str(item) + '\n'
                    else:
                        yield self.filedata[i]
                        # handle models lacking trailing newlines
                        if self.filedata[i] and self.filedata[i][-1] != '\n':
                            yield '\n'

            # Last, emit any remaining lines
            if i == lastSearchLine:
                for item in (x for x in self.searchPath
                             if x.index is None):
                    yield str(item) + '\n'
            if i == lastOpLine:
                for item in (x for x in self.systemItems
                             if x.index is None):
                    yield str(item) + '\n'

        # Finally, emit any trailing comments
        while commentLines:
            yield self.filedata[commentLines.pop(0)]

    def format(self):
        return ''.join(self.iterFormat())

    def write(self, f):
        f.write(self.format())

#class SystemModelXML(SystemModel):
#    '''
#    Implements the abstract system model persisting in an XML format,
#    which is intended to be machine-readable and machine-editable.
#    ...
#    '''

class SystemModelFile(object):
    def __init__(self, model, fileName='/etc/conary/system-model'):
        self.fileName = fileName
        self.root = model.cfg.root
        self.model = model

        self.fileFullName = self.root+fileName
        if self.exists():
            self.parse()

    def exists(self):
        return util.exists(self.fileFullName)

    def read(self):
        self.model.filedata = open(self.fileFullName, 'r').readlines()
        return self.model.filedata

    def parse(self, fileData=None):
        if fileData is None:
            self.read()
        else:
            self.model.filedata = fileData
        self.model.parse(fileData=self.model.filedata,
                         fileName=self.fileFullName)

    def write(self, fileName=None):
        '''
        Writes the current system model to the specified file (relative
        to the configured root), or overwrites the previously-specified
        file if no filename is provided.
        '''
        if fileName == None:
            fileName = self.fileName
        fileFullName = self.model.cfg.root+fileName

        dirName = os.path.dirname(fileFullName)
        fd, tmpName = tempfile.mkstemp(prefix='system-model', dir=dirName)
        f = os.fdopen(fd, 'w')
        self.model.write(f)
        os.rename(tmpName, fileFullName)
<|endoftext|>