<commit_before>import dolfin as df
import os
from . import *
from common.io import mpi_is_root
from common.bcs import Fixed, Charged
__author__ = "Asger Bolet"

info_cyan("Charge wall for at test of debye layers")

class Left(df.SubDomain):
    def inside(self, x, on_boundary):
        return bool(df.near(x[0],0.0) and on_boundary)

class Right(df.SubDomain):
    def __init__(self, Lx):
        self.Lx = Lx
        df.SubDomain.__init__(self)

    def inside(self, x, on_boundary):
        return bool(df.near(x[0], self.Lx) and on_boundary )

class Bottom(df.SubDomain):
    def inside(self, x, on_boundary):
        return bool(df.near(x[1],0.0) and on_boundary)

class Top(df.SubDomain):
    def __init__(self, Ly):
        self.Ly = Ly
        df.SubDomain.__init__(self)

    def inside(self, x, on_boundary):
        return bool(df.near(x[1], self.Ly) and on_boundary )

def problem():
    #         2, beta in phase 1, beta in phase 2
    solutes = [["c_p",  1, 1e-4, 1.e-3, 3., 1.],
               ["c_m", -1, 1e-4, 1.e-3, 3., 1.]]

    # Format: name : (family, degree, is_vector)
    base_elements = dict(u=["Lagrange", 2, True],
                         p=["Lagrange", 1, False],
                         phi=["Lagrange", 1, False],
                         g=["Lagrange", 1, False],
                         c=["Lagrange", 1, False],
                         V=["Lagrange", 1, False])

    factor = 1./4.

    # Default parameters to be loaded unless starting from checkpoint.
    parameters = dict(
        solver="basic",
        folder="results_charge_wall",
        restart_folder=False,
        enable_NS=True,
        enable_PF=False,
        enable_EC=True,
        save_intv=5,
        stats_intv=5,
        checkpoint_intv=50,
        tstep=0,
        dt=factor*0.08,
        t_0=0.,
        T=20.,
        dx=factor*1./16,
        interface_thickness=factor*0.080,
        solutes=solutes,
        base_elements=base_elements,
        Lx=1.,
        Ly=5.,
        rad_init=0.25,
        #
        V_top=1.,
        V_btm=0.,
        surface_tension=24.5,
        grav_const=0.0,
        #
        pf_mobility_coeff=factor*0.000040,
        density=[1000., 1000.],
        viscosity=[1., 1.],
        permittivity=[1., 5.],
        #
        initial_interface="flat",
        #
        use_iterative_solvers=False,
        use_pressure_stabilization=False
    )
    return parameters

def mesh(Lx=1, Ly=5, dx=1./16, **namespace):
    return df.RectangleMesh(df.Point(0., 0.), df.Point(Lx, Ly),
                            int(Lx/dx), int(Ly/dx))

def initialize(Lx, Ly, rad_init,
               interface_thickness, solutes, restart_folder,
               field_to_subspace,
               enable_NS, enable_PF, enable_EC, initial_interface, **namespace):
    """ Create the initial state.
    The initial states are specified in a dict indexed by field. The format
    should be
                w_init_field[field] = 'df.Function(...)'.
    The work dicts w_ and w_1 are automatically initialized from these
    functions elsewhere in the code.

    Note: You only need to specify the initial states that are nonzero.
    """

    c0 = [.001, .001]
    w_init_field = dict()
    if not restart_folder:
        if enable_EC:
            for ci, solute in zip(c0, solutes):
                c_init = initial_c(ci,
                                   field_to_subspace[solute[0]].collapse())
            V_init_expr = df.Expression("0.", degree=1)
            w_init_field["V"] = df.interpolate(
            V_init_expr, field_to_subspace["V"].collapse())

        # Phase field

        if enable_PF:
            w_init_field["phi"] = initial_phasefield(
                Lx/5, Lx/2, rad_init, interface_thickness,
                field_to_subspace["phi"].collapse(), shape=initial_interface)

    return w_init_field

def create_bcs(Lx, Ly, solutes, **namespace):
    """ The boundaries and boundary conditions are defined here. """
    boundaries = dict(
        right=[Right(Lx)],
        left=[Left(0)],
        bottom=[Bottom(0)],
        top=[Top(Ly)]
    )
    c0 = [.001, .001]
    noslip = Fixed((0., 0.))
    V_ground = Fixed(0.0)
    surfacecharge = Charged(0.0001)

    bcs = dict()

    bcs["right"] = dict(
        u=noslip,
    )
    bcs["left"] = dict(
        u=noslip
    )

    bcs["top"] = dict(
        u=noslip,
        V=surfacecharge
            )
    bcs["bottom"] = dict(
        V=V_ground
            )
    for ci, solute in zip(c0, solutes):
        bcs["bottom"][solute[0]] = Fixed(ci)

    # Apply pointwise BCs e.g. to pin pressure.
    bcs_pointwise = dict()
    bcs_pointwise["p"] = (0., "x[0] < DOLFIN_EPS && x[1] < DOLFIN_EPS")

    return boundaries, bcs, bcs_pointwise

def create_bcs_old(field_to_subspace, Lx, Ly, solutes,
               V_top, V_btm,
               enable_NS, enable_PF, enable_EC,
               **namespace):
    """ The boundary conditions are defined in terms of field. """
    bcs_fields = dict()

    # Navier-Stokes

    # Define the FacetFunction an mark all
    boundary_markers = df.FacetFunction('size_t', mesh)
    boundary_markers.set_all(mark[0])
    # Find the differet parts of the boundary
    right = Right(Lx)
    left = Left(0)
    bottom = Bottom(0)
    top = Top(Ly)

    #Mark the differt parts of boundary in the FacetFunction
    right.mark(boundary_markers,mark["wall"])
    left.mark(boundary_markers,mark["openside"])
    top.mark(boundary_markers,mark["openside"])
    bottom.mark(boundary_markers,mark["openside"])

    if enable_NS:
        freeslip = df.DirichletBC(field_to_subspace["u"].sub(1),
                                  df.Constant(0.),
                                  bottom)
        leftwall = df.DirichletBC(field_to_subspace["u"],
                                df.Constant((0., 0.)),
                                left)
        rightwall = df.DirichletBC(field_to_subspace["u"],
                                df.Constant((0., 0.)),
                                right)
        topwall = df.DirichletBC(field_to_subspace["u"],
                                df.Constant((0.,0.)),
                                top)

        bcs_fields["u"] = [leftwall, rightwall, topwall, freeslip]
        # The pressure gauge
        p_pin = df.DirichletBC(field_to_subspace["p"],
                               df.Constant(0.),
                               " x[0] < DOLFIN_EPS && x[1] < DOLFIN_EPS",
                               "pointwise")
        bcs_fields["p"] = [p_pin]

    # Phase field
    #if enable_PF:
        #phiinlet = df.DirichletBC(field_to_subspace["phi"],
        #                        df.Constant(-1.0),
        #                        left)

        #phioutlet = df.DirichletBC(field_to_subspace["phi"],
        #                        df.Constant(1.0),
        #                        right)
        #bcs_fields["phi"] = [phiinlet, phioutlet]
         #bcs_fields["g"] = []

    # Electrochemistry

    if enable_EC:
        bc_V_bottom = df.DirichletBC(field_to_subspace["V"],
                                    df.Constant(V_top),
                                    bottom)
        bcs_fields["EC"] = [bc_V_top, bc_V_btm]

        for solute in solutes:
             bcs_fields[solute[0]] = []
             bcs_fields[solute[0]] = []
        bcs_fields["V"] = [bc_V_top, bc_V_btm]
    return bcs_fields

def initial_phasefield(x0, y0, rad, eps, function_space, shape="circle"):
    if shape == "flat":
        expr_str = "tanh((x[0]-x0)/(sqrt(2)*eps))"
    elif shape == "sine":
        expr_str = "tanh((x[0]-x0-10*eps*sin(x[1]*pi))/(sqrt(2)*eps))"
    elif shape == "circle":
        expr_str = ("tanh(sqrt(2)*(sqrt(pow(x[0]-x0,2)" +
                    "+pow(x[1]-y0,2))-rad)/eps)")
    else:
        info_red("Unrecognized shape: " + shape)
        exit()
    phi_init_expr = df.Expression(expr_str, x0=x0, y0=y0, rad=rad,
                                  eps=eps, degree=2)
    phi_init = df.interpolate(phi_init_expr, function_space)
    return phi_init

def tstep_hook(t, tstep, stats_intv, statsfile, field_to_subspace,
               field_to_subproblem, subproblems, w_, **namespace):
    info_blue("Timestep = {}".format(tstep))
    if False and stats_intv and tstep % stats_intv == 0:
        # GL: Seems like a rather awkward way of doing this,
        # but any other way seems to fuck up the simulation.
        # Anyhow, a better idea could be to move some of this to a post-processing stage.
        # GL: Move into common/utilities at a certain point.
        subproblem_name, subproblem_i = field_to_subproblem["phi"]
        Q = w_[subproblem_name].split(deepcopy=True)[subproblem_i]
        bubble = df.interpolate(Q, field_to_subspace["phi"].collapse())
        bubble = 0.5*(1.-df.sign(bubble))
        mass = df.assemble(bubble*df.dx)
        massy = df.assemble(
            bubble*df.Expression("x[1]", degree=1)*df.dx)
        if mpi_is_root():
            with file(statsfile, "a") as outfile:
                outfile.write("{} {} {} \n".format(t, mass, massy))

def pf_mobility(phi, gamma):
    """ Phase field mobility function. """
    # return gamma * (phi**2-1.)**2
    func = 1.-phi**2
    return 0.75 * gamma * 0.5 * (1. + df.sign(func)) * func

def start_hook(newfolder, **namespace):
    statsfile = os.path.join(newfolder, "Statistics/stats.dat")
    return dict(statsfile=statsfile)

def initial_c(c_init, function_space):
    # expr_str = ("{c_init}*0.5*(1.-tanh(sqrt(2)*(sqrt(pow(x[0]-{x}, 2)"
    #             "+pow(x[1]-{y}, 2))-{rad})/{eps}))").format(
    #                 x=x, y=y, rad=rad, eps=eps, c_init=c_init)
    expr_str = ("c_init")
    c_init_expr = df.Expression(expr_str, c_init=c_init, degree=1)
    return df.interpolate(c_init_expr, function_space)<commit_msg>cleand up a bit<commit_after>import dolfin as df
import os
from . import *
from common.io import mpi_is_root
from common.bcs import Fixed, Charged
__author__ = "Asger Bolet"

info_cyan("Charge wall for at test of debye layers")

class Left(df.SubDomain):
    def inside(self, x, on_boundary):
        return bool(df.near(x[0],0.0) and on_boundary)

class Right(df.SubDomain):
    def __init__(self, Lx):
        self.Lx = Lx
        df.SubDomain.__init__(self)

    def inside(self, x, on_boundary):
        return bool(df.near(x[0], self.Lx) and on_boundary )

class Bottom(df.SubDomain):
    def inside(self, x, on_boundary):
        return bool(df.near(x[1],0.0) and on_boundary)

class Top(df.SubDomain):
    def __init__(self, Ly):
        self.Ly = Ly
        df.SubDomain.__init__(self)

    def inside(self, x, on_boundary):
        return bool(df.near(x[1], self.Ly) and on_boundary )

def problem():
    #         2, beta in phase 1, beta in phase 2
    solutes = [["c_p",  1, 1e-4, 1.e-3, 3., 1.],
               ["c_m", -1, 1e-4, 1.e-3, 3., 1.]]

    # Format: name : (family, degree, is_vector)
    base_elements = dict(u=["Lagrange", 2, True],
                         p=["Lagrange", 1, False],
                         phi=["Lagrange", 1, False],
                         g=["Lagrange", 1, False],
                         c=["Lagrange", 1, False],
                         V=["Lagrange", 1, False])

    factor = 1./4.

    # Default parameters to be loaded unless starting from checkpoint.
    parameters = dict(
        solver="basic",
        folder="results_charge_wall",
        restart_folder=False,
        enable_NS=True,
        enable_PF=False,
        enable_EC=True,
        save_intv=5,
        stats_intv=5,
        checkpoint_intv=50,
        tstep=0,
        dt=factor*0.08,
        t_0=0.,
        T=20.,
        dx=factor*1./16,
        interface_thickness=factor*0.080,
        solutes=solutes,
        base_elements=base_elements,
        Lx=1.,
        Ly=5.,
        rad_init=0.25,
        #
        V_top=1.,
        V_btm=0.,
        surface_tension=24.5,
        grav_const=0.0,
        #
        pf_mobility_coeff=factor*0.000040,
        density=[1000., 1000.],
        viscosity=[1., 1.],
        permittivity=[1., 5.],
        #
        initial_interface="flat",
        #
        use_iterative_solvers=False,
        use_pressure_stabilization=False
    )
    return parameters

def mesh(Lx=1, Ly=5, dx=1./16, **namespace):
    return df.RectangleMesh(df.Point(0., 0.), df.Point(Lx, Ly),
                            int(Lx/dx), int(Ly/dx))

def initialize(Lx, Ly, rad_init,
               interface_thickness, solutes, restart_folder,
               field_to_subspace,
               enable_NS, enable_PF, enable_EC, initial_interface, **namespace):
    """ Create the initial state.
    The initial states are specified in a dict indexed by field. The format
    should be
                w_init_field[field] = 'df.Function(...)'.
    The work dicts w_ and w_1 are automatically initialized from these
    functions elsewhere in the code.

    Note: You only need to specify the initial states that are nonzero.
    """

    c0 = [.001, .001]
    w_init_field = dict()
    if not restart_folder:
        if enable_EC:
            for ci, solute in zip(c0, solutes):
                c_init = initial_c(ci,
                                   field_to_subspace[solute[0]].collapse())
            V_init_expr = df.Expression("0.", degree=1)
            w_init_field["V"] = df.interpolate(
                V_init_expr, field_to_subspace["V"].collapse())

        # Phase field

        if enable_PF:
            w_init_field["phi"] = initial_phasefield(
                Lx/5, Lx/2, rad_init, interface_thickness,
                field_to_subspace["phi"].collapse(), shape=initial_interface)

    return w_init_field

def create_bcs(Lx, Ly, solutes, **namespace):
    """ The boundaries and boundary conditions are defined here. """
    boundaries = dict(
        right=[Right(Lx)],
        left=[Left(0)],
        bottom=[Bottom(0)],
        top=[Top(Ly)]
    )
    c0 = [.001, .001]
    noslip = Fixed((0., 0.))
    V_ground = Fixed(0.0)
    surfacecharge = Charged(0.0001)

    bcs = dict()

    bcs["right"] = dict(
        u=noslip,
    )
    bcs["left"] = dict(
        u=noslip
    )

    bcs["top"] = dict(
        u=noslip,
        V=surfacecharge
    )
    bcs["bottom"] = dict(
        V=V_ground
    )
    for ci, solute in zip(c0, solutes):
        bcs["bottom"][solute[0]] = Fixed(ci)

    # Apply pointwise BCs e.g. to pin pressure.
    bcs_pointwise = dict()
    bcs_pointwise["p"] = (0., "x[0] < DOLFIN_EPS && x[1] < DOLFIN_EPS")

    return boundaries, bcs, bcs_pointwise

def create_bcs_old(field_to_subspace, Lx, Ly, solutes,
               V_top, V_btm,
               enable_NS, enable_PF, enable_EC,
               **namespace):
    """ The boundary conditions are defined in terms of field. """
    bcs_fields = dict()

    # Navier-Stokes

    # Define the FacetFunction an mark all
    boundary_markers = df.FacetFunction('size_t', mesh)
    boundary_markers.set_all(mark[0])
    # Find the differet parts of the boundary
    right = Right(Lx)
    left = Left(0)
    bottom = Bottom(0)
    top = Top(Ly)

    #Mark the differt parts of boundary in the FacetFunction
    right.mark(boundary_markers,mark["wall"])
    left.mark(boundary_markers,mark["openside"])
    top.mark(boundary_markers,mark["openside"])
    bottom.mark(boundary_markers,mark["openside"])

    if enable_NS:
        freeslip = df.DirichletBC(field_to_subspace["u"].sub(1),
                                  df.Constant(0.),
                                  bottom)
        leftwall = df.DirichletBC(field_to_subspace["u"],
                                df.Constant((0., 0.)),
                                left)
        rightwall = df.DirichletBC(field_to_subspace["u"],
                                df.Constant((0., 0.)),
                                right)
        topwall = df.DirichletBC(field_to_subspace["u"],
                                df.Constant((0.,0.)),
                                top)

        bcs_fields["u"] = [leftwall, rightwall, topwall, freeslip]
        # The pressure gauge
        p_pin = df.DirichletBC(field_to_subspace["p"],
                               df.Constant(0.),
                               " x[0] < DOLFIN_EPS && x[1] < DOLFIN_EPS",
                               "pointwise")
        bcs_fields["p"] = [p_pin]

    # Phase field
    #if enable_PF:
        #phiinlet = df.DirichletBC(field_to_subspace["phi"],
        #                        df.Constant(-1.0),
        #                        left)

        #phioutlet = df.DirichletBC(field_to_subspace["phi"],
        #                        df.Constant(1.0),
        #                        right)
        #bcs_fields["phi"] = [phiinlet, phioutlet]
         #bcs_fields["g"] = []

    # Electrochemistry

    if enable_EC:
        bc_V_bottom = df.DirichletBC(field_to_subspace["V"],
                                    df.Constant(V_top),
                                    bottom)
        bcs_fields["EC"] = [bc_V_top, bc_V_btm]

        for solute in solutes:
             bcs_fields[solute[0]] = []
             bcs_fields[solute[0]] = []
        bcs_fields["V"] = [bc_V_top, bc_V_btm]
    return bcs_fields

def initial_phasefield(x0, y0, rad, eps, function_space, shape="circle"):
    if shape == "flat":
        expr_str = "tanh((x[0]-x0)/(sqrt(2)*eps))"
    elif shape == "sine":
        expr_str = "tanh((x[0]-x0-10*eps*sin(x[1]*pi))/(sqrt(2)*eps))"
    elif shape == "circle":
        expr_str = ("tanh(sqrt(2)*(sqrt(pow(x[0]-x0,2)" +
                    "+pow(x[1]-y0,2))-rad)/eps)")
    else:
        info_red("Unrecognized shape: " + shape)
        exit()
    phi_init_expr = df.Expression(expr_str, x0=x0, y0=y0, rad=rad,
                                  eps=eps, degree=2)
    phi_init = df.interpolate(phi_init_expr, function_space)
    return phi_init

def tstep_hook(t, tstep, stats_intv, statsfile, field_to_subspace,
               field_to_subproblem, subproblems, w_, **namespace):
    info_blue("Timestep = {}".format(tstep))
    if False and stats_intv and tstep % stats_intv == 0:
        # GL: Seems like a rather awkward way of doing this,
        # but any other way seems to fuck up the simulation.
        # Anyhow, a better idea could be to move some of this to a post-processing stage.
        # GL: Move into common/utilities at a certain point.
        subproblem_name, subproblem_i = field_to_subproblem["phi"]
        Q = w_[subproblem_name].split(deepcopy=True)[subproblem_i]
        bubble = df.interpolate(Q, field_to_subspace["phi"].collapse())
        bubble = 0.5*(1.-df.sign(bubble))
        mass = df.assemble(bubble*df.dx)
        massy = df.assemble(
            bubble*df.Expression("x[1]", degree=1)*df.dx)
        if mpi_is_root():
            with file(statsfile, "a") as outfile:
                outfile.write("{} {} {} \n".format(t, mass, massy))

def pf_mobility(phi, gamma):
    """ Phase field mobility function. """
    # return gamma * (phi**2-1.)**2
    func = 1.-phi**2
    return 0.75 * gamma * 0.5 * (1. + df.sign(func)) * func

def start_hook(newfolder, **namespace):
    statsfile = os.path.join(newfolder, "Statistics/stats.dat")
    return dict(statsfile=statsfile)

def initial_c(c_init, function_space):
    # expr_str = ("{c_init}*0.5*(1.-tanh(sqrt(2)*(sqrt(pow(x[0]-{x}, 2)"
    #             "+pow(x[1]-{y}, 2))-{rad})/{eps}))").format(
    #                 x=x, y=y, rad=rad, eps=eps, c_init=c_init)
    expr_str = ("c_init")
    c_init_expr = df.Expression(expr_str, c_init=c_init, degree=1)
    return df.interpolate(c_init_expr, function_space)<|endoftext|>


<commit_before>from typing import Any, Type, Optional, Set, Dict

def _name(type_: Type) -> str:
    return type_.__name__ if hasattr(type_, "__name__") else str(type_)

class DaciteError(Exception):
    pass

class DaciteFieldError(DaciteError):
    def __init__(self, field_path: Optional[str] = None):
        super().__init__()
        self.field_path = field_path

    def update_path(self, parent_field_path: str) -> None:
        if self.field_path:
            self.field_path = f"{parent_field_path}.{self.field_path}"
        else:
            self.field_path = parent_field_path

class WrongTypeError(DaciteFieldError):
    def __init__(self, field_type: Type, value: Any, field_path: Optional[str] = None) -> None:
        super().__init__(field_path=field_path)
        self.field_type = field_type
        self.value = value

    def __str__(self) -> str:
        return (
            f'wrong value type for field "{self.field_path}" - should be "{_name(self.field_type)}" '
            f'instead of value "{self.value}" of type "{_name(type(self.value))}"'
        )

class MissingValueError(DaciteFieldError):
    def __init__(self, field_path: Optional[str] = None):
        super().__init__(field_path=field_path)

    def __str__(self) -> str:
        return f'missing value for field "{self.field_path}"'

class UnionMatchError(WrongTypeError):
    def __str__(self) -> str:
        return (
            f'can not match type "{_name(type(self.value))}" to any type '
            f'of "{self.field_path}" union: {_name(self.field_type)}'
        )

class StrictUnionMatchError(DaciteFieldError):
    def __init__(self, union_matches: Dict[Type, Any], field_path: Optional[str] = None) -> None:
        super().__init__(field_path=field_path)
        self.union_matches = union_matches

    def __str__(self) -> str:
        conflicting_types = ", ".join(_name(type_) for type_ in self.union_matches)
        return f'can not choose between possible Union matches for field "{self.field_path}": {conflicting_types}'

class ForwardReferenceError(DaciteError):
    def __init__(self, message: str) -> None:
        super().__init__()
        self.message = message

    def __str__(self) -> str:
        return f"can not resolve forward reference: {self.message}"

class UnexpectedDataError(DaciteError):
    def __init__(self, keys: Set[str]) -> None:
        super().__init__()
        self.keys = keys

    def __str__(self) -> str:
        formatted_keys = ", ".join(f'"{key}"' for key in self.keys)
        return f"can not match {formatted_keys} to any data class field"
<commit_msg>Added checking for union type (#169)<commit_after>from typing import Any, Type, Optional, Set, Dict
from dacite.types import is_union

def _name(type_: Type) -> str:
    return type_.__name__ if hasattr(type_, "__name__") and not is_union(type_) else str(type_)

class DaciteError(Exception):
    pass

class DaciteFieldError(DaciteError):
    def __init__(self, field_path: Optional[str] = None):
        super().__init__()
        self.field_path = field_path

    def update_path(self, parent_field_path: str) -> None:
        if self.field_path:
            self.field_path = f"{parent_field_path}.{self.field_path}"
        else:
            self.field_path = parent_field_path

class WrongTypeError(DaciteFieldError):
    def __init__(self, field_type: Type, value: Any, field_path: Optional[str] = None) -> None:
        super().__init__(field_path=field_path)
        self.field_type = field_type
        self.value = value

    def __str__(self) -> str:
        return (
            f'wrong value type for field "{self.field_path}" - should be "{_name(self.field_type)}" '
            f'instead of value "{self.value}" of type "{_name(type(self.value))}"'
        )

class MissingValueError(DaciteFieldError):
    def __init__(self, field_path: Optional[str] = None):
        super().__init__(field_path=field_path)

    def __str__(self) -> str:
        return f'missing value for field "{self.field_path}"'

class UnionMatchError(WrongTypeError):
    def __str__(self) -> str:
        return (
            f'can not match type "{_name(type(self.value))}" to any type '
            f'of "{self.field_path}" union: {_name(self.field_type)}'
        )

class StrictUnionMatchError(DaciteFieldError):
    def __init__(self, union_matches: Dict[Type, Any], field_path: Optional[str] = None) -> None:
        super().__init__(field_path=field_path)
        self.union_matches = union_matches

    def __str__(self) -> str:
        conflicting_types = ", ".join(_name(type_) for type_ in self.union_matches)
        return f'can not choose between possible Union matches for field "{self.field_path}": {conflicting_types}'

class ForwardReferenceError(DaciteError):
    def __init__(self, message: str) -> None:
        super().__init__()
        self.message = message

    def __str__(self) -> str:
        return f"can not resolve forward reference: {self.message}"

class UnexpectedDataError(DaciteError):
    def __init__(self, keys: Set[str]) -> None:
        super().__init__()
        self.keys = keys

    def __str__(self) -> str:
        formatted_keys = ", ".join(f'"{key}"' for key in self.keys)
        return f"can not match {formatted_keys} to any data class field"
<|endoftext|>


<commit_before>
import json

#import incident_class
#import location
from datetime import date
from datetime import time

class Location:
    def __init__(self, name, group):
        self.lat = 42.727
        self.long = -73.676
        self.location_name = name
        self.location_group = group

    def setCoords(self, _lat, _long):
        self.lat = _lat
        self.long = _long

##this will be initialized using strings and datetime objects created from the information in the mongo db entries
class Incident:
    def __init__(self, _event_num, _incident_type, _location, _date_occurred, _date_reported):
        self.event_num = _event_num #int
        self.incident_type = _incident_type #string
        self.location = _location #location description
        #self.event_description = _description #string

        ##just use python built-in date objects for these::
        self.date_reported = _date_reported #datetime.date
        self.date_occurred = _date_occurred #datetime.date

class LocationData():

    def __init__(self):

        self.north = {"GYMNASIUM, '87", "CAMPUS PARKING, NORTH LOT", "E-COMPLEX", "COLONIE APARTMENTS", "Heffner", "J-BUILDING", "SAGE AVENUE", "BLITMAN RESIDENCE COMMONS"}

        self.east = {"EAST CAMPUS ATHLETIC VILLAGE", "HOUSTON FIELD HOUSE", "BURDETT AVENUE RESIDENCE", "DAVISON HALL", "NASON HALL", "CROCKETT HALL", "BARTON HALL", "RENSSELAER UNION", "BRAY HALL" "RAHPS - ALBRIGHT", "RAHPS-B", "COMMONS DINING HALL (FRES", "COMMONS PARKING", "Robinson Pool", "Mueller Center", "Quadrangle Dorms", "DEPARTMENT OF PUBLIC SAFETY", "NED HARKNESS ATHLETIC FIE", "Stackwyck", "Sherry Road", "BRYCKWYCK APARTMENTS", "WARREN HALL", "Cary Hall", "BRINSMADE TERRACE", "Sharp Hall", "Critical Facility", "NUGENT HALL"}

        self.off = {"OTHER OFF-CAMPUS LOCATION"}
        self.west = {"POLYTECH APARTMENTS", "CITY STATION"}
        self.south = {}
        self.academic = {"RUSSELL SAGE LABORATORY", "COGSWELL LABORATORY", "GREENE BUILDING", "JONSSON ENGINEERING CENTE", "ACADEMY HALL"}
        self.default_group = "RPI"
        #self.missing_coords = {}

    def locationGroup(self, loc):
        if(loc in self.north): return "North"
        elif(loc in self.off): return "Off Campus"
        elif(loc in self.west): return "West"
        elif(loc in self.south): return "South"
        else:
            return self.default_group

class JsonToIncident:

    def __init__(self):
        self.begin_date = date(2016, 10, 1)
        self.end_date = date(2016, 10, 31)

        self.location_data = LocationData()
        self.json_files = {(10,2016):"test.json", (11,2016): "NOV_16.json"}

    #returns list of dictionaries for months matching date range
    def getJsonDic(self):
        json_dic_list = [] #list of dictionaries with all json files of specified date range
        m = self.begin_date.month
        y = self.begin_date.year

        while (y <= date.today().year):
            time_pair = (m, y)
            if time_pair in self.json_files:
                with open(self.json_files[time_pair]) as f:
                    incid = json.load(f) #list of dictionaries containing json info
                json_dic_list = json_dic_list + incid

            m = m+1
            if (m == 12):
                m = 1
                y = y + 1

            if (y > self.end_date.year): break
            elif (m > self.end_date.month and y == self.end_date.year): break

        return json_dic_list

    def assignLocationGroup(self, location):
        location = location.upper()
        return self.location_data.locationGroup(location)

    def createIncidents(self):

        incidents = {}

        incid = self.getJsonDic()

        d = self.begin_date
        i = 0

        while (i < len(incid)):
            inc = incid[i]
            inc_date_occ = inc['event #'].split("-")
            date_occurred = date(2000 + int(inc_date_occ[0]), int(inc_date_occ[1]), int(inc_date_occ[2]) )

            if(date_occurred >= self.end_date):
                break
            elif (date_occurred >= self.begin_date and not(inc['event #'] in incidents) ):
                #print(inc)
                inc_date_rep = inc['date reported'].split(" ", 1)
                inc_date_rep = inc_date_rep[0].split("/")
                date_reported = date(2000 + int(inc_date_rep[2]), int(inc_date_rep[0]), int(inc_date_rep[1]))

                loc = Location(inc['location'], self.assignLocationGroup(inc['location']))
                inc_obj = Incident(inc['event #'], incid[i]['incident'], loc, date_occurred, date_reported)

                incidents[inc['event #']] = inc_obj
            i = i + 1

        print(len(list(incidents.values() )))
        return list(incidents.values() )

    def setDateRange(self, _begin, _end):
        assert(_begin <= _end)
        self.begin_date = _begin
        self.end_date = _end

class IncidentToJson():

    def __init__(self):
        pass

    def dumpJSON(self, file_obj, incid_dic):
        #docs_list = list(incid_dic)
        json_docs = json.dumps(incid_dic, indent = 4)
        file_obj.write(json_docs)

    def createJson(self, incidents):

        fname = 'incidents.txt'

        with open(fname, 'w') as json_file:
            for incid in incidents:

                incid_dic = {'event #': incid.event_num, 'incident_type': incid.incident_type, 'location': incid.location.location_name, 'location group': incid.location.location_group, 'latitude': incid.location.lat, "longitude": incid.location.long, 'date reported': incid.date_reported.isoformat(), 'date_occurred': incid.date_occurred.isoformat()}

                print(incid_dic)
                self.dumpJSON(json_file, incid_dic)

        json_file.close()

        return fname

#holds selection of incidents based on date range
class IncidentCache:

    #init will take in date objects made outside of the cache class in the main function upon start up reflecting the range of dates in the database that we want to pull incidents from
    def __init__(self):
        self.incidents = [] #list of incident objects
        self.begin_date = date(date.today().year, date.today().month-1, 1) #default starting last month
        self.end_date = date.today()

        self.JtoI = JsonToIncident()

    def setCacheByDate(self, _begin_date, _end_date):

        if (len(self.incidents) == 0):
            self.begin_date = _begin_date
            self.end_date = _end_date
            self.fullyPopulateCache()
        elif (_begin_date == self.begin_date and _end_date == self.end_date):
            return
        else:
            self._setCacheByDate(_begin_date, _end_date)

    def fullyPopulateCache(self):
        self.JtoI.setDateRange(self.begin_date, self.end_date)
        self.incidents = self.JtoI.createIncidents()

    def _setCacheByDate(self, new_begin, new_end):

        assert(new_begin <= date.today() and new_end <= date.today())

        new_incidents = []

        for incid in self.incidents:
            if (incid.date_occurred <= new_end and incid.date_occurred >= new_begin):
                new_incidents.append(incid)

        if (new_begin < self.begin_date):
            self.JtoI.setDateRange(new_begin, self.begin_date)
            new_incidents = new_incidents + self.JtoI.createIncidents()

        if (new_end > self.end_date):
            self.JtoI.setDateRange(self.end_date, new_end)
            new_incidents = new_incidents + self.JtoI.createIncidents()

        self.begin_date = new_begin
        self.end_date = new_end

        self.incidents = new_incidents

def getCacheJsonByMonth(month):
    cache = IncidentCache()

    cache.setCacheByDate(date(2016, month, 1), date(2016, month, 31))

    ItoJ = IncidentToJson()

    return ItoJ.createJson(cache.incidents)

<commit_msg>Update incident_generator_class.py<commit_after>
import json

#import incident_class
#import location
from datetime import date
from datetime import time

class Location:
    def __init__(self, name, group):
        self.lat = 42.727
        self.long = -73.676
        self.location_name = name
        self.location_group = group

    def setCoords(self, _lat, _long):
        self.lat = _lat
        self.long = _long

##this will be initialized using strings and datetime objects created from the information in the mongo db entries
class Incident:
    def __init__(self, _event_num, _incident_type, _location, _date_occurred, _date_reported):
        self.event_num = _event_num #int
        self.incident_type = _incident_type #string
        self.location = _location #location description
        #self.event_description = _description #string

        ##just use python built-in date objects for these::
        self.date_reported = _date_reported #datetime.date
        self.date_occurred = _date_occurred #datetime.date

class LocationData():

    def __init__(self):

        self.north = {"GYMNASIUM, '87", "CAMPUS PARKING, NORTH LOT", "E-COMPLEX", "COLONIE APARTMENTS", "Heffner", "J-BUILDING", "SAGE AVENUE", "BLITMAN RESIDENCE COMMONS"}

        self.east = {"EAST CAMPUS ATHLETIC VILLAGE", "HOUSTON FIELD HOUSE", "BURDETT AVENUE RESIDENCE", "DAVISON HALL", "NASON HALL", "CROCKETT HALL", "BARTON HALL", "RENSSELAER UNION", "BRAY HALL" "RAHPS - ALBRIGHT", "RAHPS-B", "COMMONS DINING HALL (FRES", "COMMONS PARKING", "Robinson Pool", "Mueller Center", "Quadrangle Dorms", "DEPARTMENT OF PUBLIC SAFETY", "NED HARKNESS ATHLETIC FIE", "Stackwyck", "Sherry Road", "BRYCKWYCK APARTMENTS", "WARREN HALL", "Cary Hall", "BRINSMADE TERRACE", "Sharp Hall", "Critical Facility", "NUGENT HALL"}

        self.off = {"OTHER OFF-CAMPUS LOCATION"}
        self.west = {"POLYTECH APARTMENTS", "CITY STATION"}
        self.south = {}
        self.academic = {"RUSSELL SAGE LABORATORY", "COGSWELL LABORATORY", "GREENE BUILDING", "JONSSON ENGINEERING CENTE", "ACADEMY HALL"}
        self.default_group = "RPI"
        #self.missing_coords = {}

    def locationGroup(self, loc):
        if(loc in self.north): return "North"
        elif(loc in self.off): return "Off Campus"
        elif(loc in self.west): return "West"
        elif(loc in self.south): return "South"
        else:
            return self.default_group

class JsonToIncident:

    def __init__(self):
        self.begin_date = date(2016, 10, 1)
        self.end_date = date(2016, 10, 31)

        self.location_data = LocationData()
        self.json_files = {(10,2016):"OCT_16.json", (11,2016): "NOV_16.json"}

    #returns list of dictionaries for months matching date range
    def getJsonDic(self):
        json_dic_list = [] #list of dictionaries with all json files of specified date range
        m = self.begin_date.month
        y = self.begin_date.year

        while (y <= date.today().year):
            time_pair = (m, y)
            if time_pair in self.json_files:
                with open(self.json_files[time_pair]) as f:
                    incid = json.load(f) #list of dictionaries containing json info
                json_dic_list = json_dic_list + incid

            m = m+1
            if (m == 12):
                m = 1
                y = y + 1

            if (y > self.end_date.year): break
            elif (m > self.end_date.month and y == self.end_date.year): break

        return json_dic_list

    def assignLocationGroup(self, location):
        location = location.upper()
        return self.location_data.locationGroup(location)

    def createIncidents(self):

        incidents = {}

        incid = self.getJsonDic()

        d = self.begin_date
        i = 0

        while (i < len(incid)):
            inc = incid[i]
            inc_date_occ = inc['event #'].split("-")
            date_occurred = date(2000 + int(inc_date_occ[0]), int(inc_date_occ[1]), int(inc_date_occ[2]) )

            if(date_occurred >= self.end_date):
                break
            elif (date_occurred >= self.begin_date and not(inc['event #'] in incidents) ):
                #print(inc)
                inc_date_rep = inc['date reported'].split(" ", 1)
                inc_date_rep = inc_date_rep[0].split("/")
                date_reported = date(2000 + int(inc_date_rep[2]), int(inc_date_rep[0]), int(inc_date_rep[1]))

                loc = Location(inc['location'], self.assignLocationGroup(inc['location']))
                inc_obj = Incident(inc['event #'], incid[i]['incident'], loc, date_occurred, date_reported)

                incidents[inc['event #']] = inc_obj
            i = i + 1

        print(len(list(incidents.values() )))
        return list(incidents.values() )

    def setDateRange(self, _begin, _end):
        assert(_begin <= _end)
        self.begin_date = _begin
        self.end_date = _end

class IncidentToJson():

    def __init__(self):
        pass

    def dumpJSON(self, file_obj, incid_dic):
        #docs_list = list(incid_dic)
        json_docs = json.dumps(incid_dic, indent = 4)
        file_obj.write(json_docs)

    def createJson(self, incidents):

        fname = 'incidents.txt'

        with open(fname, 'w') as json_file:
            for incid in incidents:

                incid_dic = {'event #': incid.event_num, 'incident_type': incid.incident_type, 'location': incid.location.location_name, 'location group': incid.location.location_group, 'latitude': incid.location.lat, "longitude": incid.location.long, 'date reported': incid.date_reported.isoformat(), 'date_occurred': incid.date_occurred.isoformat()}

                print(incid_dic)
                self.dumpJSON(json_file, incid_dic)

        json_file.close()

        return fname

#holds selection of incidents based on date range
class IncidentCache:

    #init will take in date objects made outside of the cache class in the main function upon start up reflecting the range of dates in the database that we want to pull incidents from
    def __init__(self):
        self.incidents = [] #list of incident objects
        self.begin_date = date(date.today().year, date.today().month-1, 1) #default starting last month
        self.end_date = date.today()

        self.JtoI = JsonToIncident()

    def setCacheByDate(self, _begin_date, _end_date):

        if (len(self.incidents) == 0):
            self.begin_date = _begin_date
            self.end_date = _end_date
            self.fullyPopulateCache()
        elif (_begin_date == self.begin_date and _end_date == self.end_date):
            return
        else:
            self._setCacheByDate(_begin_date, _end_date)

    def fullyPopulateCache(self):
        self.JtoI.setDateRange(self.begin_date, self.end_date)
        self.incidents = self.JtoI.createIncidents()

    def _setCacheByDate(self, new_begin, new_end):

        assert(new_begin <= date.today() and new_end <= date.today())

        new_incidents = []

        for incid in self.incidents:
            if (incid.date_occurred <= new_end and incid.date_occurred >= new_begin):
                new_incidents.append(incid)

        if (new_begin < self.begin_date):
            self.JtoI.setDateRange(new_begin, self.begin_date)
            new_incidents = new_incidents + self.JtoI.createIncidents()

        if (new_end > self.end_date):
            self.JtoI.setDateRange(self.end_date, new_end)
            new_incidents = new_incidents + self.JtoI.createIncidents()

        self.begin_date = new_begin
        self.end_date = new_end

        self.incidents = new_incidents

def getCacheJsonByMonth(month):
    cache = IncidentCache()

    cache.setCacheByDate(date(2016, month, 1), date(2016, month, 31))

    ItoJ = IncidentToJson()

    return ItoJ.createJson(cache.incidents)

<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
#
# Python Client for eAPI documentation build configuration file, created by
# sphinx-quickstart on Sat Mar 28 22:43:11 2015.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.

import sys
import os
import re
import sphinx_rtd_theme

# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
sys.path.insert(0, '../pyeapi')

# -- General configuration ------------------------------------------------

# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'

# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
    'sphinx.ext.autodoc',
    'sphinx.ext.coverage',
    'sphinx.ext.viewcode',
    'sphinx.ext.doctest',
    'sphinxcontrib.napoleon'
]

# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']

# The suffix of source filenames.
source_suffix = '.rst'

# The encoding of source files.
#source_encoding = 'utf-8-sig'

# The master toctree document.
master_doc = 'index'

# General information about the project.
project = u'Python Client for eAPI'
copyright = u'2015, Arista EOS+ CS'

# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
release = open('../VERSION').read().split()[0].strip()
# Assume PEP 440 version strings
p = re.compile(r'(\d+!)?((\d+)(.\d+)*(.\d+)*)(.?[a|b|rc]\d*)?(.post\d*)?(.dev\d*)?', re.IGNORECASE)
vers = p.search(release)

if vers:
    version = vers.group(2)
else:
    version = 'develop'

# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None

# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'

# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build']

# The reST default role (used for this markup: `text`) to use for all
# documents.
#default_role = None

# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True

# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True

# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False

# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'

# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []

# If true, keep warnings as "system message" paragraphs in the built documents.
#keep_warnings = False

# -- Options for HTML output ----------------------------------------------

# The theme to use for HTML and HTML Help pages.  See the documentation for
# a list of builtin themes.
html_theme = 'sphinx_rtd_theme'

# Theme options are theme-specific and customize the look and feel of a theme
# further.  For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}

# Add any paths that contain custom themes here, relative to this directory.
html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]

# The name for this set of Sphinx documents.  If None, it defaults to
# "<project> v<release> documentation".
#html_title = None

# A shorter title for the navigation bar.  Default is the same as html_title.
#html_short_title = None

# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None

# The name of an image file (within the static path) to use as favicon of the
# docs.  This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None

# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']

# Add any extra paths that contain custom files (such as robots.txt or
# .htaccess) here, relative to this directory. These files are copied
# directly to the root of the documentation.
#html_extra_path = []

# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'

# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True

# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}

# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}

# If false, no module index is generated.
#html_domain_indices = True

# If false, no index is generated.
#html_use_index = True

# If true, the index is split into individual pages for each letter.
#html_split_index = False

# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True

# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True

# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True

# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it.  The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''

# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None

# Output file base name for HTML help builder.
htmlhelp_basename = 'PythonClientforeAPIdoc'

# -- Options for LaTeX output ---------------------------------------------

latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',

# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',

# Additional stuff for the LaTeX preamble.
#'preamble': '',
}

# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
#  author, documentclass [howto, manual, or own class]).
latex_documents = [
  ('index', 'PythonClientforeAPI.tex', u'Python Client for eAPI Documentation',
   u'Arista EOS+ CS', 'manual'),
]

# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None

# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False

# If true, show page references after internal links.
#latex_show_pagerefs = False

# If true, show URL addresses after external links.
#latex_show_urls = False

# Documents to append as an appendix to all manuals.
#latex_appendices = []

# If false, no module index is generated.
#latex_domain_indices = True

# -- Options for manual page output ---------------------------------------

# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
    ('index', 'pythonclientforeapi', u'Python Client for eAPI Documentation',
     [u'Arista EOS+ CS'], 1)
]

# If true, show URL addresses after external links.
#man_show_urls = False

# -- Options for Texinfo output -------------------------------------------

# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
#  dir menu entry, description, category)
texinfo_documents = [
  ('index', 'PythonClientforeAPI', u'Python Client for eAPI Documentation',
   u'Arista EOS+ CS', 'PythonClientforeAPI', 'One line description of project.',
   'Miscellaneous'),
]

# Documents to append as an appendix to all manuals.
#texinfo_appendices = []

# If false, no module index is generated.
#texinfo_domain_indices = True

# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'

# If true, do not generate a @detailmenu in the "Top" node's menu.
#texinfo_no_detailmenu = False

# -- Options for Epub output ----------------------------------------------

# Bibliographic Dublin Core info.
epub_title = u'Python Client for eAPI'
epub_author = u'Arista EOS+ CS'
epub_publisher = u'Arista EOS+ CS'
epub_copyright = u'2015, Arista EOS+ CS'

# The basename for the epub file. It defaults to the project name.
#epub_basename = u'Python Client for eAPI'

# The HTML theme for the epub output. Since the default themes are not optimized
# for small screen space, using the same theme for HTML and epub output is
# usually not wise. This defaults to 'epub', a theme designed to save visual
# space.
#epub_theme = 'epub'

# The language of the text. It defaults to the language option
# or en if the language is not set.
#epub_language = ''

# The scheme of the identifier. Typical schemes are ISBN or URL.
#epub_scheme = ''

# The unique identifier of the text. This can be a ISBN number
# or the project homepage.
#epub_identifier = ''

# A unique identification for the text.
#epub_uid = ''

# A tuple containing the cover image and cover page html template filenames.
#epub_cover = ()

# A sequence of (type, uri, title) tuples for the guide element of content.opf.
#epub_guide = ()

# HTML files that should be inserted before the pages created by sphinx.
# The format is a list of tuples containing the path and title.
#epub_pre_files = []

# HTML files shat should be inserted after the pages created by sphinx.
# The format is a list of tuples containing the path and title.
#epub_post_files = []

# A list of files that should not be packed into the epub file.
epub_exclude_files = ['search.html']

# The depth of the table of contents in toc.ncx.
#epub_tocdepth = 3

# Allow duplicate toc entries.
#epub_tocdup = True

# Choose between 'default' and 'includehidden'.
#epub_tocscope = 'default'

# Fix unsupported image types using the PIL.
#epub_fix_images = False

# Scale large images.
#epub_max_image_width = 0

# How to display URL addresses: 'footnote', 'no', or 'inline'.
#epub_show_urls = 'inline'

# If false, no index is generated.
#epub_use_index = True
<commit_msg>docs: fixing #231<commit_after># -*- coding: utf-8 -*-
#
# Python Client for eAPI documentation build configuration file, created by
# sphinx-quickstart on Sat Mar 28 22:43:11 2015.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.

import sys
import os
import re
import sphinx_rtd_theme

# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
sys.path.insert(0, '../pyeapi')

# -- General configuration ------------------------------------------------

# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'

# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
    'sphinx.ext.autodoc',
    'sphinx.ext.coverage',
    'sphinx.ext.viewcode',
    'sphinx.ext.doctest',
    'sphinx.ext.napoleon'
]

# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']

# The suffix of source filenames.
source_suffix = '.rst'

# The encoding of source files.
#source_encoding = 'utf-8-sig'

# The master toctree document.
master_doc = 'index'

# General information about the project.
project = u'Python Client for eAPI'
copyright = u'2015, Arista EOS+ CS'

# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
release = open('../VERSION').read().split()[0].strip()
# Assume PEP 440 version strings
p = re.compile(r'(\d+!)?((\d+)(.\d+)*(.\d+)*)(.?[a|b|rc]\d*)?(.post\d*)?(.dev\d*)?', re.IGNORECASE)
vers = p.search(release)

if vers:
    version = vers.group(2)
else:
    version = 'develop'

# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None

# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'

# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build']

# The reST default role (used for this markup: `text`) to use for all
# documents.
#default_role = None

# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True

# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True

# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False

# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'

# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []

# If true, keep warnings as "system message" paragraphs in the built documents.
#keep_warnings = False

# -- Options for HTML output ----------------------------------------------

# The theme to use for HTML and HTML Help pages.  See the documentation for
# a list of builtin themes.
html_theme = 'sphinx_rtd_theme'

# Theme options are theme-specific and customize the look and feel of a theme
# further.  For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}

# Add any paths that contain custom themes here, relative to this directory.
html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]

# The name for this set of Sphinx documents.  If None, it defaults to
# "<project> v<release> documentation".
#html_title = None

# A shorter title for the navigation bar.  Default is the same as html_title.
#html_short_title = None

# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None

# The name of an image file (within the static path) to use as favicon of the
# docs.  This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None

# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']

# Add any extra paths that contain custom files (such as robots.txt or
# .htaccess) here, relative to this directory. These files are copied
# directly to the root of the documentation.
#html_extra_path = []

# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'

# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True

# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}

# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}

# If false, no module index is generated.
#html_domain_indices = True

# If false, no index is generated.
#html_use_index = True

# If true, the index is split into individual pages for each letter.
#html_split_index = False

# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True

# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True

# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True

# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it.  The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''

# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None

# Output file base name for HTML help builder.
htmlhelp_basename = 'PythonClientforeAPIdoc'

# -- Options for LaTeX output ---------------------------------------------

latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',

# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',

# Additional stuff for the LaTeX preamble.
#'preamble': '',
}

# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
#  author, documentclass [howto, manual, or own class]).
latex_documents = [
  ('index', 'PythonClientforeAPI.tex', u'Python Client for eAPI Documentation',
   u'Arista EOS+ CS', 'manual'),
]

# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None

# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False

# If true, show page references after internal links.
#latex_show_pagerefs = False

# If true, show URL addresses after external links.
#latex_show_urls = False

# Documents to append as an appendix to all manuals.
#latex_appendices = []

# If false, no module index is generated.
#latex_domain_indices = True

# -- Options for manual page output ---------------------------------------

# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
    ('index', 'pythonclientforeapi', u'Python Client for eAPI Documentation',
     [u'Arista EOS+ CS'], 1)
]

# If true, show URL addresses after external links.
#man_show_urls = False

# -- Options for Texinfo output -------------------------------------------

# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
#  dir menu entry, description, category)
texinfo_documents = [
  ('index', 'PythonClientforeAPI', u'Python Client for eAPI Documentation',
   u'Arista EOS+ CS', 'PythonClientforeAPI', 'One line description of project.',
   'Miscellaneous'),
]

# Documents to append as an appendix to all manuals.
#texinfo_appendices = []

# If false, no module index is generated.
#texinfo_domain_indices = True

# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'

# If true, do not generate a @detailmenu in the "Top" node's menu.
#texinfo_no_detailmenu = False

# -- Options for Epub output ----------------------------------------------

# Bibliographic Dublin Core info.
epub_title = u'Python Client for eAPI'
epub_author = u'Arista EOS+ CS'
epub_publisher = u'Arista EOS+ CS'
epub_copyright = u'2015, Arista EOS+ CS'

# The basename for the epub file. It defaults to the project name.
#epub_basename = u'Python Client for eAPI'

# The HTML theme for the epub output. Since the default themes are not optimized
# for small screen space, using the same theme for HTML and epub output is
# usually not wise. This defaults to 'epub', a theme designed to save visual
# space.
#epub_theme = 'epub'

# The language of the text. It defaults to the language option
# or en if the language is not set.
#epub_language = ''

# The scheme of the identifier. Typical schemes are ISBN or URL.
#epub_scheme = ''

# The unique identifier of the text. This can be a ISBN number
# or the project homepage.
#epub_identifier = ''

# A unique identification for the text.
#epub_uid = ''

# A tuple containing the cover image and cover page html template filenames.
#epub_cover = ()

# A sequence of (type, uri, title) tuples for the guide element of content.opf.
#epub_guide = ()

# HTML files that should be inserted before the pages created by sphinx.
# The format is a list of tuples containing the path and title.
#epub_pre_files = []

# HTML files shat should be inserted after the pages created by sphinx.
# The format is a list of tuples containing the path and title.
#epub_post_files = []

# A list of files that should not be packed into the epub file.
epub_exclude_files = ['search.html']

# The depth of the table of contents in toc.ncx.
#epub_tocdepth = 3

# Allow duplicate toc entries.
#epub_tocdup = True

# Choose between 'default' and 'includehidden'.
#epub_tocscope = 'default'

# Fix unsupported image types using the PIL.
#epub_fix_images = False

# Scale large images.
#epub_max_image_width = 0

# How to display URL addresses: 'footnote', 'no', or 'inline'.
#epub_show_urls = 'inline'

# If false, no index is generated.
#epub_use_index = True
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-

# Copyright (C) 2011 Romain Bignon, Laurent Bachelier
#
# This file is part of ass2m.
#
# ass2m 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.
#
# ass2m 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 ass2m. If not, see <http://www.gnu.org/licenses/>.

from __future__ import with_statement
from contextlib import closing
import os
import re
from gzip import GzipFile

from ass2m.plugin import Plugin

from ass2m.server import Action, FileApp
from webob.exc import HTTPNotFound, HTTPPreconditionFailed

__all__ = ['AssetsPlugin']

class AssetAction(Action):
    SANITIZE_REGEXP = re.compile(r'\w+\.\w+')

    def get(self):
        filename = self.ctx.req.str_GET.get('file')
        if self.SANITIZE_REGEXP.match(filename):
            realpath = self.find_file(filename)
            if realpath:
                if self.accepts_gzip():
                    realpath = self.gzip_file(realpath)
                self.ctx.res = FileApp(realpath)
                return
            self.ctx.res = HTTPNotFound()
        else:
            self.ctx.res = HTTPPreconditionFailed()

    def find_file(self, filename):
            paths = [os.path.join(path, 'assets') for path in self.ctx.DATA_PATHS]
            for path in paths:
                realpath = os.path.join(path, filename)
                if os.path.isfile(realpath):
                    return realpath

    def accepts_gzip(self):
        return 'gzip' in self.ctx.req.accept_encoding

    def gzip_file(self, realpath):
        cachedir = os.path.join(self.ctx.storage.path, 'assets_cache')
        if not os.path.isdir(cachedir):
            os.makedirs(cachedir)
        filename = os.path.basename(realpath)
        dest = os.path.join(cachedir, filename+'.gz')
        mtime = os.path.getmtime(realpath)
        if not os.path.exists(dest) or mtime > os.path.getmtime(dest):
            with open(realpath, 'rb') as f_in:
                with closing(GzipFile(dest, 'wb')) as f_out:
                    f_out.writelines(f_in)
            os.utime(dest, (mtime, mtime))
        return dest

class AssetsPlugin(Plugin):
    def init(self):
        self.register_web_action('asset', AssetAction)
<commit_msg>First try to find a read-only gzipped copy of the asset.<commit_after># -*- coding: utf-8 -*-

# Copyright (C) 2011 Romain Bignon, Laurent Bachelier
#
# This file is part of ass2m.
#
# ass2m 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.
#
# ass2m 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 ass2m. If not, see <http://www.gnu.org/licenses/>.

from __future__ import with_statement
from contextlib import closing
import os
import re
from gzip import GzipFile

from ass2m.plugin import Plugin

from ass2m.server import Action, FileApp
from webob.exc import HTTPNotFound, HTTPPreconditionFailed

__all__ = ['AssetsPlugin']

class AssetAction(Action):
    SANITIZE_REGEXP = re.compile(r'\w+\.\w+')

    def get(self):
        filename = self.ctx.req.str_GET.get('file')
        if self.SANITIZE_REGEXP.match(filename):
            realpath = self.find_file(filename)
            if realpath:
                if self.accepts_gzip():
                    realpath = self.gzip_file(realpath)
                self.ctx.res = FileApp(realpath)
                return
            self.ctx.res = HTTPNotFound()
        else:
            self.ctx.res = HTTPPreconditionFailed()

    def find_file(self, filename):
            paths = [os.path.join(path, 'assets') for path in self.ctx.DATA_PATHS]
            for path in paths:
                realpath = os.path.join(path, filename)
                if os.path.isfile(realpath):
                    return realpath

    def accepts_gzip(self):
        return 'gzip' in self.ctx.req.accept_encoding

    def gzip_file(self, realpath):
        filename = os.path.basename(realpath)
        mtime = os.path.getmtime(realpath)

        # first look if there is a (read-only) gzipped version of the asset
        realpath_gz = realpath+'.gz'
        if os.path.exists(realpath_gz) and not mtime > os.path.getmtime(realpath_gz):
            return realpath_gz

        # then look for a local cache of that asset, if not present, create it
        cachedir = os.path.join(self.ctx.storage.path, 'assets_cache')
        dest = os.path.join(cachedir, filename+'.gz')
        if not os.path.exists(dest) or mtime > os.path.getmtime(dest):
            if not os.path.isdir(cachedir):
                os.makedirs(cachedir)
            with open(realpath, 'rb') as f_in:
                with closing(GzipFile(dest, 'wb')) as f_out:
                    f_out.writelines(f_in)
            os.utime(dest, (mtime, mtime))
        return dest

class AssetsPlugin(Plugin):
    def init(self):
        self.register_web_action('asset', AssetAction)
<|endoftext|>


<commit_before>#!/usr/bin/env python3

# daemon98.py file post-processor.
# - graphs
# - MySQL queries
# - upload

import configparser
import os
import subprocess
import sys
import syslog
import time
import traceback

from mausy5043libs.libdaemon3 import Daemon
import mausy5043funcs.fileops3 as mf
from random import randrange as rnd

# constants
DEBUG       = False
IS_JOURNALD = os.path.isfile('/bin/journalctl')
MYID        = "".join(list(filter(str.isdigit, os.path.realpath(__file__).split('/')[-1])))
MYAPP       = os.path.realpath(__file__).split('/')[-3]
NODE        = os.uname()[1]
GRAPH_UPDATE      = 10   # in minutes
SQL_UPDATE_HOUR   = GRAPH_UPDATE  # in minutes (shouldn't be shorter than GRAPH_UPDATE)
SQL_UPDATE_DAY    = 27  # in minutes
SQL_UPDATE_WEEK   = 4   # in hours
SQL_UPDATE_YEAR   = 8   # in hours

# initialise logging
syslog.openlog(ident=MYAPP, facility=syslog.LOG_LOCAL0)

class MyDaemon(Daemon):
  """Definition of daemon."""
  @staticmethod
  def run():
    iniconf         = configparser.ConfigParser()
    inisection      = MYID
    home            = os.path.expanduser('~')
    s               = iniconf.read(home + '/' + MYAPP + '/config.ini')
    mf.syslog_trace("Config file   : {0}".format(s), False, DEBUG)
    mf.syslog_trace("Options       : {0}".format(iniconf.items(inisection)), False, DEBUG)
    reporttime      = iniconf.getint(inisection, "reporttime")
    samplespercycle = iniconf.getint(inisection, "samplespercycle")
    flock           = iniconf.get(inisection, "lockfile")
    scriptname      = iniconf.get(inisection, "lftpscript")

    sampletime      = reporttime/samplespercycle         # time [s] between samples
    sqldata.get(sqldata.h_cmd)
    sqldata.get(sqldata.d_cmd)
    sqldata.get(sqldata.w_cmd)
    sqldata.get(sqldata.y_cmd)
    if (trendgraph.make() == 0):
      upload_page(scriptname)
    while True:
      try:
        starttime   = time.time()

        do_stuff(flock, home, scriptname)

        waittime    = sampletime - (time.time() - starttime) - (starttime % sampletime)
        if (waittime > 0):
          mf.syslog_trace("Waiting  : {0}s".format(waittime), False, DEBUG)
          mf.syslog_trace("................................", False, DEBUG)
          time.sleep(waittime)
      except Exception:
        mf.syslog_trace("Unexpected error in run()", syslog.LOG_CRIT, DEBUG)
        mf.syslog_trace(traceback.format_exc(), syslog.LOG_CRIT, DEBUG)
        raise

class SqlDataFetch(object):
  """
  SqlDataFetch:
  Manages retrieval of data from the MySQL server
  """
  def __init__(self, h_time, d_time, w_time, y_time):
    super(SqlDataFetch, self).__init__()
    self.home           = os.environ['HOME']
    self.h_dataisstale  = True
    self.h_cmd          = self.home + '/' + MYAPP + '/queries/hour.sh'
    self.h_updatetime   = h_time * 60
    self.h_timer        = time.time() + rnd(60, self.h_updatetime)
    self.d_dataisstale  = True
    self.d_cmd          = self.home + '/' + MYAPP + '/queries/day.sh'
    self.d_updatetime   = d_time * 60
    self.d_timer        = time.time() + rnd(60, self.d_updatetime)
    self.w_dataisstale  = True
    self.w_cmd          = self.home + '/' + MYAPP + '/queries/week.sh'
    self.w_updatetime   = w_time * 3600
    self.w_timer        = time.time() + rnd(60, self.w_updatetime)
    self.y_dataisstale  = True
    self.y_cmd          = self.home + '/' + MYAPP + '/queries/year.sh'
    self.y_updatetime   = y_time * 3600
    self.y_timer        = time.time() + rnd(60, self.y_updatetime)

  def get(self, cmnd):
    """
    Get the requested data.
    """
    mf.syslog_trace("...:  {0}".format(cmnd), False, DEBUG)
    result = subprocess.call(cmnd)
    return not (result == 0)  # return False if successful == data nolonger stale

  def fetch(self):
    """
    Manage staleness of the data and get it when needed.
    """
    ts = time.time()
    t0 = ts
    if t0 >= self.h_timer:
      self.h_dataisstale = self.get(self.h_cmd)
      t1 = time.time()
      self.h_timer = t1 + self.h_updatetime + rnd(-60, 60)
      # dt = t1 - t0  # determine query duration
      t0 = t1
    if t0 >= self.d_timer:
      self.d_dataisstale = self.get(self.d_cmd)
      t1 = time.time()
      self.d_timer = t1 + self.d_updatetime + rnd(-60, 60)
      # dt = t1 - t0  # determine query duration
      t0 = t1
    if t0 >= self.w_timer:
      self.w_dataisstale = self.get(self.w_cmd)
      t1 = time.time()
      self.w_timer = t1 + self.w_updatetime + rnd(-60, 60)
      # dt = t1 - t0  # determine query duration
      t0 = t1
    if t0 >= self.y_timer:
      self.y_dataisstale = self.get(self.y_cmd)
      t1 = time.time()
      self.y_timer = t1 + self.y_updatetime + rnd(-60, 60)
      # dt = t1 - t0  # determine query duration
    return time.time() - ts

class Graph(object):
  """docstring for Graph."""
  def __init__(self, updatetime):
    super(Graph, self).__init__()
    self.home = os.environ['HOME']
    self.updatetime = updatetime * 60
    self.timer      = time.time() + rnd(60, self.updatetime)
    self.command    = self.home + '/' + MYAPP + '/mkgraphs.sh'

  def draw(self, cmnd):
    """Draw the graphs"""
    mf.syslog_trace("...:  {0}".format(cmnd), False, DEBUG)
    return subprocess.call(cmnd)

  def make(self):
    t0 = time.time()
    result = 1
    if t0 >= self.timer:
      result = self.draw(self.command)
      t1 = time.time()
      self.timer = t1 + self.updatetime + rnd(-60, 60)
    return result

def do_stuff(flock, homedir, script):
  # wait 4 seconds for processes to finish
  time.sleep(4)

  # Retrieve data from MySQL database
  result = sqldata.fetch()
  mf.syslog_trace("...datafetch:  {0}".format(result), False, DEBUG)

  # Create the graphs based on the MySQL data
  result = trendgraph.make()
  mf.syslog_trace("...trendgrph:  {0}".format(result), False, DEBUG)
  if (result == 0):
    upload_page(script)

def upload_page(script):
  try:
    # Upload the webpage and graphs
    if os.path.isfile('/tmp/' + MYAPP + '/site/text.md'):
      write_lftp(script)
      cmnd = ['lftp', '-f', script]
      mf.syslog_trace("...:  {0}".format(cmnd), False, DEBUG)
      cmnd = subprocess.check_output(cmnd, timeout=20)
      mf.syslog_trace("...uploadpag:  {0}".format(cmnd), False, DEBUG)
  except subprocess.TimeoutExpired:
    mf.syslog_trace("***TIMEOUT***:  {0}".format(cmnd), syslog.LOG_ERR, DEBUG)
    time.sleep(17*60)             # wait 17 minutes for the router to restart.
    pass
  except subprocess.CalledProcessError:
    mf.syslog_trace("***ERROR***:    {0}".format(cmnd), syslog.LOG_ERR, DEBUG)
    time.sleep(17*60)             # wait 17 minutes for the router to restart.
    pass

def write_lftp(script):
  with open(script, 'w') as f:
    f.write('# DO NOT EDIT\n')
    f.write('# This file is created automatically by ' + MYAPP + '\n\n')
    f.write('# lftp script\n\n')
    f.write('set cmd:fail-exit yes;\n')
    f.write('open hendrixnet.nl;\n')
    f.write('cd 04.status/;\n')
    f.write('set cmd:fail-exit no;\n')
    f.write('mkdir -p -f _' + NODE + ' ;\n')
    f.write('set cmd:fail-exit yes;\n')
    f.write('cd _' + NODE + ' ;\n')
    f.write('mirror --reverse --delete --verbose=3 -c /tmp/' + MYAPP + '/site/ . ;\n')
    f.write('\n')

if __name__ == "__main__":
  daemon = MyDaemon('/tmp/' + MYAPP + '/' + MYID + '.pid')
  trendgraph = Graph(GRAPH_UPDATE)
  sqldata = SqlDataFetch(SQL_UPDATE_HOUR, SQL_UPDATE_DAY, SQL_UPDATE_WEEK, SQL_UPDATE_YEAR)
  if len(sys.argv) == 2:
    if 'start' == sys.argv[1]:
      daemon.start()
    elif 'stop' == sys.argv[1]:
      daemon.stop()
    elif 'restart' == sys.argv[1]:
      daemon.restart()
    elif 'foreground' == sys.argv[1]:
      # assist with debugging.
      print("Debug-mode started. Use <Ctrl>+C to stop.")
      DEBUG = True
      mf.syslog_trace("Daemon logging is ON", syslog.LOG_DEBUG, DEBUG)
      daemon.run()
    else:
      print("Unknown command")
      sys.exit(2)
    sys.exit(0)
  else:
    print("usage: {0!s} start|stop|restart|foreground".format(sys.argv[0]))
    sys.exit(2)
<commit_msg>issue command<commit_after>#!/usr/bin/env python3

# daemon98.py file post-processor.
# - graphs
# - MySQL queries
# - upload

import configparser
import os
import subprocess
import sys
import syslog
import time
import traceback

from mausy5043libs.libdaemon3 import Daemon
import mausy5043funcs.fileops3 as mf
from random import randrange as rnd

# constants
DEBUG       = False
IS_JOURNALD = os.path.isfile('/bin/journalctl')
MYID        = "".join(list(filter(str.isdigit, os.path.realpath(__file__).split('/')[-1])))
MYAPP       = os.path.realpath(__file__).split('/')[-3]
NODE        = os.uname()[1]
GRAPH_UPDATE      = 10   # in minutes
SQL_UPDATE_HOUR   = GRAPH_UPDATE  # in minutes (shouldn't be shorter than GRAPH_UPDATE)
SQL_UPDATE_DAY    = 27  # in minutes
SQL_UPDATE_WEEK   = 4   # in hours
SQL_UPDATE_YEAR   = 8   # in hours

# initialise logging
syslog.openlog(ident=MYAPP, facility=syslog.LOG_LOCAL0)

class MyDaemon(Daemon):
  """Definition of daemon."""
  @staticmethod
  def run():
    iniconf         = configparser.ConfigParser()
    inisection      = MYID
    home            = os.path.expanduser('~')
    s               = iniconf.read(home + '/' + MYAPP + '/config.ini')
    mf.syslog_trace("Config file   : {0}".format(s), False, DEBUG)
    mf.syslog_trace("Options       : {0}".format(iniconf.items(inisection)), False, DEBUG)
    reporttime      = iniconf.getint(inisection, "reporttime")
    samplespercycle = iniconf.getint(inisection, "samplespercycle")
    flock           = iniconf.get(inisection, "lockfile")
    scriptname      = iniconf.get(inisection, "lftpscript")

    sampletime      = reporttime/samplespercycle         # time [s] between samples
    sqldata.get(sqldata.h_cmd)
    sqldata.get(sqldata.d_cmd)
    sqldata.get(sqldata.w_cmd)
    sqldata.get(sqldata.y_cmd)
    if (trendgraph.draw(trendgraph.command) == 0):
      upload_page(scriptname)
    while True:
      try:
        starttime   = time.time()

        do_stuff(flock, home, scriptname)

        waittime    = sampletime - (time.time() - starttime) - (starttime % sampletime)
        if (waittime > 0):
          mf.syslog_trace("Waiting  : {0}s".format(waittime), False, DEBUG)
          mf.syslog_trace("................................", False, DEBUG)
          time.sleep(waittime)
      except Exception:
        mf.syslog_trace("Unexpected error in run()", syslog.LOG_CRIT, DEBUG)
        mf.syslog_trace(traceback.format_exc(), syslog.LOG_CRIT, DEBUG)
        raise

class SqlDataFetch(object):
  """
  SqlDataFetch:
  Manages retrieval of data from the MySQL server
  """
  def __init__(self, h_time, d_time, w_time, y_time):
    super(SqlDataFetch, self).__init__()
    self.home           = os.environ['HOME']
    self.h_dataisstale  = True
    self.h_cmd          = self.home + '/' + MYAPP + '/queries/hour.sh'
    self.h_updatetime   = h_time * 60
    self.h_timer        = time.time() + rnd(60, self.h_updatetime)
    self.d_dataisstale  = True
    self.d_cmd          = self.home + '/' + MYAPP + '/queries/day.sh'
    self.d_updatetime   = d_time * 60
    self.d_timer        = time.time() + rnd(60, self.d_updatetime)
    self.w_dataisstale  = True
    self.w_cmd          = self.home + '/' + MYAPP + '/queries/week.sh'
    self.w_updatetime   = w_time * 3600
    self.w_timer        = time.time() + rnd(60, self.w_updatetime)
    self.y_dataisstale  = True
    self.y_cmd          = self.home + '/' + MYAPP + '/queries/year.sh'
    self.y_updatetime   = y_time * 3600
    self.y_timer        = time.time() + rnd(60, self.y_updatetime)

  def get(self, cmnd):
    """
    Get the requested data.
    """
    mf.syslog_trace("...:  {0}".format(cmnd), False, DEBUG)
    result = subprocess.call(cmnd)
    return not (result == 0)  # return False if successful == data nolonger stale

  def fetch(self):
    """
    Manage staleness of the data and get it when needed.
    """
    ts = time.time()
    t0 = ts
    if t0 >= self.h_timer:
      self.h_dataisstale = self.get(self.h_cmd)
      t1 = time.time()
      self.h_timer = t1 + self.h_updatetime + rnd(-60, 60)
      # dt = t1 - t0  # determine query duration
      t0 = t1
    if t0 >= self.d_timer:
      self.d_dataisstale = self.get(self.d_cmd)
      t1 = time.time()
      self.d_timer = t1 + self.d_updatetime + rnd(-60, 60)
      # dt = t1 - t0  # determine query duration
      t0 = t1
    if t0 >= self.w_timer:
      self.w_dataisstale = self.get(self.w_cmd)
      t1 = time.time()
      self.w_timer = t1 + self.w_updatetime + rnd(-60, 60)
      # dt = t1 - t0  # determine query duration
      t0 = t1
    if t0 >= self.y_timer:
      self.y_dataisstale = self.get(self.y_cmd)
      t1 = time.time()
      self.y_timer = t1 + self.y_updatetime + rnd(-60, 60)
      # dt = t1 - t0  # determine query duration
    return time.time() - ts

class Graph(object):
  """docstring for Graph."""
  def __init__(self, updatetime):
    super(Graph, self).__init__()
    self.home = os.environ['HOME']
    self.updatetime = updatetime * 60
    self.timer      = time.time() + rnd(60, self.updatetime)
    self.command    = self.home + '/' + MYAPP + '/mkgraphs.sh'

  def draw(self, cmnd):
    """Draw the graphs"""
    mf.syslog_trace("...:  {0}".format(cmnd), False, DEBUG)
    return subprocess.call(cmnd)

  def make(self):
    t0 = time.time()
    result = 1
    if t0 >= self.timer:
      result = self.draw(self.command)
      t1 = time.time()
      self.timer = t1 + self.updatetime + rnd(-60, 60)
    return result

def do_stuff(flock, homedir, script):
  # wait 4 seconds for processes to finish
  time.sleep(4)

  # Retrieve data from MySQL database
  result = sqldata.fetch()
  mf.syslog_trace("...datafetch:  {0}".format(result), False, DEBUG)

  # Create the graphs based on the MySQL data
  result = trendgraph.make()
  mf.syslog_trace("...trendgrph:  {0}".format(result), False, DEBUG)
  if (result == 0):
    upload_page(script)

def upload_page(script):
  try:
    # Upload the webpage and graphs
    if os.path.isfile('/tmp/' + MYAPP + '/site/text.md'):
      write_lftp(script)
      cmnd = ['lftp', '-f', script]
      mf.syslog_trace("...:  {0}".format(cmnd), False, DEBUG)
      cmnd = subprocess.check_output(cmnd, timeout=20)
      mf.syslog_trace("...uploadpag:  {0}".format(cmnd), False, DEBUG)
  except subprocess.TimeoutExpired:
    mf.syslog_trace("***TIMEOUT***:  {0}".format(cmnd), syslog.LOG_ERR, DEBUG)
    time.sleep(17*60)             # wait 17 minutes for the router to restart.
    pass
  except subprocess.CalledProcessError:
    mf.syslog_trace("***ERROR***:    {0}".format(cmnd), syslog.LOG_ERR, DEBUG)
    time.sleep(17*60)             # wait 17 minutes for the router to restart.
    pass

def write_lftp(script):
  with open(script, 'w') as f:
    f.write('# DO NOT EDIT\n')
    f.write('# This file is created automatically by ' + MYAPP + '\n\n')
    f.write('# lftp script\n\n')
    f.write('set cmd:fail-exit yes;\n')
    f.write('open hendrixnet.nl;\n')
    f.write('cd 04.status/;\n')
    f.write('set cmd:fail-exit no;\n')
    f.write('mkdir -p -f _' + NODE + ' ;\n')
    f.write('set cmd:fail-exit yes;\n')
    f.write('cd _' + NODE + ' ;\n')
    f.write('mirror --reverse --delete --verbose=3 -c /tmp/' + MYAPP + '/site/ . ;\n')
    f.write('\n')

if __name__ == "__main__":
  daemon = MyDaemon('/tmp/' + MYAPP + '/' + MYID + '.pid')
  trendgraph = Graph(GRAPH_UPDATE)
  sqldata = SqlDataFetch(SQL_UPDATE_HOUR, SQL_UPDATE_DAY, SQL_UPDATE_WEEK, SQL_UPDATE_YEAR)
  if len(sys.argv) == 2:
    if 'start' == sys.argv[1]:
      daemon.start()
    elif 'stop' == sys.argv[1]:
      daemon.stop()
    elif 'restart' == sys.argv[1]:
      daemon.restart()
    elif 'foreground' == sys.argv[1]:
      # assist with debugging.
      print("Debug-mode started. Use <Ctrl>+C to stop.")
      DEBUG = True
      mf.syslog_trace("Daemon logging is ON", syslog.LOG_DEBUG, DEBUG)
      daemon.run()
    else:
      print("Unknown command")
      sys.exit(2)
    sys.exit(0)
  else:
    print("usage: {0!s} start|stop|restart|foreground".format(sys.argv[0]))
    sys.exit(2)
<|endoftext|>


<commit_before>import hf
from mako.template import Template
import logging, traceback, os

class ModuleBase:
    """
    Base class for HappyFace modules.
    A module provides two core functions:
    1) Acquisition of data through the methods
      1] prepareAcquisition: Specify the files to download
      2] extractData: Return a dictionary with data to fill into the database
      3] fillSubtables: to write the datasets for the modules subtables
    2) Rendering the module by returning a template data dictionary
     in method getTemplateData.

    Because thread-safety is required for concurrent rendering, the module itself
    MUST NOT save its state during rendering. The modules functions are internally
    accessed by the ModuleProxy class.
    """

    config_defaults = {
        'description': '',
        'instruction': '',
        'type': 'rated'
    }

    def __init__(self, instance_name, config, run, dataset, template):
        self.logger = logging.getLogger(self.__module__+'('+instance_name+')')
        self.module_name = self.__class__.module_name
        self.module_table = self.__class__.module_table
        self.instance_name = instance_name
        self.config = config
        self.run = run
        self.dataset = dataset
        self.template = template

    def prepareAcquisition(self):
        pass

    def fillSubtables(self, module_entry_id):
        pass

    def getTemplateData(self):
        """
        Override this method if your template requires special
        preprocessing of data or you have data in subtables.
        """
        return {"dataset": self.dataset, "run": self.run}

    def __unicode__(self):
        return self.instance_name

    def __str__(self):
        return self.instance_name

    def getStatusString(self):
        icon = 'unhappy'
        if self.dataset is None:
            icon = 'unhappy' if type == 'rated' else 'unavail_plot'
        else:
            if type == 'rated':
                if self.dataset['status'] > 0.66:
                    icon = 'happy'
                elif self.dataset['status'] > 0.33:
                    icon = 'neutral'
                else:
                    icon = 'unhappy'
            else:
                icon = 'avail_plot' if self.dataset['status'] > 0.9 else 'unavail_plot'
        return icon

    def url(self):
        # something along ?date=2012-03-24&time=17:20&t=batchsys&m=${module.instance_name}
        return "#%s" % self.instance_name

    def getStatusIcon(self):
        return os.path.join(hf.config.get('paths', 'template_icons_url'), 'mod_'+self.getStatusString()+'.png')

    def getNavStatusIcon(self):
        return os.path.join(hf.config.get('paths', 'template_icons_url'), 'nav_'+self.getStatusString()+'.png')

    def render(self):
        module_html = ''
        if self.template is None:
            return '
Rendering module %s failed because template was not loaded
' % self.instance_name
        try:
            template_data = { 'module': self, 'run': self.run }
            if self.dataset is None:
                template_data['no_data'] = True
                module_html = self.template.render(**template_data)
            else:
                template_data.update(self.getTemplateData())
                template_data['no_data'] = False
                module_html = self.template.render(**template_data)
        except Exception, e:
            module_html = "
Final rendering of '%s' failed completely!
" % self.instance_name
            self.logger.error("Rendering of module %s failed: %s" %(self.module_name, str(e)))
            self.logger.debug(traceback.format_exc())
        return module_html
        <commit_msg>Make HF namepsace available in module template<commit_after>import hf
from mako.template import Template
import logging, traceback, os

class ModuleBase:
    """
    Base class for HappyFace modules.
    A module provides two core functions:
    1) Acquisition of data through the methods
      1] prepareAcquisition: Specify the files to download
      2] extractData: Return a dictionary with data to fill into the database
      3] fillSubtables: to write the datasets for the modules subtables
    2) Rendering the module by returning a template data dictionary
     in method getTemplateData.

    Because thread-safety is required for concurrent rendering, the module itself
    MUST NOT save its state during rendering. The modules functions are internally
    accessed by the ModuleProxy class.
    """

    config_defaults = {
        'description': '',
        'instruction': '',
        'type': 'rated'
    }

    def __init__(self, instance_name, config, run, dataset, template):
        self.logger = logging.getLogger(self.__module__+'('+instance_name+')')
        self.module_name = self.__class__.module_name
        self.module_table = self.__class__.module_table
        self.instance_name = instance_name
        self.config = config
        self.run = run
        self.dataset = dataset
        self.template = template

    def prepareAcquisition(self):
        pass

    def fillSubtables(self, module_entry_id):
        pass

    def getTemplateData(self):
        """
        Override this method if your template requires special
        preprocessing of data or you have data in subtables.
        """
        return {"dataset": self.dataset, "run": self.run}

    def __unicode__(self):
        return self.instance_name

    def __str__(self):
        return self.instance_name

    def getStatusString(self):
        icon = 'unhappy'
        if self.dataset is None:
            icon = 'unhappy' if type == 'rated' else 'unavail_plot'
        else:
            if type == 'rated':
                if self.dataset['status'] > 0.66:
                    icon = 'happy'
                elif self.dataset['status'] > 0.33:
                    icon = 'neutral'
                else:
                    icon = 'unhappy'
            else:
                icon = 'avail_plot' if self.dataset['status'] > 0.9 else 'unavail_plot'
        return icon

    def url(self):
        # something along ?date=2012-03-24&time=17:20&t=batchsys&m=${module.instance_name}
        return "#%s" % self.instance_name

    def getStatusIcon(self):
        return os.path.join(hf.config.get('paths', 'template_icons_url'), 'mod_'+self.getStatusString()+'.png')

    def getNavStatusIcon(self):
        return os.path.join(hf.config.get('paths', 'template_icons_url'), 'nav_'+self.getStatusString()+'.png')

    def render(self):
        module_html = ''
        if self.template is None:
            return '
Rendering module %s failed because template was not loaded
' % self.instance_name
        try:
            template_data = { 'module': self, 'run': self.run, 'hf': hf }
            if self.dataset is None:
                template_data['no_data'] = True
                module_html = self.template.render(**template_data)
            else:
                template_data.update(self.getTemplateData())
                template_data['no_data'] = False
                module_html = self.template.render(**template_data)
        except Exception, e:
            module_html = "
Final rendering of '%s' failed completely!
" % self.instance_name
            self.logger.error("Rendering of module %s failed: %s" %(self.module_name, str(e)))
            self.logger.debug(traceback.format_exc())
        return module_html
        <|endoftext|>