hexsha
stringlengths
40
40
size
int64
2
1.02M
ext
stringclasses
10 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
245
max_stars_repo_name
stringlengths
6
130
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
10
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
245
max_issues_repo_name
stringlengths
6
130
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
10
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
245
max_forks_repo_name
stringlengths
6
130
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
10
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
2
1.02M
avg_line_length
float64
1
958k
max_line_length
int64
1
987k
alphanum_fraction
float64
0
1
content_no_comment
stringlengths
0
1.01M
is_comment_constant_removed
bool
2 classes
is_sharp_comment_removed
bool
1 class
f72c919a5fbacff307b79548546b94830a8d5ed5
26,995
py
Python
kivymd/uix/list.py
akaminetzkyp/KivyMD
940791ee1217e09184d8916c0eccc7534f097a48
[ "MIT" ]
1
2020-07-01T12:39:51.000Z
2020-07-01T12:39:51.000Z
kivymd/uix/list.py
ayo6706/KivyMD
c67850fd9f505d20a9e86ab89a39918daf34cd43
[ "MIT" ]
null
null
null
kivymd/uix/list.py
ayo6706/KivyMD
c67850fd9f505d20a9e86ab89a39918daf34cd43
[ "MIT" ]
null
null
null
""" Components/List =============== .. seealso:: `Material Design spec, Lists <https://material.io/components/lists>`_ .. rubric:: Lists are continuous, vertical indexes of text or images. .. image:: https://github.com/HeaTTheatR/KivyMD-data/raw/master/gallery/kivymddoc/lists.png :align: center The class :class:`~MDList` in combination with a :class:`~BaseListItem` like :class:`~OneLineListItem` will create a list that expands as items are added to it, working nicely with `Kivy's` :class:`~kivy.uix.scrollview.ScrollView`. Due to the variety in sizes and controls in the `Material Design spec`, this module suffers from a certain level of complexity to keep the widgets compliant, flexible and performant. For this `KivyMD` provides list items that try to cover the most common usecases, when those are insufficient, there's a base class called :class:`~BaseListItem` which you can use to create your own list items. This documentation will only cover the provided ones, for custom implementations please refer to this module's source code. `KivyMD` provides the following list items classes for use: Text only ListItems ------------------- - OneLineListItem_ - TwoLineListItem_ - ThreeLineListItem_ ListItems with widget containers -------------------------------- These widgets will take other widgets that inherit from :class:`~ILeftBody`, :class:`ILeftBodyTouch`, :class:`~IRightBody` or :class:`~IRightBodyTouch` and put them in their corresponding container. As the name implies, :class:`~ILeftBody` and :class:`~IRightBody` will signal that the widget goes into the left or right container, respectively. :class:`~ILeftBodyTouch` and :class:`~IRightBodyTouch` do the same thing, except these widgets will also receive touch events that occur within their surfaces. `KivyMD` provides base classes such as :class:`~ImageLeftWidget`, :class:`~ImageRightWidget`, :class:`~IconRightWidget`, :class:`~IconLeftWidget`, based on the above classes. .. rubric:: Allows the use of items with custom widgets on the left. - OneLineAvatarListItem_ - TwoLineAvatarListItem_ - ThreeLineAvatarListItem_ - OneLineIconListItem_ - TwoLineIconListItem_ - ThreeLineIconListItem_ .. rubric:: It allows the use of elements with custom widgets on the left and the right. - OneLineAvatarIconListItem_ - TwoLineAvatarIconListItem_ - ThreeLineAvatarIconListItem_ Usage ----- .. code-block:: python from kivy.lang import Builder from kivymd.app import MDApp from kivymd.uix.list import OneLineListItem KV = ''' ScrollView: MDList: id: container ''' class Test(MDApp): def build(self): return Builder.load_string(KV) def on_start(self): for i in range(20): self.root.ids.container.add_widget( OneLineListItem(text=f"Single-line item {i}") ) Test().run() .. image:: https://github.com/HeaTTheatR/KivyMD-data/raw/master/gallery/kivymddoc/lists.gif :align: center .. OneLineListItem: OneLineListItem --------------- .. code-block:: kv OneLineListItem: text: "Single-line item" .. image:: https://github.com/HeaTTheatR/KivyMD-data/raw/master/gallery/kivymddoc/OneLineListItem.png :align: center .. TwoLineListItem: TwoLineListItem --------------- .. code-block:: kv TwoLineListItem: text: "Two-line item" secondary_text: "Secondary text here" .. image:: https://github.com/HeaTTheatR/KivyMD-data/raw/master/gallery/kivymddoc/TwoLineListItem.png :align: center .. ThreeLineListItem: ThreeLineListItem ----------------- .. code-block:: kv ThreeLineListItem: text: "Three-line item" secondary_text: "This is a multi-line label where you can" tertiary_text: "fit more text than usual" .. image:: https://github.com/HeaTTheatR/KivyMD-data/raw/master/gallery/kivymddoc/ThreeLineListItem.png :align: center .. OneLineAvatarListItem: OneLineAvatarListItem --------------------- .. code-block:: kv OneLineAvatarListItem: text: "Single-line item with avatar" ImageLeftWidget: source: "data/logo/kivy-icon-256.png" .. image:: https://github.com/HeaTTheatR/KivyMD-data/raw/master/gallery/kivymddoc/lists-map.png :align: center .. TwoLineAvatarListItem: TwoLineAvatarListItem --------------------- .. code-block:: kv TwoLineAvatarListItem: text: "Two-line item with avatar" secondary_text: "Secondary text here" ImageLeftWidget: source: "data/logo/kivy-icon-256.png" .. image:: https://github.com/HeaTTheatR/KivyMD-data/raw/master/gallery/kivymddoc/TwoLineAvatarListItem.png :align: center .. ThreeLineAvatarListItem: ThreeLineAvatarListItem ----------------------- .. code-block:: kv ThreeLineAvatarListItem: text: "Three-line item with avatar" secondary_text: "Secondary text here" tertiary_text: "fit more text than usual" ImageLeftWidget: source: "data/logo/kivy-icon-256.png" .. image:: https://github.com/HeaTTheatR/KivyMD-data/raw/master/gallery/kivymddoc/ThreeLineAvatarListItem.png :align: center .. OneLineIconListItem: OneLineIconListItem ------------------- .. code-block:: kv OneLineAvatarListItem: text: "Single-line item with avatar" IconLeftWidget: icon: "language-python" .. image:: https://github.com/HeaTTheatR/KivyMD-data/raw/master/gallery/kivymddoc/OneLineIconListItem.png :align: center .. TwoLineIconListItem: TwoLineIconListItem ------------------- .. code-block:: kv TwoLineIconListItem: text: "Two-line item with avatar" secondary_text: "Secondary text here" IconLeftWidget: icon: "language-python" .. image:: https://github.com/HeaTTheatR/KivyMD-data/raw/master/gallery/kivymddoc/TwoLineIconListItem.png :align: center .. ThreeLineIconListItem: ThreeLineIconListItem --------------------- .. code-block:: kv ThreeLineIconListItem: text: "Three-line item with avatar" secondary_text: "Secondary text here" tertiary_text: "fit more text than usual" IconLeftWidget: icon: "language-python" .. image:: https://github.com/HeaTTheatR/KivyMD-data/raw/master/gallery/kivymddoc/ThreeLineIconListItem.png :align: center .. OneLineAvatarIconListItem: OneLineAvatarIconListItem ------------------------- .. code-block:: kv OneLineAvatarIconListItem: text: "One-line item with avatar" IconLeftWidget: icon: "plus" IconRightWidget: icon: "minus" .. image:: https://github.com/HeaTTheatR/KivyMD-data/raw/master/gallery/kivymddoc/OneLineAvatarIconListItem.png :align: center .. TwoLineAvatarIconListItem: TwoLineAvatarIconListItem ------------------------- .. code-block:: kv TwoLineAvatarIconListItem: text: "Two-line item with avatar" secondary_text: "Secondary text here" IconLeftWidget: icon: "plus" IconRightWidget: icon: "minus" .. image:: https://github.com/HeaTTheatR/KivyMD-data/raw/master/gallery/kivymddoc/TwoLineAvatarIconListItem.png :align: center .. ThreeLineAvatarIconListItem: ThreeLineAvatarIconListItem --------------------------- .. code-block:: kv ThreeLineAvatarIconListItem: text: "Three-line item with avatar" secondary_text: "Secondary text here" tertiary_text: "fit more text than usual" IconLeftWidget: icon: "plus" IconRightWidget: icon: "minus" .. image:: https://github.com/HeaTTheatR/KivyMD-data/raw/master/gallery/kivymddoc/ThreeLineAvatarIconListItem.png :align: center Custom list item ---------------- .. code-block:: python from kivy.lang import Builder from kivy.properties import StringProperty from kivymd.app import MDApp from kivymd.uix.list import IRightBodyTouch, OneLineAvatarIconListItem from kivymd.uix.selectioncontrol import MDCheckbox from kivymd.icon_definitions import md_icons KV = ''' <ListItemWithCheckbox>: IconLeftWidget: icon: root.icon RightCheckbox: BoxLayout: ScrollView: MDList: id: scroll ''' class ListItemWithCheckbox(OneLineAvatarIconListItem): '''Custom list item.''' icon = StringProperty("android") class RightCheckbox(IRightBodyTouch, MDCheckbox): '''Custom right container.''' class MainApp(MDApp): def build(self): return Builder.load_string(KV) def on_start(self): icons = list(md_icons.keys()) for i in range(30): self.root.ids.scroll.add_widget( ListItemWithCheckbox(text=f"Item {i}", icon=icons[i]) ) MainApp().run() .. image:: https://github.com/HeaTTheatR/KivyMD-data/raw/master/gallery/kivymddoc/custom-list-item.png :align: center .. code-block:: python from kivy.lang import Builder from kivymd.app import MDApp from kivymd.uix.boxlayout import MDBoxLayout from kivymd.uix.list import IRightBodyTouch KV = ''' OneLineAvatarIconListItem: text: "One-line item with avatar" on_size: self.ids._right_container.width = container.width self.ids._right_container.x = container.width IconLeftWidget: icon: "settings" Container: id: container MDIconButton: icon: "minus" MDIconButton: icon: "plus" ''' class Container(IRightBodyTouch, MDBoxLayout): adaptive_width = True class MainApp(MDApp): def build(self): return Builder.load_string(KV) MainApp().run() .. image:: https://github.com/HeaTTheatR/KivyMD-data/raw/master/gallery/kivymddoc/custom-list-right-container.png :align: center """ from kivy.lang import Builder from kivy.metrics import dp from kivy.properties import ( StringProperty, NumericProperty, ListProperty, OptionProperty, BooleanProperty, ) from kivy.uix.behaviors import ButtonBehavior from kivy.uix.floatlayout import FloatLayout from kivy.uix.image import Image import kivymd.material_resources as m_res from kivymd.uix.behaviors import RectangularRippleBehavior from kivymd.uix.button import MDIconButton from kivymd.theming import ThemableBehavior from kivymd.font_definitions import theme_font_styles from kivymd.uix.gridlayout import MDGridLayout from kivymd.uix.selectioncontrol import MDCheckbox Builder.load_string( """ #:import m_res kivymd.material_resources <MDList> cols: 1 adaptive_height: True padding: 0, self._list_vertical_padding <BaseListItem> size_hint_y: None canvas: Color: rgba: self.theme_cls.divider_color if root.divider is not None\ else (0, 0, 0, 0) Line: points: (root.x ,root.y, root.x+self.width, root.y)\ if root.divider == 'Full' else\ (root.x+root._txt_left_pad, root.y,\ root.x+self.width-root._txt_left_pad-root._txt_right_pad,\ root.y) Color: rgba: root.bg_color if root.bg_color else (0, 0, 0, 0) Rectangle: pos: self.pos size: self.size BoxLayout: id: _text_container orientation: 'vertical' pos: root.pos padding: root._txt_left_pad, root._txt_top_pad,\ root._txt_right_pad, root._txt_bot_pad MDLabel: id: _lbl_primary text: root.text font_style: root.font_style theme_text_color: root.theme_text_color text_color: root.text_color size_hint_y: None height: self.texture_size[1] markup: True shorten_from: 'right' shorten: True MDLabel: id: _lbl_secondary text: '' if root._num_lines == 1 else root.secondary_text font_style: root.secondary_font_style theme_text_color: root.secondary_theme_text_color text_color: root.secondary_text_color size_hint_y: None height: 0 if root._num_lines == 1 else self.texture_size[1] shorten: True shorten_from: 'right' markup: True MDLabel: id: _lbl_tertiary text: '' if root._num_lines == 1 else root.tertiary_text font_style: root.tertiary_font_style theme_text_color: root.tertiary_theme_text_color text_color: root.tertiary_text_color size_hint_y: None height: 0 if root._num_lines == 1 else self.texture_size[1] shorten: True shorten_from: 'right' markup: True <OneLineAvatarListItem> BoxLayout: id: _left_container size_hint: None, None x: root.x + dp(16) y: root.y + root.height/2 - self.height/2 size: dp(40), dp(40) <ThreeLineAvatarListItem> BoxLayout: id: _left_container size_hint: None, None x: root.x + dp(16) y: root.y + root.height - root._txt_top_pad - self.height - dp(5) size: dp(40), dp(40) <OneLineIconListItem> BoxLayout: id: _left_container size_hint: None, None x: root.x + dp(16) y: root.y + root.height/2 - self.height/2 size: dp(48), dp(48) <ThreeLineIconListItem> BoxLayout: id: _left_container size_hint: None, None x: root.x + dp(16) y: root.y + root.height - root._txt_top_pad - self.height - dp(5) size: dp(48), dp(48) <OneLineRightIconListItem> BoxLayout: id: _right_container size_hint: None, None x: root.x + root.width - m_res.HORIZ_MARGINS - self.width y: root.y + root.height/2 - self.height/2 size: dp(48), dp(48) <ThreeLineRightIconListItem> BoxLayout: id: _right_container size_hint: None, None x: root.x + root.width - m_res.HORIZ_MARGINS - self.width y: root.y + root.height/2 - self.height/2 size: dp(48), dp(48) <OneLineAvatarIconListItem> BoxLayout: id: _right_container size_hint: None, None x: root.x + root.width - m_res.HORIZ_MARGINS - self.width y: root.y + root.height/2 - self.height/2 size: dp(48), dp(48) <TwoLineAvatarIconListItem> BoxLayout: id: _right_container size_hint: None, None x: root.x + root.width - m_res.HORIZ_MARGINS - self.width y: root.y + root.height/2 - self.height/2 size: dp(48), dp(48) <ThreeLineAvatarIconListItem> BoxLayout: id: _right_container size_hint: None, None x: root.x + root.width - m_res.HORIZ_MARGINS - self.width y: root.y + root.height - root._txt_top_pad - self.height - dp(5) size: dp(48), dp(48) """ ) class MDList(MDGridLayout): """ListItem container. Best used in conjunction with a :class:`kivy.uix.ScrollView`. When adding (or removing) a widget, it will resize itself to fit its children, plus top and bottom paddings as described by the `MD` spec. """ _list_vertical_padding = NumericProperty("8dp") def add_widget(self, widget, index=0, canvas=None): super().add_widget(widget, index, canvas) self.height += widget.height def remove_widget(self, widget): super().remove_widget(widget) self.height -= widget.height class BaseListItem( ThemableBehavior, RectangularRippleBehavior, ButtonBehavior, FloatLayout ): """ Base class to all ListItems. Not supposed to be instantiated on its own. """ text = StringProperty() """ Text shown in the first line. :attr:`text` is a :class:`~kivy.properties.StringProperty` and defaults to `''`. """ text_color = ListProperty(None) """ Text color in ``rgba`` format used if :attr:`~theme_text_color` is set to `'Custom'`. :attr:`text_color` is a :class:`~kivy.properties.ListProperty` and defaults to `None`. """ font_style = OptionProperty("Subtitle1", options=theme_font_styles) """ Text font style. See ``kivymd.font_definitions.py``. :attr:`font_style` is a :class:`~kivy.properties.OptionProperty` and defaults to `'Subtitle1'`. """ theme_text_color = StringProperty("Primary", allownone=True) """ Theme text color in ``rgba`` format for primary text. :attr:`theme_text_color` is a :class:`~kivy.properties.StringProperty` and defaults to `'Primary'`. """ secondary_text = StringProperty() """ Text shown in the second line. :attr:`secondary_text` is a :class:`~kivy.properties.StringProperty` and defaults to `''`. """ tertiary_text = StringProperty() """ The text is displayed on the third line. :attr:`tertiary_text` is a :class:`~kivy.properties.StringProperty` and defaults to `''`. """ secondary_text_color = ListProperty(None) """ Text color in ``rgba`` format used for secondary text if :attr:`~secondary_theme_text_color` is set to `'Custom'`. :attr:`secondary_text_color` is a :class:`~kivy.properties.ListProperty` and defaults to `None`. """ tertiary_text_color = ListProperty(None) """ Text color in ``rgba`` format used for tertiary text if :attr:`~secondary_theme_text_color` is set to 'Custom'. :attr:`tertiary_text_color` is a :class:`~kivy.properties.ListProperty` and defaults to `None`. """ secondary_theme_text_color = StringProperty("Secondary", allownone=True) """ Theme text color for secondary text. :attr:`secondary_theme_text_color` is a :class:`~kivy.properties.StringProperty` and defaults to `'Secondary'`. """ tertiary_theme_text_color = StringProperty("Secondary", allownone=True) """ Theme text color for tertiary text. :attr:`tertiary_theme_text_color` is a :class:`~kivy.properties.StringProperty` and defaults to `'Secondary'`. """ secondary_font_style = OptionProperty("Body1", options=theme_font_styles) """ Font style for secondary line. See ``kivymd.font_definitions.py``. :attr:`secondary_font_style` is a :class:`~kivy.properties.OptionProperty` and defaults to `'Body1'`. """ tertiary_font_style = OptionProperty("Body1", options=theme_font_styles) """ Font style for tertiary line. See ``kivymd.font_definitions.py``. :attr:`tertiary_font_style` is a :class:`~kivy.properties.OptionProperty` and defaults to `'Body1'`. """ divider = OptionProperty( "Full", options=["Full", "Inset", None], allownone=True ) """ Divider mode. Available options are: `'Full'`, `'Inset'` and default to `'Full'`. :attr:`tertiary_font_style` is a :class:`~kivy.properties.OptionProperty` and defaults to `'Body1'`. """ bg_color = ListProperty() """ Background color for menu item. :attr:`bg_color` is a :class:`~kivy.properties.ListProperty` and defaults to `[]`. """ _txt_left_pad = NumericProperty("16dp") _txt_top_pad = NumericProperty() _txt_bot_pad = NumericProperty() _txt_right_pad = NumericProperty(m_res.HORIZ_MARGINS) _num_lines = 3 _no_ripple_effect = BooleanProperty(False) class ILeftBody: """ Pseudo-interface for widgets that go in the left container for ListItems that support it. Implements nothing and requires no implementation, for annotation only. """ pass class ILeftBodyTouch: """ Same as :class:`~ILeftBody`, but allows the widget to receive touch events instead of triggering the ListItem's ripple effect. """ pass class IRightBody: """ Pseudo-interface for widgets that go in the right container for ListItems that support it. Implements nothing and requires no implementation, for annotation only. """ pass class IRightBodyTouch: """ Same as :class:`~IRightBody`, but allows the widget to receive touch events instead of triggering the ``ListItem``'s ripple effect """ pass class ContainerSupport: """ Overrides ``add_widget`` in a ``ListItem`` to include support for ``I*Body`` widgets when the appropiate containers are present. """ _touchable_widgets = ListProperty() def add_widget(self, widget, index=0): if issubclass(widget.__class__, ILeftBody): self.ids._left_container.add_widget(widget) elif issubclass(widget.__class__, ILeftBodyTouch): self.ids._left_container.add_widget(widget) self._touchable_widgets.append(widget) elif issubclass(widget.__class__, IRightBody): self.ids._right_container.add_widget(widget) elif issubclass(widget.__class__, IRightBodyTouch): self.ids._right_container.add_widget(widget) self._touchable_widgets.append(widget) else: return super().add_widget(widget) def remove_widget(self, widget): super().remove_widget(widget) if widget in self._touchable_widgets: self._touchable_widgets.remove(widget) def on_touch_down(self, touch): if self.propagate_touch_to_touchable_widgets(touch, "down"): return super().on_touch_down(touch) def on_touch_move(self, touch, *args): if self.propagate_touch_to_touchable_widgets(touch, "move", *args): return super().on_touch_move(touch, *args) def on_touch_up(self, touch): if self.propagate_touch_to_touchable_widgets(touch, "up"): return super().on_touch_up(touch) def propagate_touch_to_touchable_widgets(self, touch, touch_event, *args): triggered = False for i in self._touchable_widgets: if i.collide_point(touch.x, touch.y): triggered = True if touch_event == "down": i.on_touch_down(touch) elif touch_event == "move": i.on_touch_move(touch, *args) elif touch_event == "up": i.on_touch_up(touch) return triggered class OneLineListItem(BaseListItem): """A one line list item.""" _txt_top_pad = NumericProperty("16dp") _txt_bot_pad = NumericProperty("15dp") # dp(20) - dp(5) _height = NumericProperty() _num_lines = 1 def __init__(self, **kwargs): super().__init__(**kwargs) self.height = dp(48) if not self._height else self._height class TwoLineListItem(BaseListItem): """A two line list item.""" _txt_top_pad = NumericProperty("20dp") _txt_bot_pad = NumericProperty("15dp") # dp(20) - dp(5) _height = NumericProperty() def __init__(self, **kwargs): super().__init__(**kwargs) self.height = dp(72) if not self._height else self._height class ThreeLineListItem(BaseListItem): """A three line list item.""" _txt_top_pad = NumericProperty("16dp") _txt_bot_pad = NumericProperty("15dp") # dp(20) - dp(5) _height = NumericProperty() _num_lines = 3 def __init__(self, **kwargs): super().__init__(**kwargs) self.height = dp(88) if not self._height else self._height class OneLineAvatarListItem(ContainerSupport, BaseListItem): _txt_left_pad = NumericProperty("72dp") _txt_top_pad = NumericProperty("20dp") _txt_bot_pad = NumericProperty("19dp") # dp(24) - dp(5) _height = NumericProperty() _num_lines = 1 def __init__(self, **kwargs): super().__init__(**kwargs) self.height = dp(56) if not self._height else self._height class TwoLineAvatarListItem(OneLineAvatarListItem): _txt_top_pad = NumericProperty("20dp") _txt_bot_pad = NumericProperty("15dp") # dp(20) - dp(5) _height = NumericProperty() _num_lines = 2 def __init__(self, **kwargs): super().__init__(**kwargs) self.height = dp(72) if not self._height else self._height class ThreeLineAvatarListItem(ContainerSupport, ThreeLineListItem): _txt_left_pad = NumericProperty("72dp") class OneLineIconListItem(ContainerSupport, OneLineListItem): _txt_left_pad = NumericProperty("72dp") class TwoLineIconListItem(OneLineIconListItem): _txt_top_pad = NumericProperty("20dp") _txt_bot_pad = NumericProperty("15dp") # dp(20) - dp(5) _height = NumericProperty() _num_lines = 2 def __init__(self, **kwargs): super().__init__(**kwargs) self.height = dp(72) if not self._height else self._height class ThreeLineIconListItem(ContainerSupport, ThreeLineListItem): _txt_left_pad = NumericProperty("72dp") class OneLineRightIconListItem(ContainerSupport, OneLineListItem): # dp(40) = dp(16) + dp(24): _txt_right_pad = NumericProperty("40dp") def __init__(self, **kwargs): super().__init__(**kwargs) self._txt_right_pad = dp(40) + m_res.HORIZ_MARGINS class TwoLineRightIconListItem(OneLineRightIconListItem): _txt_top_pad = NumericProperty("20dp") _txt_bot_pad = NumericProperty("15dp") # dp(20) - dp(5) _height = NumericProperty() _num_lines = 2 def __init__(self, **kwargs): super().__init__(**kwargs) self.height = dp(72) if not self._height else self._height class ThreeLineRightIconListItem(ContainerSupport, ThreeLineListItem): # dp(40) = dp(16) + dp(24): _txt_right_pad = NumericProperty("40dp") def __init__(self, **kwargs): super().__init__(**kwargs) self._txt_right_pad = dp(40) + m_res.HORIZ_MARGINS class OneLineAvatarIconListItem(OneLineAvatarListItem): # dp(40) = dp(16) + dp(24): _txt_right_pad = NumericProperty("40dp") def __init__(self, **kwargs): super().__init__(**kwargs) self._txt_right_pad = dp(40) + m_res.HORIZ_MARGINS class TwoLineAvatarIconListItem(TwoLineAvatarListItem): # dp(40) = dp(16) + dp(24): _txt_right_pad = NumericProperty("40dp") def __init__(self, **kwargs): super().__init__(**kwargs) self._txt_right_pad = dp(40) + m_res.HORIZ_MARGINS class ThreeLineAvatarIconListItem(ThreeLineAvatarListItem): # dp(40) = dp(16) + dp(24): _txt_right_pad = NumericProperty("40dp") def __init__(self, **kwargs): super().__init__(**kwargs) self._txt_right_pad = dp(40) + m_res.HORIZ_MARGINS class ImageLeftWidget(ILeftBody, Image): pass class ImageRightWidget(IRightBodyTouch, Image): pass class IconRightWidget(IRightBodyTouch, MDIconButton): pass class IconLeftWidget(ILeftBodyTouch, MDIconButton): pass class CheckboxLeftWidget(ILeftBodyTouch, MDCheckbox): pass
27.185297
113
0.655195
from kivy.lang import Builder from kivy.metrics import dp from kivy.properties import ( StringProperty, NumericProperty, ListProperty, OptionProperty, BooleanProperty, ) from kivy.uix.behaviors import ButtonBehavior from kivy.uix.floatlayout import FloatLayout from kivy.uix.image import Image import kivymd.material_resources as m_res from kivymd.uix.behaviors import RectangularRippleBehavior from kivymd.uix.button import MDIconButton from kivymd.theming import ThemableBehavior from kivymd.font_definitions import theme_font_styles from kivymd.uix.gridlayout import MDGridLayout from kivymd.uix.selectioncontrol import MDCheckbox Builder.load_string( """ #:import m_res kivymd.material_resources <MDList> cols: 1 adaptive_height: True padding: 0, self._list_vertical_padding <BaseListItem> size_hint_y: None canvas: Color: rgba: self.theme_cls.divider_color if root.divider is not None\ else (0, 0, 0, 0) Line: points: (root.x ,root.y, root.x+self.width, root.y)\ if root.divider == 'Full' else\ (root.x+root._txt_left_pad, root.y,\ root.x+self.width-root._txt_left_pad-root._txt_right_pad,\ root.y) Color: rgba: root.bg_color if root.bg_color else (0, 0, 0, 0) Rectangle: pos: self.pos size: self.size BoxLayout: id: _text_container orientation: 'vertical' pos: root.pos padding: root._txt_left_pad, root._txt_top_pad,\ root._txt_right_pad, root._txt_bot_pad MDLabel: id: _lbl_primary text: root.text font_style: root.font_style theme_text_color: root.theme_text_color text_color: root.text_color size_hint_y: None height: self.texture_size[1] markup: True shorten_from: 'right' shorten: True MDLabel: id: _lbl_secondary text: '' if root._num_lines == 1 else root.secondary_text font_style: root.secondary_font_style theme_text_color: root.secondary_theme_text_color text_color: root.secondary_text_color size_hint_y: None height: 0 if root._num_lines == 1 else self.texture_size[1] shorten: True shorten_from: 'right' markup: True MDLabel: id: _lbl_tertiary text: '' if root._num_lines == 1 else root.tertiary_text font_style: root.tertiary_font_style theme_text_color: root.tertiary_theme_text_color text_color: root.tertiary_text_color size_hint_y: None height: 0 if root._num_lines == 1 else self.texture_size[1] shorten: True shorten_from: 'right' markup: True <OneLineAvatarListItem> BoxLayout: id: _left_container size_hint: None, None x: root.x + dp(16) y: root.y + root.height/2 - self.height/2 size: dp(40), dp(40) <ThreeLineAvatarListItem> BoxLayout: id: _left_container size_hint: None, None x: root.x + dp(16) y: root.y + root.height - root._txt_top_pad - self.height - dp(5) size: dp(40), dp(40) <OneLineIconListItem> BoxLayout: id: _left_container size_hint: None, None x: root.x + dp(16) y: root.y + root.height/2 - self.height/2 size: dp(48), dp(48) <ThreeLineIconListItem> BoxLayout: id: _left_container size_hint: None, None x: root.x + dp(16) y: root.y + root.height - root._txt_top_pad - self.height - dp(5) size: dp(48), dp(48) <OneLineRightIconListItem> BoxLayout: id: _right_container size_hint: None, None x: root.x + root.width - m_res.HORIZ_MARGINS - self.width y: root.y + root.height/2 - self.height/2 size: dp(48), dp(48) <ThreeLineRightIconListItem> BoxLayout: id: _right_container size_hint: None, None x: root.x + root.width - m_res.HORIZ_MARGINS - self.width y: root.y + root.height/2 - self.height/2 size: dp(48), dp(48) <OneLineAvatarIconListItem> BoxLayout: id: _right_container size_hint: None, None x: root.x + root.width - m_res.HORIZ_MARGINS - self.width y: root.y + root.height/2 - self.height/2 size: dp(48), dp(48) <TwoLineAvatarIconListItem> BoxLayout: id: _right_container size_hint: None, None x: root.x + root.width - m_res.HORIZ_MARGINS - self.width y: root.y + root.height/2 - self.height/2 size: dp(48), dp(48) <ThreeLineAvatarIconListItem> BoxLayout: id: _right_container size_hint: None, None x: root.x + root.width - m_res.HORIZ_MARGINS - self.width y: root.y + root.height - root._txt_top_pad - self.height - dp(5) size: dp(48), dp(48) """ ) class MDList(MDGridLayout): _list_vertical_padding = NumericProperty("8dp") def add_widget(self, widget, index=0, canvas=None): super().add_widget(widget, index, canvas) self.height += widget.height def remove_widget(self, widget): super().remove_widget(widget) self.height -= widget.height class BaseListItem( ThemableBehavior, RectangularRippleBehavior, ButtonBehavior, FloatLayout ): text = StringProperty() text_color = ListProperty(None) font_style = OptionProperty("Subtitle1", options=theme_font_styles) theme_text_color = StringProperty("Primary", allownone=True) secondary_text = StringProperty() tertiary_text = StringProperty() secondary_text_color = ListProperty(None) tertiary_text_color = ListProperty(None) secondary_theme_text_color = StringProperty("Secondary", allownone=True) tertiary_theme_text_color = StringProperty("Secondary", allownone=True) secondary_font_style = OptionProperty("Body1", options=theme_font_styles) tertiary_font_style = OptionProperty("Body1", options=theme_font_styles) divider = OptionProperty( "Full", options=["Full", "Inset", None], allownone=True ) bg_color = ListProperty() _txt_left_pad = NumericProperty("16dp") _txt_top_pad = NumericProperty() _txt_bot_pad = NumericProperty() _txt_right_pad = NumericProperty(m_res.HORIZ_MARGINS) _num_lines = 3 _no_ripple_effect = BooleanProperty(False) class ILeftBody: pass class ILeftBodyTouch: pass class IRightBody: pass class IRightBodyTouch: pass class ContainerSupport: _touchable_widgets = ListProperty() def add_widget(self, widget, index=0): if issubclass(widget.__class__, ILeftBody): self.ids._left_container.add_widget(widget) elif issubclass(widget.__class__, ILeftBodyTouch): self.ids._left_container.add_widget(widget) self._touchable_widgets.append(widget) elif issubclass(widget.__class__, IRightBody): self.ids._right_container.add_widget(widget) elif issubclass(widget.__class__, IRightBodyTouch): self.ids._right_container.add_widget(widget) self._touchable_widgets.append(widget) else: return super().add_widget(widget) def remove_widget(self, widget): super().remove_widget(widget) if widget in self._touchable_widgets: self._touchable_widgets.remove(widget) def on_touch_down(self, touch): if self.propagate_touch_to_touchable_widgets(touch, "down"): return super().on_touch_down(touch) def on_touch_move(self, touch, *args): if self.propagate_touch_to_touchable_widgets(touch, "move", *args): return super().on_touch_move(touch, *args) def on_touch_up(self, touch): if self.propagate_touch_to_touchable_widgets(touch, "up"): return super().on_touch_up(touch) def propagate_touch_to_touchable_widgets(self, touch, touch_event, *args): triggered = False for i in self._touchable_widgets: if i.collide_point(touch.x, touch.y): triggered = True if touch_event == "down": i.on_touch_down(touch) elif touch_event == "move": i.on_touch_move(touch, *args) elif touch_event == "up": i.on_touch_up(touch) return triggered class OneLineListItem(BaseListItem): _txt_top_pad = NumericProperty("16dp") _txt_bot_pad = NumericProperty("15dp") _height = NumericProperty() _num_lines = 1 def __init__(self, **kwargs): super().__init__(**kwargs) self.height = dp(48) if not self._height else self._height class TwoLineListItem(BaseListItem): _txt_top_pad = NumericProperty("20dp") _txt_bot_pad = NumericProperty("15dp") _height = NumericProperty() def __init__(self, **kwargs): super().__init__(**kwargs) self.height = dp(72) if not self._height else self._height class ThreeLineListItem(BaseListItem): _txt_top_pad = NumericProperty("16dp") _txt_bot_pad = NumericProperty("15dp") _height = NumericProperty() _num_lines = 3 def __init__(self, **kwargs): super().__init__(**kwargs) self.height = dp(88) if not self._height else self._height class OneLineAvatarListItem(ContainerSupport, BaseListItem): _txt_left_pad = NumericProperty("72dp") _txt_top_pad = NumericProperty("20dp") _txt_bot_pad = NumericProperty("19dp") _height = NumericProperty() _num_lines = 1 def __init__(self, **kwargs): super().__init__(**kwargs) self.height = dp(56) if not self._height else self._height class TwoLineAvatarListItem(OneLineAvatarListItem): _txt_top_pad = NumericProperty("20dp") _txt_bot_pad = NumericProperty("15dp") _height = NumericProperty() _num_lines = 2 def __init__(self, **kwargs): super().__init__(**kwargs) self.height = dp(72) if not self._height else self._height class ThreeLineAvatarListItem(ContainerSupport, ThreeLineListItem): _txt_left_pad = NumericProperty("72dp") class OneLineIconListItem(ContainerSupport, OneLineListItem): _txt_left_pad = NumericProperty("72dp") class TwoLineIconListItem(OneLineIconListItem): _txt_top_pad = NumericProperty("20dp") _txt_bot_pad = NumericProperty("15dp") _height = NumericProperty() _num_lines = 2 def __init__(self, **kwargs): super().__init__(**kwargs) self.height = dp(72) if not self._height else self._height class ThreeLineIconListItem(ContainerSupport, ThreeLineListItem): _txt_left_pad = NumericProperty("72dp") class OneLineRightIconListItem(ContainerSupport, OneLineListItem): _txt_right_pad = NumericProperty("40dp") def __init__(self, **kwargs): super().__init__(**kwargs) self._txt_right_pad = dp(40) + m_res.HORIZ_MARGINS class TwoLineRightIconListItem(OneLineRightIconListItem): _txt_top_pad = NumericProperty("20dp") _txt_bot_pad = NumericProperty("15dp") _height = NumericProperty() _num_lines = 2 def __init__(self, **kwargs): super().__init__(**kwargs) self.height = dp(72) if not self._height else self._height class ThreeLineRightIconListItem(ContainerSupport, ThreeLineListItem): _txt_right_pad = NumericProperty("40dp") def __init__(self, **kwargs): super().__init__(**kwargs) self._txt_right_pad = dp(40) + m_res.HORIZ_MARGINS class OneLineAvatarIconListItem(OneLineAvatarListItem): _txt_right_pad = NumericProperty("40dp") def __init__(self, **kwargs): super().__init__(**kwargs) self._txt_right_pad = dp(40) + m_res.HORIZ_MARGINS class TwoLineAvatarIconListItem(TwoLineAvatarListItem): _txt_right_pad = NumericProperty("40dp") def __init__(self, **kwargs): super().__init__(**kwargs) self._txt_right_pad = dp(40) + m_res.HORIZ_MARGINS class ThreeLineAvatarIconListItem(ThreeLineAvatarListItem): _txt_right_pad = NumericProperty("40dp") def __init__(self, **kwargs): super().__init__(**kwargs) self._txt_right_pad = dp(40) + m_res.HORIZ_MARGINS class ImageLeftWidget(ILeftBody, Image): pass class ImageRightWidget(IRightBodyTouch, Image): pass class IconRightWidget(IRightBodyTouch, MDIconButton): pass class IconLeftWidget(ILeftBodyTouch, MDIconButton): pass class CheckboxLeftWidget(ILeftBodyTouch, MDCheckbox): pass
true
true
f72c928677b51e691762e5e54a0552edfcb7fb7d
4,361
py
Python
lab4/predict_income_romain_claret_and_sylvain_robert-nicoud_lab4.py
RomainClaret/msc.ml.labs
4e6b8e1c1ab841ab8ebbaee13f6ae43e9a1c44a5
[ "MIT" ]
null
null
null
lab4/predict_income_romain_claret_and_sylvain_robert-nicoud_lab4.py
RomainClaret/msc.ml.labs
4e6b8e1c1ab841ab8ebbaee13f6ae43e9a1c44a5
[ "MIT" ]
null
null
null
lab4/predict_income_romain_claret_and_sylvain_robert-nicoud_lab4.py
RomainClaret/msc.ml.labs
4e6b8e1c1ab841ab8ebbaee13f6ae43e9a1c44a5
[ "MIT" ]
null
null
null
#!/usr/bin/env python3 # 12.04.21 # Assignment lab 04 # Master Class: Machine Learning (5MI2018) # Faculty of Economic Science # University of Neuchatel (Switzerland) # Lab 4, see ML21_Exercise_4.pdf for more information # https://github.com/RomainClaret/msc.ml.labs # Authors: # - Romain Claret @RomainClaret # - Sylvain Robert-Nicoud @Nic0uds import warnings import pickle import pandas as pd from sklearn.preprocessing import LabelEncoder from sklearn.metrics import accuracy_score warnings.filterwarnings("ignore") # SPLITING ADULT.TEST FILE IN SUBFILES #spliting the adult.test file into several files to simulate weeks filename = 'adult.test' file_handler = open(filename, 'r').readlines()[1:] prefix_file = "adult_2021_cw_" week_number = 1 split_into = 10 line_count = 0 file_length = len(file_handler) for i in range(0,file_length): if i % ((file_length)//split_into) == 0 and i+((file_length//split_into)//2) < file_length: open(str(prefix_file)+str(week_number) + ".csv", "w+").writelines(file_handler[i:i+(file_length//split_into)]) week_number += 1 # RUN PIPELINE MODEL FROM OTHER FILE #input file, and save the predictions into a different file. #Example: #Let's say you have the input data weekly in the file adult_2021_cw_12.csv. #This second script should read the input from this file and use the classifier to make predictions and write those predictions in the file adult_2021_cw_12_pred.csv . # load pipeline model pipeline_model = pickle.load( open("grid_search_model.pickle", "rb" )) weeks_count = 10 filename = 'adult.test' prefix_file = "adult_2021_cw_" # get the features names and the values of the categories from adult.names (build a dictionary) data_dict = {} with open('adult.names') as f: for l in f: if l[0] == '|' or ':' not in l: continue c = l.split(':') if c[1].startswith(' continuous'): data_dict[c[0]] = "" else: data_dict[c[0]] = c[1].replace("\n","").replace(".","").replace(" ","").split(",") header = list(data_dict.keys())+['income'] # for each week based on a count and a naming convention for i in range (weeks_count): filename = str(prefix_file)+str(i+1)+".csv" df_weekly = pd.read_table(filename, sep=r',\s', na_values='?', skiprows=[0], header=None, names=header).dropna() drop_list = ["education", "occupation", "relationship"] df_weekly = df_weekly.drop(columns=drop_list) dict_replace = { 'marital-status' : { 'Never-married': 'Not-Married', 'Married-civ-spouse': 'Married', 'Divorced': 'Not-Married', 'Married-spouse-absent': 'Married', 'Separated': 'Married', 'Married-AF-spouse': 'Married', 'Widowed': 'Not-Married' }, 'workclass': { 'State-gov': 'Government', 'Self-emp-not-inc': 'Self-Employment', 'Federal-gov': 'Government', 'Local-gov': 'Government', 'Self-emp-inc': 'Self-Employment' } } df_weekly.replace(dict_replace, inplace=True) df_weekly["income"].replace({"<=50K.": "<=50K", ">50K.": ">50K"}, inplace=True) for l in ["marital-status", "sex", "income"]: l_enc = LabelEncoder() encoder_weekly = l_enc.fit(df_weekly[l]) df_weekly["encoded_"+l] = encoder_weekly.transform(df_weekly[l]) y_hat_dtree_weekly = pipeline_model.predict(df_weekly) pref_filename = str(prefix_file)+str(i+1)+"_pred.csv" print(pref_filename, "accuracy_score:",accuracy_score(df_weekly["encoded_income"],y_hat_dtree_weekly),"\n") # save the prediction into file pd.DataFrame(y_hat_dtree_weekly).to_csv(str(pref_filename),header=["pred_income"], index=None) # lab 03 results: # adult_2021_cw_1.csv accuracy_score: 0.8293736501079914 # adult_2021_cw_2.csv accuracy_score: 0.8503253796095445 # adult_2021_cw_3.csv accuracy_score: 0.8427807486631016 # adult_2021_cw_4.csv accuracy_score: 0.8307860262008734 # adult_2021_cw_5.csv accuracy_score: 0.8507462686567164 # adult_2021_cw_6.csv accuracy_score: 0.854978354978355 # adult_2021_cw_7.csv accuracy_score: 0.8545454545454545 # adult_2021_cw_8.csv accuracy_score: 0.8514531754574811 # adult_2021_cw_9.csv accuracy_score: 0.8296943231441049 # adult_2021_cw_10.csv accuracy_score: 0.8574537540805223
36.341667
167
0.687686
import warnings import pickle import pandas as pd from sklearn.preprocessing import LabelEncoder from sklearn.metrics import accuracy_score warnings.filterwarnings("ignore") filename = 'adult.test' file_handler = open(filename, 'r').readlines()[1:] prefix_file = "adult_2021_cw_" week_number = 1 split_into = 10 line_count = 0 file_length = len(file_handler) for i in range(0,file_length): if i % ((file_length)//split_into) == 0 and i+((file_length//split_into)//2) < file_length: open(str(prefix_file)+str(week_number) + ".csv", "w+").writelines(file_handler[i:i+(file_length//split_into)]) week_number += 1 #This second script should read the input from this file and use the classifier to make predictions and write those predictions in the file adult_2021_cw_12_pred.csv . # load pipeline model pipeline_model = pickle.load( open("grid_search_model.pickle", "rb" )) weeks_count = 10 filename = 'adult.test' prefix_file = "adult_2021_cw_" # get the features names and the values of the categories from adult.names (build a dictionary) data_dict = {} with open('adult.names') as f: for l in f: if l[0] == '|' or ':' not in l: continue c = l.split(':') if c[1].startswith(' continuous'): data_dict[c[0]] = "" else: data_dict[c[0]] = c[1].replace("\n","").replace(".","").replace(" ","").split(",") header = list(data_dict.keys())+['income'] # for each week based on a count and a naming convention for i in range (weeks_count): filename = str(prefix_file)+str(i+1)+".csv" df_weekly = pd.read_table(filename, sep=r',\s', na_values='?', skiprows=[0], header=None, names=header).dropna() drop_list = ["education", "occupation", "relationship"] df_weekly = df_weekly.drop(columns=drop_list) dict_replace = { 'marital-status' : { 'Never-married': 'Not-Married', 'Married-civ-spouse': 'Married', 'Divorced': 'Not-Married', 'Married-spouse-absent': 'Married', 'Separated': 'Married', 'Married-AF-spouse': 'Married', 'Widowed': 'Not-Married' }, 'workclass': { 'State-gov': 'Government', 'Self-emp-not-inc': 'Self-Employment', 'Federal-gov': 'Government', 'Local-gov': 'Government', 'Self-emp-inc': 'Self-Employment' } } df_weekly.replace(dict_replace, inplace=True) df_weekly["income"].replace({"<=50K.": "<=50K", ">50K.": ">50K"}, inplace=True) for l in ["marital-status", "sex", "income"]: l_enc = LabelEncoder() encoder_weekly = l_enc.fit(df_weekly[l]) df_weekly["encoded_"+l] = encoder_weekly.transform(df_weekly[l]) y_hat_dtree_weekly = pipeline_model.predict(df_weekly) pref_filename = str(prefix_file)+str(i+1)+"_pred.csv" print(pref_filename, "accuracy_score:",accuracy_score(df_weekly["encoded_income"],y_hat_dtree_weekly),"\n") # save the prediction into file pd.DataFrame(y_hat_dtree_weekly).to_csv(str(pref_filename),header=["pred_income"], index=None) # lab 03 results: # adult_2021_cw_1.csv accuracy_score: 0.8293736501079914 # adult_2021_cw_2.csv accuracy_score: 0.8503253796095445 # adult_2021_cw_3.csv accuracy_score: 0.8427807486631016 # adult_2021_cw_4.csv accuracy_score: 0.8307860262008734 # adult_2021_cw_5.csv accuracy_score: 0.8507462686567164 # adult_2021_cw_6.csv accuracy_score: 0.854978354978355 # adult_2021_cw_7.csv accuracy_score: 0.8545454545454545 # adult_2021_cw_8.csv accuracy_score: 0.8514531754574811 # adult_2021_cw_9.csv accuracy_score: 0.8296943231441049 # adult_2021_cw_10.csv accuracy_score: 0.8574537540805223
true
true
f72c93dc9d0c650ab8f3bacc646cd04dbfed3888
92
py
Python
app/admin/__init__.py
baz1nga/Work-Shift
77df03120c4bc512703f02a653a6bbc982b14857
[ "MIT" ]
null
null
null
app/admin/__init__.py
baz1nga/Work-Shift
77df03120c4bc512703f02a653a6bbc982b14857
[ "MIT" ]
null
null
null
app/admin/__init__.py
baz1nga/Work-Shift
77df03120c4bc512703f02a653a6bbc982b14857
[ "MIT" ]
null
null
null
from flask import Blueprint bp = Blueprint('admin', __name__) from app.admin import views
15.333333
33
0.771739
from flask import Blueprint bp = Blueprint('admin', __name__) from app.admin import views
true
true
f72c94f9f4bcc67b00da8e6ffb7d26d5bc04f527
1,108
py
Python
puzzle14/14a.py
muellerd/advent_of_code20
4d9619de165b584f406ef8a1b136d79355dfe3e1
[ "MIT" ]
null
null
null
puzzle14/14a.py
muellerd/advent_of_code20
4d9619de165b584f406ef8a1b136d79355dfe3e1
[ "MIT" ]
null
null
null
puzzle14/14a.py
muellerd/advent_of_code20
4d9619de165b584f406ef8a1b136d79355dfe3e1
[ "MIT" ]
null
null
null
rows = [] with open("C:\\Privat\\advent_of_code20\\puzzle14\\input1.txt") as f: for line in f: rows.append(line.strip()) #print(rows) memory = {} currentMask = "" for line in rows: split = line.split(' = ') if 'mask' in split[0]: currentMask = split[1].strip() else: # value in bit bit = format(int(split[1]), '036b') # bit through mask maskl = len(currentMask) bitl = len(bit) result = '' #print(bit) #print(currentMask) for i in range(0, len(bit)): maskBit = currentMask[i] bitBit = bit[i] if maskBit != 'X': result += maskBit else: result += bitBit #print(result) toWrite = int(result, 2) # replace in memory memoryPosition = split[0][4:-1] if not memoryPosition in memory: memory[memoryPosition] = 0 memory[memoryPosition] = toWrite #print(memory) sum = 0 for key in memory: sum += memory[key] print("Sum of all values in memory: " + str(sum))
21.307692
69
0.525271
rows = [] with open("C:\\Privat\\advent_of_code20\\puzzle14\\input1.txt") as f: for line in f: rows.append(line.strip()) memory = {} currentMask = "" for line in rows: split = line.split(' = ') if 'mask' in split[0]: currentMask = split[1].strip() else: bit = format(int(split[1]), '036b') maskl = len(currentMask) bitl = len(bit) result = '' for i in range(0, len(bit)): maskBit = currentMask[i] bitBit = bit[i] if maskBit != 'X': result += maskBit else: result += bitBit toWrite = int(result, 2) memoryPosition = split[0][4:-1] if not memoryPosition in memory: memory[memoryPosition] = 0 memory[memoryPosition] = toWrite sum = 0 for key in memory: sum += memory[key] print("Sum of all values in memory: " + str(sum))
true
true
f72c9587c2b7459c937e13b276ff7e0feb632297
3,314
py
Python
detect_image.py
YunYang1994/CodeFun
36fcdbfb4ed55fbb8f8dbc6f900842cc7bb9f068
[ "MIT" ]
150
2019-06-19T03:54:40.000Z
2019-10-21T07:09:02.000Z
detect_image.py
YunYang1994/cv-notebooks
36fcdbfb4ed55fbb8f8dbc6f900842cc7bb9f068
[ "MIT" ]
7
2019-11-26T07:27:42.000Z
2020-04-02T03:35:29.000Z
detect_image.py
YunYang1994/cv-notebooks
36fcdbfb4ed55fbb8f8dbc6f900842cc7bb9f068
[ "MIT" ]
25
2019-11-27T11:07:56.000Z
2020-03-19T15:44:20.000Z
#! /usr/bin/env python # coding=utf-8 #================================================================ # Copyright (C) 2020 * Ltd. All rights reserved. # # Editor : VIM # File name : detect_image.py # Author : YunYang1994 # Created date: 2020-03-19 14:05:53 # Description : # #================================================================ import os import cv2 import time import numpy as np import tensorflow as tf from PIL import Image, ImageFont, ImageDraw from mtcnn import pnet, rnet, onet from models import IResnet from utils import detect_face, align_face, recognize_face model = IResnet(tflite_model="IResnet.tflite") font = ImageFont.truetype('weghts/HuaWenXinWei-1.ttf', 30) image = cv2.imread("/Users/yangyun/多人照片/5.jpg") image_h, image_w, _ = image.shape org_image = image.copy() image = cv2.cvtColor(image ,cv2.COLOR_BGR2RGB) total_boxes, points = detect_face(image, 20, pnet, rnet, onet, [0.6, 0.7, 0.9], 0.709) for idx, (bounding_box, keypoints) in enumerate(zip(total_boxes, points.T)): bounding_boxes = { 'box': [int(bounding_box[0]), int(bounding_box[1]), int(bounding_box[2]-bounding_box[0]), int(bounding_box[3]-bounding_box[1])], 'confidence': bounding_box[-1], 'keypoints': { 'left_eye': (int(keypoints[0]), int(keypoints[5])), 'right_eye': (int(keypoints[1]), int(keypoints[6])), 'nose': (int(keypoints[2]), int(keypoints[7])), 'mouth_left': (int(keypoints[3]), int(keypoints[8])), 'mouth_right': (int(keypoints[4]), int(keypoints[9])), } } bounding_box = bounding_boxes['box'] keypoints = bounding_boxes['keypoints'] cv2.circle(org_image,(keypoints['left_eye']), 2, (255,0,0), 3) cv2.circle(org_image,(keypoints['right_eye']), 2, (255,0,0), 3) cv2.circle(org_image,(keypoints['nose']), 2, (255,0,0), 3) cv2.circle(org_image,(keypoints['mouth_left']), 2, (255,0,0), 3) cv2.circle(org_image,(keypoints['mouth_right']),2, (255,0,0), 3) cv2.rectangle(org_image, (bounding_box[0], bounding_box[1]), (bounding_box[0]+bounding_box[2], bounding_box[1] + bounding_box[3]), (0,255,0), 2) # align face and extract it out align_image = align_face(image, keypoints) marigin = 16 xmin = max(bounding_box[0] - marigin, 0) ymin = max(bounding_box[1] - marigin, 0) xmax = min(bounding_box[0] + bounding_box[2] + marigin, image_w) ymax = min(bounding_box[1] + bounding_box[3] + marigin, image_h) crop_image = align_image[ymin:ymax, xmin:xmax, :] if crop_image is not None: t1 = time.time() embedding = model(crop_image) person = recognize_face(embedding) org_image_pil = Image.fromarray(org_image) draw = ImageDraw.Draw(org_image_pil) text_size = draw.textsize(person, font) draw.text((bounding_box[0], bounding_box[1]-16), person, fill=(0, 0, 255), font=font) org_image = np.array(org_image_pil) t2 = time.time() print("time: %.2fms" %((t2-t1)*1000)) org_image = cv2.cvtColor(org_image, cv2.COLOR_BGR2RGB) image = Image.fromarray(org_image) image.show() # image.save("test.png")
36.822222
96
0.601992
import os import cv2 import time import numpy as np import tensorflow as tf from PIL import Image, ImageFont, ImageDraw from mtcnn import pnet, rnet, onet from models import IResnet from utils import detect_face, align_face, recognize_face model = IResnet(tflite_model="IResnet.tflite") font = ImageFont.truetype('weghts/HuaWenXinWei-1.ttf', 30) image = cv2.imread("/Users/yangyun/多人照片/5.jpg") image_h, image_w, _ = image.shape org_image = image.copy() image = cv2.cvtColor(image ,cv2.COLOR_BGR2RGB) total_boxes, points = detect_face(image, 20, pnet, rnet, onet, [0.6, 0.7, 0.9], 0.709) for idx, (bounding_box, keypoints) in enumerate(zip(total_boxes, points.T)): bounding_boxes = { 'box': [int(bounding_box[0]), int(bounding_box[1]), int(bounding_box[2]-bounding_box[0]), int(bounding_box[3]-bounding_box[1])], 'confidence': bounding_box[-1], 'keypoints': { 'left_eye': (int(keypoints[0]), int(keypoints[5])), 'right_eye': (int(keypoints[1]), int(keypoints[6])), 'nose': (int(keypoints[2]), int(keypoints[7])), 'mouth_left': (int(keypoints[3]), int(keypoints[8])), 'mouth_right': (int(keypoints[4]), int(keypoints[9])), } } bounding_box = bounding_boxes['box'] keypoints = bounding_boxes['keypoints'] cv2.circle(org_image,(keypoints['left_eye']), 2, (255,0,0), 3) cv2.circle(org_image,(keypoints['right_eye']), 2, (255,0,0), 3) cv2.circle(org_image,(keypoints['nose']), 2, (255,0,0), 3) cv2.circle(org_image,(keypoints['mouth_left']), 2, (255,0,0), 3) cv2.circle(org_image,(keypoints['mouth_right']),2, (255,0,0), 3) cv2.rectangle(org_image, (bounding_box[0], bounding_box[1]), (bounding_box[0]+bounding_box[2], bounding_box[1] + bounding_box[3]), (0,255,0), 2) align_image = align_face(image, keypoints) marigin = 16 xmin = max(bounding_box[0] - marigin, 0) ymin = max(bounding_box[1] - marigin, 0) xmax = min(bounding_box[0] + bounding_box[2] + marigin, image_w) ymax = min(bounding_box[1] + bounding_box[3] + marigin, image_h) crop_image = align_image[ymin:ymax, xmin:xmax, :] if crop_image is not None: t1 = time.time() embedding = model(crop_image) person = recognize_face(embedding) org_image_pil = Image.fromarray(org_image) draw = ImageDraw.Draw(org_image_pil) text_size = draw.textsize(person, font) draw.text((bounding_box[0], bounding_box[1]-16), person, fill=(0, 0, 255), font=font) org_image = np.array(org_image_pil) t2 = time.time() print("time: %.2fms" %((t2-t1)*1000)) org_image = cv2.cvtColor(org_image, cv2.COLOR_BGR2RGB) image = Image.fromarray(org_image) image.show()
true
true
f72c966881d67f6b446e37599487a4a5d041df9b
60,197
py
Python
heat/engine/resources/openstack/nova/server.py
maestro-hybrid-cloud/heat
91a4bb3170bd81b1c67a896706851e55709c9b5a
[ "Apache-2.0" ]
null
null
null
heat/engine/resources/openstack/nova/server.py
maestro-hybrid-cloud/heat
91a4bb3170bd81b1c67a896706851e55709c9b5a
[ "Apache-2.0" ]
null
null
null
heat/engine/resources/openstack/nova/server.py
maestro-hybrid-cloud/heat
91a4bb3170bd81b1c67a896706851e55709c9b5a
[ "Apache-2.0" ]
null
null
null
# # 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 import uuid from oslo_config import cfg from oslo_log import log as logging from oslo_serialization import jsonutils from oslo_utils import uuidutils import six from heat.common import exception from heat.common.i18n import _ from heat.engine import attributes from heat.engine.clients import progress from heat.engine import constraints from heat.engine import function from heat.engine import properties from heat.engine.resources.openstack.neutron import port as neutron_port from heat.engine.resources.openstack.neutron import subnet from heat.engine.resources.openstack.nova import server_network_mixin from heat.engine.resources import scheduler_hints as sh from heat.engine.resources import stack_user from heat.engine import support from heat.rpc import api as rpc_api cfg.CONF.import_opt('default_software_config_transport', 'heat.common.config') LOG = logging.getLogger(__name__) class Server(stack_user.StackUser, sh.SchedulerHintsMixin, server_network_mixin.ServerNetworkMixin): PROPERTIES = ( NAME, IMAGE, BLOCK_DEVICE_MAPPING, BLOCK_DEVICE_MAPPING_V2, FLAVOR, FLAVOR_UPDATE_POLICY, IMAGE_UPDATE_POLICY, KEY_NAME, ADMIN_USER, AVAILABILITY_ZONE, SECURITY_GROUPS, NETWORKS, SCHEDULER_HINTS, METADATA, USER_DATA_FORMAT, USER_DATA, RESERVATION_ID, CONFIG_DRIVE, DISK_CONFIG, PERSONALITY, ADMIN_PASS, SOFTWARE_CONFIG_TRANSPORT ) = ( 'name', 'image', 'block_device_mapping', 'block_device_mapping_v2', 'flavor', 'flavor_update_policy', 'image_update_policy', 'key_name', 'admin_user', 'availability_zone', 'security_groups', 'networks', 'scheduler_hints', 'metadata', 'user_data_format', 'user_data', 'reservation_id', 'config_drive', 'diskConfig', 'personality', 'admin_pass', 'software_config_transport' ) _BLOCK_DEVICE_MAPPING_KEYS = ( BLOCK_DEVICE_MAPPING_DEVICE_NAME, BLOCK_DEVICE_MAPPING_VOLUME_ID, BLOCK_DEVICE_MAPPING_SNAPSHOT_ID, BLOCK_DEVICE_MAPPING_VOLUME_SIZE, BLOCK_DEVICE_MAPPING_DELETE_ON_TERM, ) = ( 'device_name', 'volume_id', 'snapshot_id', 'volume_size', 'delete_on_termination', ) _BLOCK_DEVICE_MAPPING_V2_KEYS = ( BLOCK_DEVICE_MAPPING_DEVICE_NAME, BLOCK_DEVICE_MAPPING_VOLUME_ID, BLOCK_DEVICE_MAPPING_IMAGE_ID, BLOCK_DEVICE_MAPPING_SNAPSHOT_ID, BLOCK_DEVICE_MAPPING_SWAP_SIZE, BLOCK_DEVICE_MAPPING_DEVICE_TYPE, BLOCK_DEVICE_MAPPING_DISK_BUS, BLOCK_DEVICE_MAPPING_BOOT_INDEX, BLOCK_DEVICE_MAPPING_VOLUME_SIZE, BLOCK_DEVICE_MAPPING_DELETE_ON_TERM, ) = ( 'device_name', 'volume_id', 'image_id', 'snapshot_id', 'swap_size', 'device_type', 'disk_bus', 'boot_index', 'volume_size', 'delete_on_termination', ) _NETWORK_KEYS = ( NETWORK_UUID, NETWORK_ID, NETWORK_FIXED_IP, NETWORK_PORT, NETWORK_SUBNET, NETWORK_PORT_EXTRA ) = ( 'uuid', 'network', 'fixed_ip', 'port', 'subnet', 'port_extra_properties' ) _SOFTWARE_CONFIG_FORMATS = ( HEAT_CFNTOOLS, RAW, SOFTWARE_CONFIG ) = ( 'HEAT_CFNTOOLS', 'RAW', 'SOFTWARE_CONFIG' ) _SOFTWARE_CONFIG_TRANSPORTS = ( POLL_SERVER_CFN, POLL_SERVER_HEAT, POLL_TEMP_URL, ZAQAR_MESSAGE ) = ( 'POLL_SERVER_CFN', 'POLL_SERVER_HEAT', 'POLL_TEMP_URL', 'ZAQAR_MESSAGE' ) ATTRIBUTES = ( NAME_ATTR, ADDRESSES, NETWORKS_ATTR, FIRST_ADDRESS, INSTANCE_NAME, ACCESSIPV4, ACCESSIPV6, CONSOLE_URLS, ) = ( 'name', 'addresses', 'networks', 'first_address', 'instance_name', 'accessIPv4', 'accessIPv6', 'console_urls', ) properties_schema = { NAME: properties.Schema( properties.Schema.STRING, _('Server name.'), update_allowed=True ), IMAGE: properties.Schema( properties.Schema.STRING, _('The ID or name of the image to boot with.'), constraints=[ constraints.CustomConstraint('glance.image') ], update_allowed=True ), BLOCK_DEVICE_MAPPING: properties.Schema( properties.Schema.LIST, _('Block device mappings for this server.'), schema=properties.Schema( properties.Schema.MAP, schema={ BLOCK_DEVICE_MAPPING_DEVICE_NAME: properties.Schema( properties.Schema.STRING, _('A device name where the volume will be ' 'attached in the system at /dev/device_name. ' 'This value is typically vda.'), required=True ), BLOCK_DEVICE_MAPPING_VOLUME_ID: properties.Schema( properties.Schema.STRING, _('The ID of the volume to boot from. Only one ' 'of volume_id or snapshot_id should be ' 'provided.'), constraints=[ constraints.CustomConstraint('cinder.volume') ] ), BLOCK_DEVICE_MAPPING_SNAPSHOT_ID: properties.Schema( properties.Schema.STRING, _('The ID of the snapshot to create a volume ' 'from.'), constraints=[ constraints.CustomConstraint('cinder.snapshot') ] ), BLOCK_DEVICE_MAPPING_VOLUME_SIZE: properties.Schema( properties.Schema.INTEGER, _('The size of the volume, in GB. It is safe to ' 'leave this blank and have the Compute service ' 'infer the size.') ), BLOCK_DEVICE_MAPPING_DELETE_ON_TERM: properties.Schema( properties.Schema.BOOLEAN, _('Indicate whether the volume should be deleted ' 'when the server is terminated.') ), }, ) ), BLOCK_DEVICE_MAPPING_V2: properties.Schema( properties.Schema.LIST, _('Block device mappings v2 for this server.'), schema=properties.Schema( properties.Schema.MAP, schema={ BLOCK_DEVICE_MAPPING_DEVICE_NAME: properties.Schema( properties.Schema.STRING, _('A device name where the volume will be ' 'attached in the system at /dev/device_name. ' 'This value is typically vda.'), ), BLOCK_DEVICE_MAPPING_VOLUME_ID: properties.Schema( properties.Schema.STRING, _('The volume_id can be boot or non-boot device ' 'to the server.'), constraints=[ constraints.CustomConstraint('cinder.volume') ] ), BLOCK_DEVICE_MAPPING_IMAGE_ID: properties.Schema( properties.Schema.STRING, _('The ID of the image to create a volume from.'), constraints=[ constraints.CustomConstraint('glance.image') ], ), BLOCK_DEVICE_MAPPING_SNAPSHOT_ID: properties.Schema( properties.Schema.STRING, _('The ID of the snapshot to create a volume ' 'from.'), constraints=[ constraints.CustomConstraint('cinder.snapshot') ] ), BLOCK_DEVICE_MAPPING_SWAP_SIZE: properties.Schema( properties.Schema.INTEGER, _('The size of the swap, in MB.') ), BLOCK_DEVICE_MAPPING_DEVICE_TYPE: properties.Schema( properties.Schema.STRING, _('Device type: at the moment we can make distinction' ' only between disk and cdrom.'), constraints=[ constraints.AllowedValues(['cdrom', 'disk']), ], ), BLOCK_DEVICE_MAPPING_DISK_BUS: properties.Schema( properties.Schema.STRING, _('Bus of the device: hypervisor driver chooses a ' 'suitable default if omitted.'), constraints=[ constraints.AllowedValues(['ide', 'lame_bus', 'scsi', 'usb', 'virtio']), ], ), BLOCK_DEVICE_MAPPING_BOOT_INDEX: properties.Schema( properties.Schema.INTEGER, _('Integer used for ordering the boot disks.'), ), BLOCK_DEVICE_MAPPING_VOLUME_SIZE: properties.Schema( properties.Schema.INTEGER, _('Size of the block device in GB. If it is omitted, ' 'hypervisor driver calculates size.'), ), BLOCK_DEVICE_MAPPING_DELETE_ON_TERM: properties.Schema( properties.Schema.BOOLEAN, _('Indicate whether the volume should be deleted ' 'when the server is terminated.') ), }, ), support_status=support.SupportStatus(version='2015.1') ), FLAVOR: properties.Schema( properties.Schema.STRING, _('The ID or name of the flavor to boot onto.'), required=True, update_allowed=True, constraints=[ constraints.CustomConstraint('nova.flavor') ] ), FLAVOR_UPDATE_POLICY: properties.Schema( properties.Schema.STRING, _('Policy on how to apply a flavor update; either by requesting ' 'a server resize or by replacing the entire server.'), default='RESIZE', constraints=[ constraints.AllowedValues(['RESIZE', 'REPLACE']), ], update_allowed=True ), IMAGE_UPDATE_POLICY: properties.Schema( properties.Schema.STRING, _('Policy on how to apply an image-id update; either by ' 'requesting a server rebuild or by replacing the entire server'), default='REBUILD', constraints=[ constraints.AllowedValues(['REBUILD', 'REPLACE', 'REBUILD_PRESERVE_EPHEMERAL']), ], update_allowed=True ), KEY_NAME: properties.Schema( properties.Schema.STRING, _('Name of keypair to inject into the server.'), constraints=[ constraints.CustomConstraint('nova.keypair') ] ), ADMIN_USER: properties.Schema( properties.Schema.STRING, _('Name of the administrative user to use on the server.'), support_status=support.SupportStatus( status=support.HIDDEN, version='5.0.0', message=_('The default cloud-init user set up for each image ' '(e.g. "ubuntu" for Ubuntu 12.04+, "fedora" for ' 'Fedora 19+ and "cloud-user" for CentOS/RHEL 6.5).'), previous_status=support.SupportStatus( status=support.DEPRECATED, version='2014.1', previous_status=support.SupportStatus(version='2013.2') ) ) ), AVAILABILITY_ZONE: properties.Schema( properties.Schema.STRING, _('Name of the availability zone for server placement.') ), SECURITY_GROUPS: properties.Schema( properties.Schema.LIST, _('List of security group names or IDs. Cannot be used if ' 'neutron ports are associated with this server; assign ' 'security groups to the ports instead.'), default=[] ), NETWORKS: properties.Schema( properties.Schema.LIST, _('An ordered list of nics to be added to this server, with ' 'information about connected networks, fixed ips, port etc.'), schema=properties.Schema( properties.Schema.MAP, schema={ NETWORK_UUID: properties.Schema( properties.Schema.STRING, _('ID of network to create a port on.'), support_status=support.SupportStatus( status=support.HIDDEN, version='5.0.0', previous_status=support.SupportStatus( status=support.DEPRECATED, message=_('Use property %s.') % NETWORK_ID, version='2014.1' ) ), constraints=[ constraints.CustomConstraint('neutron.network') ] ), NETWORK_ID: properties.Schema( properties.Schema.STRING, _('Name or ID of network to create a port on.'), constraints=[ constraints.CustomConstraint('neutron.network') ] ), NETWORK_FIXED_IP: properties.Schema( properties.Schema.STRING, _('Fixed IP address to specify for the port ' 'created on the requested network.'), constraints=[ constraints.CustomConstraint('ip_addr') ] ), NETWORK_PORT: properties.Schema( properties.Schema.STRING, _('ID of an existing port to associate with this ' 'server.'), constraints=[ constraints.CustomConstraint('neutron.port') ] ), NETWORK_PORT_EXTRA: properties.Schema( properties.Schema.MAP, _('Dict, which has expand properties for port. ' 'Used only if port property is not specified ' 'for creating port.'), schema=neutron_port.Port.extra_properties_schema, support_status=support.SupportStatus(version='6.0.0') ), NETWORK_SUBNET: properties.Schema( properties.Schema.STRING, _('Subnet in which to allocate the IP address for ' 'port. Used for creating port, based on derived ' 'properties. If subnet is specified, network ' 'property becomes optional.'), support_status=support.SupportStatus(version='5.0.0') ) }, ), update_allowed=True ), SCHEDULER_HINTS: properties.Schema( properties.Schema.MAP, _('Arbitrary key-value pairs specified by the client to help ' 'boot a server.') ), METADATA: properties.Schema( properties.Schema.MAP, _('Arbitrary key/value metadata to store for this server. Both ' 'keys and values must be 255 characters or less. Non-string ' 'values will be serialized to JSON (and the serialized ' 'string must be 255 characters or less).'), update_allowed=True ), USER_DATA_FORMAT: properties.Schema( properties.Schema.STRING, _('How the user_data should be formatted for the server. For ' 'HEAT_CFNTOOLS, the user_data is bundled as part of the ' 'heat-cfntools cloud-init boot configuration data. For RAW ' 'the user_data is passed to Nova unmodified. ' 'For SOFTWARE_CONFIG user_data is bundled as part of the ' 'software config data, and metadata is derived from any ' 'associated SoftwareDeployment resources.'), default=HEAT_CFNTOOLS, constraints=[ constraints.AllowedValues(_SOFTWARE_CONFIG_FORMATS), ] ), SOFTWARE_CONFIG_TRANSPORT: properties.Schema( properties.Schema.STRING, _('How the server should receive the metadata required for ' 'software configuration. POLL_SERVER_CFN will allow calls to ' 'the cfn API action DescribeStackResource authenticated with ' 'the provided keypair. POLL_SERVER_HEAT will allow calls to ' 'the Heat API resource-show using the provided keystone ' 'credentials. POLL_TEMP_URL will create and populate a ' 'Swift TempURL with metadata for polling. ZAQAR_MESSAGE will ' 'create a dedicated zaqar queue and post the metadata ' 'for polling.'), default=cfg.CONF.default_software_config_transport, constraints=[ constraints.AllowedValues(_SOFTWARE_CONFIG_TRANSPORTS), ] ), USER_DATA: properties.Schema( properties.Schema.STRING, _('User data script to be executed by cloud-init.'), default='' ), RESERVATION_ID: properties.Schema( properties.Schema.STRING, _('A UUID for the set of servers being requested.') ), CONFIG_DRIVE: properties.Schema( properties.Schema.BOOLEAN, _('If True, enable config drive on the server.') ), DISK_CONFIG: properties.Schema( properties.Schema.STRING, _('Control how the disk is partitioned when the server is ' 'created.'), constraints=[ constraints.AllowedValues(['AUTO', 'MANUAL']), ] ), PERSONALITY: properties.Schema( properties.Schema.MAP, _('A map of files to create/overwrite on the server upon boot. ' 'Keys are file names and values are the file contents.'), default={} ), ADMIN_PASS: properties.Schema( properties.Schema.STRING, _('The administrator password for the server.'), update_allowed=True ), } attributes_schema = { NAME_ATTR: attributes.Schema( _('Name of the server.'), type=attributes.Schema.STRING ), ADDRESSES: attributes.Schema( _('A dict of all network addresses with corresponding port_id. ' 'Each network will have two keys in dict, they are network ' 'name and network id. ' 'The port ID may be obtained through the following expression: ' '"{get_attr: [<server>, addresses, <network name_or_id>, 0, ' 'port]}".'), type=attributes.Schema.MAP ), NETWORKS_ATTR: attributes.Schema( _('A dict of assigned network addresses of the form: ' '{"public": [ip1, ip2...], "private": [ip3, ip4], ' '"public_uuid": [ip1, ip2...], "private_uuid": [ip3, ip4]}. ' 'Each network will have two keys in dict, they are network ' 'name and network id. '), type=attributes.Schema.MAP ), FIRST_ADDRESS: attributes.Schema( _('Convenience attribute to fetch the first assigned network ' 'address, or an empty string if nothing has been assigned at ' 'this time. Result may not be predictable if the server has ' 'addresses from more than one network.'), support_status=support.SupportStatus( status=support.HIDDEN, version='5.0.0', message=_('Use the networks attribute instead of ' 'first_address. For example: "{get_attr: ' '[<server name>, networks, <network name>, 0]}"'), previous_status=support.SupportStatus( status=support.DEPRECATED, version='2014.2', previous_status=support.SupportStatus(version='2013.2') ) ) ), INSTANCE_NAME: attributes.Schema( _('AWS compatible instance name.'), type=attributes.Schema.STRING ), ACCESSIPV4: attributes.Schema( _('The manually assigned alternative public IPv4 address ' 'of the server.'), type=attributes.Schema.STRING ), ACCESSIPV6: attributes.Schema( _('The manually assigned alternative public IPv6 address ' 'of the server.'), type=attributes.Schema.STRING ), CONSOLE_URLS: attributes.Schema( _("URLs of server's consoles. " "To get a specific console type, the requested type " "can be specified as parameter to the get_attr function, " "e.g. get_attr: [ <server>, console_urls, novnc ]. " "Currently supported types are " "novnc, xvpvnc, spice-html5, rdp-html5, serial."), support_status=support.SupportStatus(version='2015.1'), type=attributes.Schema.MAP ), } # Server host name limit to 53 characters by due to typical default # linux HOST_NAME_MAX of 64, minus the .novalocal appended to the name physical_resource_name_limit = 53 default_client_name = 'nova' entity = 'servers' def translation_rules(self): return [properties.TranslationRule( self.properties, properties.TranslationRule.REPLACE, source_path=[self.NETWORKS, self.NETWORK_ID], value_name=self.NETWORK_UUID)] def __init__(self, name, json_snippet, stack): super(Server, self).__init__(name, json_snippet, stack) if self.user_data_software_config(): self._register_access_key() def _server_name(self): name = self.properties[self.NAME] if name: return name return self.physical_resource_name() def _config_drive(self): # This method is overridden by the derived CloudServer resource return self.properties[self.CONFIG_DRIVE] def _populate_deployments_metadata(self, meta): meta['deployments'] = meta.get('deployments', []) meta['os-collect-config'] = meta.get('os-collect-config', {}) if self.transport_poll_server_heat(): meta['os-collect-config'].update({'heat': { 'user_id': self._get_user_id(), 'password': self.password, 'auth_url': self.context.auth_url, 'project_id': self.stack.stack_user_project_id, 'stack_id': self.stack.identifier().stack_path(), 'resource_name': self.name}}) if self.transport_zaqar_message(): queue_id = self.physical_resource_name() self.data_set('metadata_queue_id', queue_id) zaqar_plugin = self.client_plugin('zaqar') zaqar = zaqar_plugin.create_for_tenant( self.stack.stack_user_project_id) queue = zaqar.queue(queue_id) queue.post({'body': meta, 'ttl': zaqar_plugin.DEFAULT_TTL}) meta['os-collect-config'].update({'zaqar': { 'user_id': self._get_user_id(), 'password': self.password, 'auth_url': self.context.auth_url, 'project_id': self.stack.stack_user_project_id, 'queue_id': queue_id}}) elif self.transport_poll_server_cfn(): meta['os-collect-config'].update({'cfn': { 'metadata_url': '%s/v1/' % cfg.CONF.heat_metadata_server_url, 'access_key_id': self.access_key, 'secret_access_key': self.secret_key, 'stack_name': self.stack.name, 'path': '%s.Metadata' % self.name}}) elif self.transport_poll_temp_url(): container = self.physical_resource_name() object_name = str(uuid.uuid4()) self.client('swift').put_container(container) url = self.client_plugin('swift').get_temp_url( container, object_name, method='GET') put_url = self.client_plugin('swift').get_temp_url( container, object_name) self.data_set('metadata_put_url', put_url) self.data_set('metadata_object_name', object_name) meta['os-collect-config'].update({'request': { 'metadata_url': url}}) self.client('swift').put_object( container, object_name, jsonutils.dumps(meta)) self.metadata_set(meta) def _register_access_key(self): """Access is limited to this resource, which created the keypair.""" def access_allowed(resource_name): return resource_name == self.name if self.transport_poll_server_cfn(): self.stack.register_access_allowed_handler( self.access_key, access_allowed) elif self.transport_poll_server_heat(): self.stack.register_access_allowed_handler( self._get_user_id(), access_allowed) def _create_transport_credentials(self): if self.transport_poll_server_cfn(): self._create_user() self._create_keypair() elif (self.transport_poll_server_heat() or self.transport_zaqar_message()): self.password = uuid.uuid4().hex self._create_user() self._register_access_key() @property def access_key(self): return self.data().get('access_key') @property def secret_key(self): return self.data().get('secret_key') @property def password(self): return self.data().get('password') @password.setter def password(self, password): if password is None: self.data_delete('password') else: self.data_set('password', password, True) def user_data_raw(self): return self.properties[self.USER_DATA_FORMAT] == self.RAW def user_data_software_config(self): return self.properties[ self.USER_DATA_FORMAT] == self.SOFTWARE_CONFIG def transport_poll_server_cfn(self): return self.properties[ self.SOFTWARE_CONFIG_TRANSPORT] == self.POLL_SERVER_CFN def transport_poll_server_heat(self): return self.properties[ self.SOFTWARE_CONFIG_TRANSPORT] == self.POLL_SERVER_HEAT def transport_poll_temp_url(self): return self.properties[ self.SOFTWARE_CONFIG_TRANSPORT] == self.POLL_TEMP_URL def transport_zaqar_message(self): return self.properties.get( self.SOFTWARE_CONFIG_TRANSPORT) == self.ZAQAR_MESSAGE def get_software_config(self, ud_content): try: sc = self.rpc_client().show_software_config( self.context, ud_content) return sc[rpc_api.SOFTWARE_CONFIG_CONFIG] except Exception as ex: self.rpc_client().ignore_error_named(ex, 'NotFound') return ud_content def handle_create(self): security_groups = self.properties[self.SECURITY_GROUPS] user_data_format = self.properties[self.USER_DATA_FORMAT] ud_content = self.properties[self.USER_DATA] if self.user_data_software_config() or self.user_data_raw(): if uuidutils.is_uuid_like(ud_content): # attempt to load the userdata from software config ud_content = self.get_software_config(ud_content) metadata = self.metadata_get(True) or {} if self.user_data_software_config(): self._create_transport_credentials() self._populate_deployments_metadata(metadata) userdata = self.client_plugin().build_userdata( metadata, ud_content, instance_user=None, user_data_format=user_data_format) flavor = self.properties[self.FLAVOR] availability_zone = self.properties[self.AVAILABILITY_ZONE] image = self.properties[self.IMAGE] if image: image = self.client_plugin('glance').get_image_id(image) flavor_id = self.client_plugin().get_flavor_id(flavor) instance_meta = self.properties[self.METADATA] if instance_meta is not None: instance_meta = self.client_plugin().meta_serialize( instance_meta) scheduler_hints = self._scheduler_hints( self.properties[self.SCHEDULER_HINTS]) nics = self._build_nics(self.properties[self.NETWORKS]) block_device_mapping = self._build_block_device_mapping( self.properties[self.BLOCK_DEVICE_MAPPING]) block_device_mapping_v2 = self._build_block_device_mapping_v2( self.properties[self.BLOCK_DEVICE_MAPPING_V2]) reservation_id = self.properties[self.RESERVATION_ID] disk_config = self.properties[self.DISK_CONFIG] admin_pass = self.properties[self.ADMIN_PASS] or None personality_files = self.properties[self.PERSONALITY] key_name = self.properties[self.KEY_NAME] server = None try: server = self.client().servers.create( name=self._server_name(), image=image, flavor=flavor_id, key_name=key_name, security_groups=security_groups, userdata=userdata, meta=instance_meta, scheduler_hints=scheduler_hints, nics=nics, availability_zone=availability_zone, block_device_mapping=block_device_mapping, block_device_mapping_v2=block_device_mapping_v2, reservation_id=reservation_id, config_drive=self._config_drive(), disk_config=disk_config, files=personality_files, admin_pass=admin_pass) finally: # Avoid a race condition where the thread could be canceled # before the ID is stored if server is not None: self.resource_id_set(server.id) return server.id def check_create_complete(self, server_id): check = self.client_plugin()._check_active(server_id) if check: self.store_external_ports() return check def handle_check(self): server = self.client().servers.get(self.resource_id) status = self.client_plugin().get_status(server) checks = [{'attr': 'status', 'expected': 'ACTIVE', 'current': status}] self._verify_check_conditions(checks) @classmethod def _build_block_device_mapping(cls, bdm): if not bdm: return None bdm_dict = {} for mapping in bdm: mapping_parts = [] snapshot_id = mapping.get(cls.BLOCK_DEVICE_MAPPING_SNAPSHOT_ID) if snapshot_id: mapping_parts.append(snapshot_id) mapping_parts.append('snap') else: volume_id = mapping.get(cls.BLOCK_DEVICE_MAPPING_VOLUME_ID) mapping_parts.append(volume_id) mapping_parts.append('') volume_size = mapping.get(cls.BLOCK_DEVICE_MAPPING_VOLUME_SIZE) delete = mapping.get(cls.BLOCK_DEVICE_MAPPING_DELETE_ON_TERM) if volume_size: mapping_parts.append(str(volume_size)) else: mapping_parts.append('') if delete: mapping_parts.append(str(delete)) device_name = mapping.get(cls.BLOCK_DEVICE_MAPPING_DEVICE_NAME) bdm_dict[device_name] = ':'.join(mapping_parts) return bdm_dict @classmethod def _build_block_device_mapping_v2(cls, bdm_v2): if not bdm_v2: return None bdm_v2_list = [] for mapping in bdm_v2: bmd_dict = None if mapping.get(cls.BLOCK_DEVICE_MAPPING_VOLUME_ID): bmd_dict = { 'uuid': mapping.get(cls.BLOCK_DEVICE_MAPPING_VOLUME_ID), 'source_type': 'volume', 'destination_type': 'volume', 'boot_index': 0, 'delete_on_termination': False, } elif mapping.get(cls.BLOCK_DEVICE_MAPPING_SNAPSHOT_ID): bmd_dict = { 'uuid': mapping.get(cls.BLOCK_DEVICE_MAPPING_SNAPSHOT_ID), 'source_type': 'snapshot', 'destination_type': 'volume', 'boot_index': 0, 'delete_on_termination': False, } elif mapping.get(cls.BLOCK_DEVICE_MAPPING_IMAGE_ID): bmd_dict = { 'uuid': mapping.get(cls.BLOCK_DEVICE_MAPPING_IMAGE_ID), 'source_type': 'image', 'destination_type': 'volume', 'boot_index': 0, 'delete_on_termination': False, } elif mapping.get(cls.BLOCK_DEVICE_MAPPING_SWAP_SIZE): bmd_dict = { 'source_type': 'blank', 'destination_type': 'local', 'boot_index': -1, 'delete_on_termination': True, 'guest_format': 'swap', 'volume_size': mapping.get( cls.BLOCK_DEVICE_MAPPING_SWAP_SIZE), } # NOTE(prazumovsky): In case of server doesn't take empty value of # device name, need to escape from such situation. device_name = mapping.get(cls.BLOCK_DEVICE_MAPPING_DEVICE_NAME) if device_name: bmd_dict[cls.BLOCK_DEVICE_MAPPING_DEVICE_NAME] = device_name update_props = (cls.BLOCK_DEVICE_MAPPING_DEVICE_TYPE, cls.BLOCK_DEVICE_MAPPING_DISK_BUS, cls.BLOCK_DEVICE_MAPPING_BOOT_INDEX, cls.BLOCK_DEVICE_MAPPING_VOLUME_SIZE, cls.BLOCK_DEVICE_MAPPING_DELETE_ON_TERM) for update_prop in update_props: if mapping.get(update_prop) is not None: bmd_dict[update_prop] = mapping.get(update_prop) if bmd_dict: bdm_v2_list.append(bmd_dict) return bdm_v2_list def _add_port_for_address(self, server): """Method adds port id to list of addresses. This method is used only for resolving attributes. """ nets = copy.deepcopy(server.addresses) ifaces = server.interface_list() ip_mac_mapping_on_port_id = dict(((iface.fixed_ips[0]['ip_address'], iface.mac_addr), iface.port_id) for iface in ifaces) for net_name in nets: for addr in nets[net_name]: addr['port'] = ip_mac_mapping_on_port_id.get( (addr['addr'], addr['OS-EXT-IPS-MAC:mac_addr'])) return self._extend_networks(nets) def _extend_networks(self, networks): """Method adds same networks with replaced name on network id. This method is used only for resolving attributes. """ nets = copy.deepcopy(networks) for key in list(nets.keys()): try: net_id = self.client_plugin().get_net_id_by_label(key) except (exception.NovaNetworkNotFound, exception.PhysicalResourceNameAmbiguity): net_id = None if net_id: nets[net_id] = nets[key] return nets def _resolve_attribute(self, name): if name == self.FIRST_ADDRESS: return self.client_plugin().server_to_ipaddress( self.resource_id) or '' if name == self.NAME_ATTR: return self._server_name() try: server = self.client().servers.get(self.resource_id) except Exception as e: self.client_plugin().ignore_not_found(e) return '' if name == self.ADDRESSES: return self._add_port_for_address(server) if name == self.NETWORKS_ATTR: return self._extend_networks(server.networks) if name == self.INSTANCE_NAME: return getattr(server, 'OS-EXT-SRV-ATTR:instance_name', None) if name == self.ACCESSIPV4: return server.accessIPv4 if name == self.ACCESSIPV6: return server.accessIPv6 if name == self.CONSOLE_URLS: return self.client_plugin('nova').get_console_urls(server) def add_dependencies(self, deps): super(Server, self).add_dependencies(deps) # Depend on any Subnet in this template with the same # network_id as the networks attached to this server. # It is not known which subnet a server might be assigned # to so all subnets in a network should be created before # the servers in that network. nets = self.properties[self.NETWORKS] if not nets: return for res in six.itervalues(self.stack): if res.has_interface('OS::Neutron::Subnet'): subnet_net = (res.properties.get(subnet.Subnet.NETWORK_ID) or res.properties.get(subnet.Subnet.NETWORK)) for net in nets: # worry about network_id because that could be the match # assigned to the subnet as well and could have been # created by this stack. Regardless, the server should # still wait on the subnet. net_id = (net.get(self.NETWORK_ID) or net.get(self.NETWORK_UUID)) if net_id and net_id == subnet_net: deps += (self, res) break def _update_flavor(self, prop_diff): flavor = prop_diff[self.FLAVOR] flavor_id = self.client_plugin().get_flavor_id(flavor) handler_args = {'args': (flavor_id,)} checker_args = {'args': (flavor_id, flavor)} prg_resize = progress.ServerUpdateProgress(self.resource_id, 'resize', handler_extra=handler_args, checker_extra=checker_args) prg_verify = progress.ServerUpdateProgress(self.resource_id, 'verify_resize') return prg_resize, prg_verify def _update_image(self, prop_diff): image_update_policy = ( prop_diff.get(self.IMAGE_UPDATE_POLICY) or self.properties[self.IMAGE_UPDATE_POLICY]) image = prop_diff[self.IMAGE] image_id = self.client_plugin('glance').get_image_id(image) preserve_ephemeral = ( image_update_policy == 'REBUILD_PRESERVE_EPHEMERAL') password = (prop_diff.get(self.ADMIN_PASS) or self.properties[self.ADMIN_PASS]) kwargs = {'password': password, 'preserve_ephemeral': preserve_ephemeral} prg = progress.ServerUpdateProgress(self.resource_id, 'rebuild', handler_extra={'args': (image_id,), 'kwargs': kwargs}) return prg def _update_networks(self, server, prop_diff): updaters = [] new_networks = prop_diff.get(self.NETWORKS) old_networks = self.properties[self.NETWORKS] if not server: server = self.client().servers.get(self.resource_id) interfaces = server.interface_list() remove_ports, add_nets = self.calculate_networks( old_networks, new_networks, interfaces) for port in remove_ports: updaters.append( progress.ServerUpdateProgress( self.resource_id, 'interface_detach', complete=True, handler_extra={'args': (port,)}) ) for args in add_nets: updaters.append( progress.ServerUpdateProgress( self.resource_id, 'interface_attach', complete=True, handler_extra={'kwargs': args}) ) return updaters def _needs_update(self, after, before, after_props, before_props, prev_resource, check_init_complete=True): result = super(Server, self)._needs_update( after, before, after_props, before_props, prev_resource, check_init_complete=check_init_complete) prop_diff = self.update_template_diff_properties(after_props, before_props) if self.FLAVOR in prop_diff: flavor_update_policy = ( prop_diff.get(self.FLAVOR_UPDATE_POLICY) or self.properties[self.FLAVOR_UPDATE_POLICY]) if flavor_update_policy == 'REPLACE': raise exception.UpdateReplace(self.name) if self.IMAGE in prop_diff: image_update_policy = ( prop_diff.get(self.IMAGE_UPDATE_POLICY) or self.properties[self.IMAGE_UPDATE_POLICY]) if image_update_policy == 'REPLACE': raise exception.UpdateReplace(self.name) return result def handle_update(self, json_snippet, tmpl_diff, prop_diff): if 'Metadata' in tmpl_diff: # If SOFTWARE_CONFIG user_data_format is enabled we require # the "deployments" and "os-collect-config" keys for Deployment # polling. We can attempt to merge the occ data, but any # metadata update containing deployments will be discarded. if self.user_data_software_config(): metadata = self.metadata_get(True) or {} new_occ_md = tmpl_diff['Metadata'].get('os-collect-config', {}) occ_md = metadata.get('os-collect-config', {}) occ_md.update(new_occ_md) tmpl_diff['Metadata']['os-collect-config'] = occ_md deployment_md = metadata.get('deployments', []) tmpl_diff['Metadata']['deployments'] = deployment_md self.metadata_set(tmpl_diff['Metadata']) updaters = [] server = None if self.METADATA in prop_diff: server = self.client().servers.get(self.resource_id) self.client_plugin().meta_update(server, prop_diff[self.METADATA]) if self.FLAVOR in prop_diff: updaters.extend(self._update_flavor(prop_diff)) if self.IMAGE in prop_diff: updaters.append(self._update_image(prop_diff)) elif self.ADMIN_PASS in prop_diff: if not server: server = self.client().servers.get(self.resource_id) server.change_password(prop_diff[self.ADMIN_PASS]) if self.NAME in prop_diff: if not server: server = self.client().servers.get(self.resource_id) self.client_plugin().rename(server, prop_diff[self.NAME]) if self.NETWORKS in prop_diff: updaters.extend(self._update_networks(server, prop_diff)) # NOTE(pas-ha) optimization is possible (starting first task # right away), but we'd rather not, as this method already might # have called several APIs return updaters def check_update_complete(self, updaters): """Push all updaters to completion in list order.""" for prg in updaters: if not prg.called: handler = getattr(self.client_plugin(), prg.handler) prg.called = handler(*prg.handler_args, **prg.handler_kwargs) return False if not prg.complete: check_complete = getattr(self.client_plugin(), prg.checker) prg.complete = check_complete(*prg.checker_args, **prg.checker_kwargs) break status = all(prg.complete for prg in updaters) if status: self.store_external_ports() return status def metadata_update(self, new_metadata=None): """Refresh the metadata if new_metadata is None.""" if new_metadata is None: # Re-resolve the template metadata and merge it with the # current resource metadata. This is necessary because the # attributes referenced in the template metadata may change # and the resource itself adds keys to the metadata which # are not specified in the template (e.g the deployments data) meta = self.metadata_get(refresh=True) or {} tmpl_meta = self.t.metadata() meta.update(tmpl_meta) self.metadata_set(meta) @staticmethod def _check_maximum(count, maximum, msg): """Check a count against a maximum. Unless maximum is -1 which indicates that there is no limit. """ if maximum != -1 and count > maximum: raise exception.StackValidationFailed(message=msg) def _validate_block_device_mapping(self): # either volume_id or snapshot_id needs to be specified, but not both # for block device mapping. bdm = self.properties[self.BLOCK_DEVICE_MAPPING] or [] bootable_vol = False for mapping in bdm: device_name = mapping[self.BLOCK_DEVICE_MAPPING_DEVICE_NAME] if device_name == 'vda': bootable_vol = True volume_id = mapping.get(self.BLOCK_DEVICE_MAPPING_VOLUME_ID) snapshot_id = mapping.get(self.BLOCK_DEVICE_MAPPING_SNAPSHOT_ID) if volume_id is not None and snapshot_id is not None: raise exception.ResourcePropertyConflict( self.BLOCK_DEVICE_MAPPING_VOLUME_ID, self.BLOCK_DEVICE_MAPPING_SNAPSHOT_ID) if volume_id is None and snapshot_id is None: msg = _('Either volume_id or snapshot_id must be specified for' ' device mapping %s') % device_name raise exception.StackValidationFailed(message=msg) bdm_v2 = self.properties[self.BLOCK_DEVICE_MAPPING_V2] or [] if bdm and bdm_v2: raise exception.ResourcePropertyConflict( self.BLOCK_DEVICE_MAPPING, self.BLOCK_DEVICE_MAPPING_V2) for mapping in bdm_v2: volume_id = mapping.get(self.BLOCK_DEVICE_MAPPING_VOLUME_ID) snapshot_id = mapping.get(self.BLOCK_DEVICE_MAPPING_SNAPSHOT_ID) image_id = mapping.get(self.BLOCK_DEVICE_MAPPING_IMAGE_ID) swap_size = mapping.get(self.BLOCK_DEVICE_MAPPING_SWAP_SIZE) property_tuple = (volume_id, snapshot_id, image_id, swap_size) if property_tuple.count(None) < 3: raise exception.ResourcePropertyConflict( self.BLOCK_DEVICE_MAPPING_VOLUME_ID, self.BLOCK_DEVICE_MAPPING_SNAPSHOT_ID, self.BLOCK_DEVICE_MAPPING_IMAGE_ID, self.BLOCK_DEVICE_MAPPING_SWAP_SIZE) if property_tuple.count(None) == 4: msg = _('Either volume_id, snapshot_id, image_id or ' 'swap_size must be specified.') raise exception.StackValidationFailed(message=msg) if any((volume_id, snapshot_id, image_id)): bootable_vol = True return bootable_vol def validate(self): """Validate any of the provided params.""" super(Server, self).validate() if self.user_data_software_config(): if 'deployments' in self.t.metadata(): msg = _('deployments key not allowed in resource metadata ' 'with user_data_format of SOFTWARE_CONFIG') raise exception.StackValidationFailed(message=msg) bootable_vol = self._validate_block_device_mapping() # make sure the image exists if specified. image = self.properties[self.IMAGE] if not image and not bootable_vol: msg = _('Neither image nor bootable volume is specified for' ' instance %s') % self.name raise exception.StackValidationFailed(message=msg) # network properties 'uuid' and 'network' shouldn't be used # both at once for all networks networks = self.properties[self.NETWORKS] or [] # record if any networks include explicit ports networks_with_port = False for network in networks: networks_with_port = (networks_with_port or network.get(self.NETWORK_PORT)) self._validate_network(network) # retrieve provider's absolute limits if it will be needed metadata = self.properties[self.METADATA] personality = self.properties[self.PERSONALITY] if metadata is not None or personality: limits = self.client_plugin().absolute_limits() # if 'security_groups' present for the server and explict 'port' # in one or more entries in 'networks', raise validation error if networks_with_port and self.properties[self.SECURITY_GROUPS]: raise exception.ResourcePropertyConflict( self.SECURITY_GROUPS, "/".join([self.NETWORKS, self.NETWORK_PORT])) # verify that the number of metadata entries is not greater # than the maximum number allowed in the provider's absolute # limits if metadata is not None: msg = _('Instance metadata must not contain greater than %s ' 'entries. This is the maximum number allowed by your ' 'service provider') % limits['maxServerMeta'] self._check_maximum(len(metadata), limits['maxServerMeta'], msg) # verify the number of personality files and the size of each # personality file against the provider's absolute limits if personality: msg = _("The personality property may not contain " "greater than %s entries.") % limits['maxPersonality'] self._check_maximum(len(personality), limits['maxPersonality'], msg) for path, contents in personality.items(): msg = (_("The contents of personality file \"%(path)s\" " "is larger than the maximum allowed personality " "file size (%(max_size)s bytes).") % {'path': path, 'max_size': limits['maxPersonalitySize']}) self._check_maximum(len(bytes(contents.encode('utf-8'))), limits['maxPersonalitySize'], msg) def _delete_temp_url(self): object_name = self.data().get('metadata_object_name') if not object_name: return try: container = self.physical_resource_name() swift = self.client('swift') swift.delete_object(container, object_name) headers = swift.head_container(container) if int(headers['x-container-object-count']) == 0: swift.delete_container(container) except Exception as ex: self.client_plugin('swift').ignore_not_found(ex) def _delete_queue(self): queue_id = self.data().get('metadata_queue_id') if not queue_id: return client_plugin = self.client_plugin('zaqar') zaqar = client_plugin.create_for_tenant( self.stack.stack_user_project_id) try: zaqar.queue(queue_id).delete() except Exception as ex: client_plugin.ignore_not_found(ex) self.data_delete('metadata_queue_id') def handle_snapshot_delete(self, state): if state[0] != self.FAILED: image_id = self.client().servers.create_image( self.resource_id, self.physical_resource_name()) return progress.ServerDeleteProgress( self.resource_id, image_id, False) return self.handle_delete() def handle_delete(self): if self.resource_id is None: return if self.user_data_software_config(): self._delete_user() self._delete_temp_url() self._delete_queue() # remove internal and external ports self._delete_internal_ports() self.data_delete('external_ports') try: self.client().servers.delete(self.resource_id) except Exception as e: self.client_plugin().ignore_not_found(e) return return progress.ServerDeleteProgress(self.resource_id) def check_delete_complete(self, prg): if not prg: return True if not prg.image_complete: image = self.client().images.get(prg.image_id) if image.status in ('DELETED', 'ERROR'): raise exception.Error(image.status) elif image.status == 'ACTIVE': prg.image_complete = True if not self.handle_delete(): return True return False return self.client_plugin().check_delete_server_complete( prg.server_id) def handle_suspend(self): """Suspend a server. Note we do not wait for the SUSPENDED state, this is polled for by check_suspend_complete in a similar way to the create logic so we can take advantage of coroutines. """ if self.resource_id is None: raise exception.Error(_('Cannot suspend %s, resource_id not set') % self.name) try: server = self.client().servers.get(self.resource_id) except Exception as e: if self.client_plugin().is_not_found(e): raise exception.NotFound(_('Failed to find server %s') % self.resource_id) else: raise else: # if the server has been suspended successful, # no need to suspend again if self.client_plugin().get_status(server) != 'SUSPENDED': LOG.debug('suspending server %s' % self.resource_id) server.suspend() return server.id def check_suspend_complete(self, server_id): cp = self.client_plugin() server = cp.fetch_server(server_id) if not server: return False status = cp.get_status(server) LOG.debug('%(name)s check_suspend_complete status = %(status)s' % {'name': self.name, 'status': status}) if status in list(cp.deferred_server_statuses + ['ACTIVE']): return status == 'SUSPENDED' else: exc = exception.ResourceUnknownStatus( result=_('Suspend of server %s failed') % server.name, resource_status=status) raise exc def handle_resume(self): """Resume a server. Note we do not wait for the ACTIVE state, this is polled for by check_resume_complete in a similar way to the create logic so we can take advantage of coroutines. """ if self.resource_id is None: raise exception.Error(_('Cannot resume %s, resource_id not set') % self.name) try: server = self.client().servers.get(self.resource_id) except Exception as e: if self.client_plugin().is_not_found(e): raise exception.NotFound(_('Failed to find server %s') % self.resource_id) else: raise else: # if the server has been resumed successful, # no need to resume again if self.client_plugin().get_status(server) != 'ACTIVE': LOG.debug('resuming server %s' % self.resource_id) server.resume() return server.id def check_resume_complete(self, server_id): return self.client_plugin()._check_active(server_id) def handle_snapshot(self): image_id = self.client().servers.create_image( self.resource_id, self.physical_resource_name()) self.data_set('snapshot_image_id', image_id) return image_id def check_snapshot_complete(self, image_id): image = self.client().images.get(image_id) if image.status == 'ACTIVE': return True elif image.status == 'ERROR' or image.status == 'DELETED': raise exception.Error(image.status) return False def handle_delete_snapshot(self, snapshot): image_id = snapshot['resource_data'].get('snapshot_image_id') try: self.client().images.delete(image_id) except Exception as e: self.client_plugin().ignore_not_found(e) def handle_restore(self, defn, restore_data): image_id = restore_data['resource_data']['snapshot_image_id'] props = function.resolve(self.properties.data) props[self.IMAGE] = image_id return defn.freeze(properties=props) def prepare_for_replace(self): self.prepare_ports_for_replace() def restore_prev_rsrc(self, convergence=False): self.restore_ports_after_rollback(convergence=convergence) def resource_mapping(): return { 'OS::Nova::Server': Server, }
42.037011
79
0.570842
import copy import uuid from oslo_config import cfg from oslo_log import log as logging from oslo_serialization import jsonutils from oslo_utils import uuidutils import six from heat.common import exception from heat.common.i18n import _ from heat.engine import attributes from heat.engine.clients import progress from heat.engine import constraints from heat.engine import function from heat.engine import properties from heat.engine.resources.openstack.neutron import port as neutron_port from heat.engine.resources.openstack.neutron import subnet from heat.engine.resources.openstack.nova import server_network_mixin from heat.engine.resources import scheduler_hints as sh from heat.engine.resources import stack_user from heat.engine import support from heat.rpc import api as rpc_api cfg.CONF.import_opt('default_software_config_transport', 'heat.common.config') LOG = logging.getLogger(__name__) class Server(stack_user.StackUser, sh.SchedulerHintsMixin, server_network_mixin.ServerNetworkMixin): PROPERTIES = ( NAME, IMAGE, BLOCK_DEVICE_MAPPING, BLOCK_DEVICE_MAPPING_V2, FLAVOR, FLAVOR_UPDATE_POLICY, IMAGE_UPDATE_POLICY, KEY_NAME, ADMIN_USER, AVAILABILITY_ZONE, SECURITY_GROUPS, NETWORKS, SCHEDULER_HINTS, METADATA, USER_DATA_FORMAT, USER_DATA, RESERVATION_ID, CONFIG_DRIVE, DISK_CONFIG, PERSONALITY, ADMIN_PASS, SOFTWARE_CONFIG_TRANSPORT ) = ( 'name', 'image', 'block_device_mapping', 'block_device_mapping_v2', 'flavor', 'flavor_update_policy', 'image_update_policy', 'key_name', 'admin_user', 'availability_zone', 'security_groups', 'networks', 'scheduler_hints', 'metadata', 'user_data_format', 'user_data', 'reservation_id', 'config_drive', 'diskConfig', 'personality', 'admin_pass', 'software_config_transport' ) _BLOCK_DEVICE_MAPPING_KEYS = ( BLOCK_DEVICE_MAPPING_DEVICE_NAME, BLOCK_DEVICE_MAPPING_VOLUME_ID, BLOCK_DEVICE_MAPPING_SNAPSHOT_ID, BLOCK_DEVICE_MAPPING_VOLUME_SIZE, BLOCK_DEVICE_MAPPING_DELETE_ON_TERM, ) = ( 'device_name', 'volume_id', 'snapshot_id', 'volume_size', 'delete_on_termination', ) _BLOCK_DEVICE_MAPPING_V2_KEYS = ( BLOCK_DEVICE_MAPPING_DEVICE_NAME, BLOCK_DEVICE_MAPPING_VOLUME_ID, BLOCK_DEVICE_MAPPING_IMAGE_ID, BLOCK_DEVICE_MAPPING_SNAPSHOT_ID, BLOCK_DEVICE_MAPPING_SWAP_SIZE, BLOCK_DEVICE_MAPPING_DEVICE_TYPE, BLOCK_DEVICE_MAPPING_DISK_BUS, BLOCK_DEVICE_MAPPING_BOOT_INDEX, BLOCK_DEVICE_MAPPING_VOLUME_SIZE, BLOCK_DEVICE_MAPPING_DELETE_ON_TERM, ) = ( 'device_name', 'volume_id', 'image_id', 'snapshot_id', 'swap_size', 'device_type', 'disk_bus', 'boot_index', 'volume_size', 'delete_on_termination', ) _NETWORK_KEYS = ( NETWORK_UUID, NETWORK_ID, NETWORK_FIXED_IP, NETWORK_PORT, NETWORK_SUBNET, NETWORK_PORT_EXTRA ) = ( 'uuid', 'network', 'fixed_ip', 'port', 'subnet', 'port_extra_properties' ) _SOFTWARE_CONFIG_FORMATS = ( HEAT_CFNTOOLS, RAW, SOFTWARE_CONFIG ) = ( 'HEAT_CFNTOOLS', 'RAW', 'SOFTWARE_CONFIG' ) _SOFTWARE_CONFIG_TRANSPORTS = ( POLL_SERVER_CFN, POLL_SERVER_HEAT, POLL_TEMP_URL, ZAQAR_MESSAGE ) = ( 'POLL_SERVER_CFN', 'POLL_SERVER_HEAT', 'POLL_TEMP_URL', 'ZAQAR_MESSAGE' ) ATTRIBUTES = ( NAME_ATTR, ADDRESSES, NETWORKS_ATTR, FIRST_ADDRESS, INSTANCE_NAME, ACCESSIPV4, ACCESSIPV6, CONSOLE_URLS, ) = ( 'name', 'addresses', 'networks', 'first_address', 'instance_name', 'accessIPv4', 'accessIPv6', 'console_urls', ) properties_schema = { NAME: properties.Schema( properties.Schema.STRING, _('Server name.'), update_allowed=True ), IMAGE: properties.Schema( properties.Schema.STRING, _('The ID or name of the image to boot with.'), constraints=[ constraints.CustomConstraint('glance.image') ], update_allowed=True ), BLOCK_DEVICE_MAPPING: properties.Schema( properties.Schema.LIST, _('Block device mappings for this server.'), schema=properties.Schema( properties.Schema.MAP, schema={ BLOCK_DEVICE_MAPPING_DEVICE_NAME: properties.Schema( properties.Schema.STRING, _('A device name where the volume will be ' 'attached in the system at /dev/device_name. ' 'This value is typically vda.'), required=True ), BLOCK_DEVICE_MAPPING_VOLUME_ID: properties.Schema( properties.Schema.STRING, _('The ID of the volume to boot from. Only one ' 'of volume_id or snapshot_id should be ' 'provided.'), constraints=[ constraints.CustomConstraint('cinder.volume') ] ), BLOCK_DEVICE_MAPPING_SNAPSHOT_ID: properties.Schema( properties.Schema.STRING, _('The ID of the snapshot to create a volume ' 'from.'), constraints=[ constraints.CustomConstraint('cinder.snapshot') ] ), BLOCK_DEVICE_MAPPING_VOLUME_SIZE: properties.Schema( properties.Schema.INTEGER, _('The size of the volume, in GB. It is safe to ' 'leave this blank and have the Compute service ' 'infer the size.') ), BLOCK_DEVICE_MAPPING_DELETE_ON_TERM: properties.Schema( properties.Schema.BOOLEAN, _('Indicate whether the volume should be deleted ' 'when the server is terminated.') ), }, ) ), BLOCK_DEVICE_MAPPING_V2: properties.Schema( properties.Schema.LIST, _('Block device mappings v2 for this server.'), schema=properties.Schema( properties.Schema.MAP, schema={ BLOCK_DEVICE_MAPPING_DEVICE_NAME: properties.Schema( properties.Schema.STRING, _('A device name where the volume will be ' 'attached in the system at /dev/device_name. ' 'This value is typically vda.'), ), BLOCK_DEVICE_MAPPING_VOLUME_ID: properties.Schema( properties.Schema.STRING, _('The volume_id can be boot or non-boot device ' 'to the server.'), constraints=[ constraints.CustomConstraint('cinder.volume') ] ), BLOCK_DEVICE_MAPPING_IMAGE_ID: properties.Schema( properties.Schema.STRING, _('The ID of the image to create a volume from.'), constraints=[ constraints.CustomConstraint('glance.image') ], ), BLOCK_DEVICE_MAPPING_SNAPSHOT_ID: properties.Schema( properties.Schema.STRING, _('The ID of the snapshot to create a volume ' 'from.'), constraints=[ constraints.CustomConstraint('cinder.snapshot') ] ), BLOCK_DEVICE_MAPPING_SWAP_SIZE: properties.Schema( properties.Schema.INTEGER, _('The size of the swap, in MB.') ), BLOCK_DEVICE_MAPPING_DEVICE_TYPE: properties.Schema( properties.Schema.STRING, _('Device type: at the moment we can make distinction' ' only between disk and cdrom.'), constraints=[ constraints.AllowedValues(['cdrom', 'disk']), ], ), BLOCK_DEVICE_MAPPING_DISK_BUS: properties.Schema( properties.Schema.STRING, _('Bus of the device: hypervisor driver chooses a ' 'suitable default if omitted.'), constraints=[ constraints.AllowedValues(['ide', 'lame_bus', 'scsi', 'usb', 'virtio']), ], ), BLOCK_DEVICE_MAPPING_BOOT_INDEX: properties.Schema( properties.Schema.INTEGER, _('Integer used for ordering the boot disks.'), ), BLOCK_DEVICE_MAPPING_VOLUME_SIZE: properties.Schema( properties.Schema.INTEGER, _('Size of the block device in GB. If it is omitted, ' 'hypervisor driver calculates size.'), ), BLOCK_DEVICE_MAPPING_DELETE_ON_TERM: properties.Schema( properties.Schema.BOOLEAN, _('Indicate whether the volume should be deleted ' 'when the server is terminated.') ), }, ), support_status=support.SupportStatus(version='2015.1') ), FLAVOR: properties.Schema( properties.Schema.STRING, _('The ID or name of the flavor to boot onto.'), required=True, update_allowed=True, constraints=[ constraints.CustomConstraint('nova.flavor') ] ), FLAVOR_UPDATE_POLICY: properties.Schema( properties.Schema.STRING, _('Policy on how to apply a flavor update; either by requesting ' 'a server resize or by replacing the entire server.'), default='RESIZE', constraints=[ constraints.AllowedValues(['RESIZE', 'REPLACE']), ], update_allowed=True ), IMAGE_UPDATE_POLICY: properties.Schema( properties.Schema.STRING, _('Policy on how to apply an image-id update; either by ' 'requesting a server rebuild or by replacing the entire server'), default='REBUILD', constraints=[ constraints.AllowedValues(['REBUILD', 'REPLACE', 'REBUILD_PRESERVE_EPHEMERAL']), ], update_allowed=True ), KEY_NAME: properties.Schema( properties.Schema.STRING, _('Name of keypair to inject into the server.'), constraints=[ constraints.CustomConstraint('nova.keypair') ] ), ADMIN_USER: properties.Schema( properties.Schema.STRING, _('Name of the administrative user to use on the server.'), support_status=support.SupportStatus( status=support.HIDDEN, version='5.0.0', message=_('The default cloud-init user set up for each image ' '(e.g. "ubuntu" for Ubuntu 12.04+, "fedora" for ' 'Fedora 19+ and "cloud-user" for CentOS/RHEL 6.5).'), previous_status=support.SupportStatus( status=support.DEPRECATED, version='2014.1', previous_status=support.SupportStatus(version='2013.2') ) ) ), AVAILABILITY_ZONE: properties.Schema( properties.Schema.STRING, _('Name of the availability zone for server placement.') ), SECURITY_GROUPS: properties.Schema( properties.Schema.LIST, _('List of security group names or IDs. Cannot be used if ' 'neutron ports are associated with this server; assign ' 'security groups to the ports instead.'), default=[] ), NETWORKS: properties.Schema( properties.Schema.LIST, _('An ordered list of nics to be added to this server, with ' 'information about connected networks, fixed ips, port etc.'), schema=properties.Schema( properties.Schema.MAP, schema={ NETWORK_UUID: properties.Schema( properties.Schema.STRING, _('ID of network to create a port on.'), support_status=support.SupportStatus( status=support.HIDDEN, version='5.0.0', previous_status=support.SupportStatus( status=support.DEPRECATED, message=_('Use property %s.') % NETWORK_ID, version='2014.1' ) ), constraints=[ constraints.CustomConstraint('neutron.network') ] ), NETWORK_ID: properties.Schema( properties.Schema.STRING, _('Name or ID of network to create a port on.'), constraints=[ constraints.CustomConstraint('neutron.network') ] ), NETWORK_FIXED_IP: properties.Schema( properties.Schema.STRING, _('Fixed IP address to specify for the port ' 'created on the requested network.'), constraints=[ constraints.CustomConstraint('ip_addr') ] ), NETWORK_PORT: properties.Schema( properties.Schema.STRING, _('ID of an existing port to associate with this ' 'server.'), constraints=[ constraints.CustomConstraint('neutron.port') ] ), NETWORK_PORT_EXTRA: properties.Schema( properties.Schema.MAP, _('Dict, which has expand properties for port. ' 'Used only if port property is not specified ' 'for creating port.'), schema=neutron_port.Port.extra_properties_schema, support_status=support.SupportStatus(version='6.0.0') ), NETWORK_SUBNET: properties.Schema( properties.Schema.STRING, _('Subnet in which to allocate the IP address for ' 'port. Used for creating port, based on derived ' 'properties. If subnet is specified, network ' 'property becomes optional.'), support_status=support.SupportStatus(version='5.0.0') ) }, ), update_allowed=True ), SCHEDULER_HINTS: properties.Schema( properties.Schema.MAP, _('Arbitrary key-value pairs specified by the client to help ' 'boot a server.') ), METADATA: properties.Schema( properties.Schema.MAP, _('Arbitrary key/value metadata to store for this server. Both ' 'keys and values must be 255 characters or less. Non-string ' 'values will be serialized to JSON (and the serialized ' 'string must be 255 characters or less).'), update_allowed=True ), USER_DATA_FORMAT: properties.Schema( properties.Schema.STRING, _('How the user_data should be formatted for the server. For ' 'HEAT_CFNTOOLS, the user_data is bundled as part of the ' 'heat-cfntools cloud-init boot configuration data. For RAW ' 'the user_data is passed to Nova unmodified. ' 'For SOFTWARE_CONFIG user_data is bundled as part of the ' 'software config data, and metadata is derived from any ' 'associated SoftwareDeployment resources.'), default=HEAT_CFNTOOLS, constraints=[ constraints.AllowedValues(_SOFTWARE_CONFIG_FORMATS), ] ), SOFTWARE_CONFIG_TRANSPORT: properties.Schema( properties.Schema.STRING, _('How the server should receive the metadata required for ' 'software configuration. POLL_SERVER_CFN will allow calls to ' 'the cfn API action DescribeStackResource authenticated with ' 'the provided keypair. POLL_SERVER_HEAT will allow calls to ' 'the Heat API resource-show using the provided keystone ' 'credentials. POLL_TEMP_URL will create and populate a ' 'Swift TempURL with metadata for polling. ZAQAR_MESSAGE will ' 'create a dedicated zaqar queue and post the metadata ' 'for polling.'), default=cfg.CONF.default_software_config_transport, constraints=[ constraints.AllowedValues(_SOFTWARE_CONFIG_TRANSPORTS), ] ), USER_DATA: properties.Schema( properties.Schema.STRING, _('User data script to be executed by cloud-init.'), default='' ), RESERVATION_ID: properties.Schema( properties.Schema.STRING, _('A UUID for the set of servers being requested.') ), CONFIG_DRIVE: properties.Schema( properties.Schema.BOOLEAN, _('If True, enable config drive on the server.') ), DISK_CONFIG: properties.Schema( properties.Schema.STRING, _('Control how the disk is partitioned when the server is ' 'created.'), constraints=[ constraints.AllowedValues(['AUTO', 'MANUAL']), ] ), PERSONALITY: properties.Schema( properties.Schema.MAP, _('A map of files to create/overwrite on the server upon boot. ' 'Keys are file names and values are the file contents.'), default={} ), ADMIN_PASS: properties.Schema( properties.Schema.STRING, _('The administrator password for the server.'), update_allowed=True ), } attributes_schema = { NAME_ATTR: attributes.Schema( _('Name of the server.'), type=attributes.Schema.STRING ), ADDRESSES: attributes.Schema( _('A dict of all network addresses with corresponding port_id. ' 'Each network will have two keys in dict, they are network ' 'name and network id. ' 'The port ID may be obtained through the following expression: ' '"{get_attr: [<server>, addresses, <network name_or_id>, 0, ' 'port]}".'), type=attributes.Schema.MAP ), NETWORKS_ATTR: attributes.Schema( _('A dict of assigned network addresses of the form: ' '{"public": [ip1, ip2...], "private": [ip3, ip4], ' '"public_uuid": [ip1, ip2...], "private_uuid": [ip3, ip4]}. ' 'Each network will have two keys in dict, they are network ' 'name and network id. '), type=attributes.Schema.MAP ), FIRST_ADDRESS: attributes.Schema( _('Convenience attribute to fetch the first assigned network ' 'address, or an empty string if nothing has been assigned at ' 'this time. Result may not be predictable if the server has ' 'addresses from more than one network.'), support_status=support.SupportStatus( status=support.HIDDEN, version='5.0.0', message=_('Use the networks attribute instead of ' 'first_address. For example: "{get_attr: ' '[<server name>, networks, <network name>, 0]}"'), previous_status=support.SupportStatus( status=support.DEPRECATED, version='2014.2', previous_status=support.SupportStatus(version='2013.2') ) ) ), INSTANCE_NAME: attributes.Schema( _('AWS compatible instance name.'), type=attributes.Schema.STRING ), ACCESSIPV4: attributes.Schema( _('The manually assigned alternative public IPv4 address ' 'of the server.'), type=attributes.Schema.STRING ), ACCESSIPV6: attributes.Schema( _('The manually assigned alternative public IPv6 address ' 'of the server.'), type=attributes.Schema.STRING ), CONSOLE_URLS: attributes.Schema( _("URLs of server's consoles. " "To get a specific console type, the requested type " "can be specified as parameter to the get_attr function, " "e.g. get_attr: [ <server>, console_urls, novnc ]. " "Currently supported types are " "novnc, xvpvnc, spice-html5, rdp-html5, serial."), support_status=support.SupportStatus(version='2015.1'), type=attributes.Schema.MAP ), } # Server host name limit to 53 characters by due to typical default # linux HOST_NAME_MAX of 64, minus the .novalocal appended to the name physical_resource_name_limit = 53 default_client_name = 'nova' entity = 'servers' def translation_rules(self): return [properties.TranslationRule( self.properties, properties.TranslationRule.REPLACE, source_path=[self.NETWORKS, self.NETWORK_ID], value_name=self.NETWORK_UUID)] def __init__(self, name, json_snippet, stack): super(Server, self).__init__(name, json_snippet, stack) if self.user_data_software_config(): self._register_access_key() def _server_name(self): name = self.properties[self.NAME] if name: return name return self.physical_resource_name() def _config_drive(self): # This method is overridden by the derived CloudServer resource return self.properties[self.CONFIG_DRIVE] def _populate_deployments_metadata(self, meta): meta['deployments'] = meta.get('deployments', []) meta['os-collect-config'] = meta.get('os-collect-config', {}) if self.transport_poll_server_heat(): meta['os-collect-config'].update({'heat': { 'user_id': self._get_user_id(), 'password': self.password, 'auth_url': self.context.auth_url, 'project_id': self.stack.stack_user_project_id, 'stack_id': self.stack.identifier().stack_path(), 'resource_name': self.name}}) if self.transport_zaqar_message(): queue_id = self.physical_resource_name() self.data_set('metadata_queue_id', queue_id) zaqar_plugin = self.client_plugin('zaqar') zaqar = zaqar_plugin.create_for_tenant( self.stack.stack_user_project_id) queue = zaqar.queue(queue_id) queue.post({'body': meta, 'ttl': zaqar_plugin.DEFAULT_TTL}) meta['os-collect-config'].update({'zaqar': { 'user_id': self._get_user_id(), 'password': self.password, 'auth_url': self.context.auth_url, 'project_id': self.stack.stack_user_project_id, 'queue_id': queue_id}}) elif self.transport_poll_server_cfn(): meta['os-collect-config'].update({'cfn': { 'metadata_url': '%s/v1/' % cfg.CONF.heat_metadata_server_url, 'access_key_id': self.access_key, 'secret_access_key': self.secret_key, 'stack_name': self.stack.name, 'path': '%s.Metadata' % self.name}}) elif self.transport_poll_temp_url(): container = self.physical_resource_name() object_name = str(uuid.uuid4()) self.client('swift').put_container(container) url = self.client_plugin('swift').get_temp_url( container, object_name, method='GET') put_url = self.client_plugin('swift').get_temp_url( container, object_name) self.data_set('metadata_put_url', put_url) self.data_set('metadata_object_name', object_name) meta['os-collect-config'].update({'request': { 'metadata_url': url}}) self.client('swift').put_object( container, object_name, jsonutils.dumps(meta)) self.metadata_set(meta) def _register_access_key(self): def access_allowed(resource_name): return resource_name == self.name if self.transport_poll_server_cfn(): self.stack.register_access_allowed_handler( self.access_key, access_allowed) elif self.transport_poll_server_heat(): self.stack.register_access_allowed_handler( self._get_user_id(), access_allowed) def _create_transport_credentials(self): if self.transport_poll_server_cfn(): self._create_user() self._create_keypair() elif (self.transport_poll_server_heat() or self.transport_zaqar_message()): self.password = uuid.uuid4().hex self._create_user() self._register_access_key() @property def access_key(self): return self.data().get('access_key') @property def secret_key(self): return self.data().get('secret_key') @property def password(self): return self.data().get('password') @password.setter def password(self, password): if password is None: self.data_delete('password') else: self.data_set('password', password, True) def user_data_raw(self): return self.properties[self.USER_DATA_FORMAT] == self.RAW def user_data_software_config(self): return self.properties[ self.USER_DATA_FORMAT] == self.SOFTWARE_CONFIG def transport_poll_server_cfn(self): return self.properties[ self.SOFTWARE_CONFIG_TRANSPORT] == self.POLL_SERVER_CFN def transport_poll_server_heat(self): return self.properties[ self.SOFTWARE_CONFIG_TRANSPORT] == self.POLL_SERVER_HEAT def transport_poll_temp_url(self): return self.properties[ self.SOFTWARE_CONFIG_TRANSPORT] == self.POLL_TEMP_URL def transport_zaqar_message(self): return self.properties.get( self.SOFTWARE_CONFIG_TRANSPORT) == self.ZAQAR_MESSAGE def get_software_config(self, ud_content): try: sc = self.rpc_client().show_software_config( self.context, ud_content) return sc[rpc_api.SOFTWARE_CONFIG_CONFIG] except Exception as ex: self.rpc_client().ignore_error_named(ex, 'NotFound') return ud_content def handle_create(self): security_groups = self.properties[self.SECURITY_GROUPS] user_data_format = self.properties[self.USER_DATA_FORMAT] ud_content = self.properties[self.USER_DATA] if self.user_data_software_config() or self.user_data_raw(): if uuidutils.is_uuid_like(ud_content): # attempt to load the userdata from software config ud_content = self.get_software_config(ud_content) metadata = self.metadata_get(True) or {} if self.user_data_software_config(): self._create_transport_credentials() self._populate_deployments_metadata(metadata) userdata = self.client_plugin().build_userdata( metadata, ud_content, instance_user=None, user_data_format=user_data_format) flavor = self.properties[self.FLAVOR] availability_zone = self.properties[self.AVAILABILITY_ZONE] image = self.properties[self.IMAGE] if image: image = self.client_plugin('glance').get_image_id(image) flavor_id = self.client_plugin().get_flavor_id(flavor) instance_meta = self.properties[self.METADATA] if instance_meta is not None: instance_meta = self.client_plugin().meta_serialize( instance_meta) scheduler_hints = self._scheduler_hints( self.properties[self.SCHEDULER_HINTS]) nics = self._build_nics(self.properties[self.NETWORKS]) block_device_mapping = self._build_block_device_mapping( self.properties[self.BLOCK_DEVICE_MAPPING]) block_device_mapping_v2 = self._build_block_device_mapping_v2( self.properties[self.BLOCK_DEVICE_MAPPING_V2]) reservation_id = self.properties[self.RESERVATION_ID] disk_config = self.properties[self.DISK_CONFIG] admin_pass = self.properties[self.ADMIN_PASS] or None personality_files = self.properties[self.PERSONALITY] key_name = self.properties[self.KEY_NAME] server = None try: server = self.client().servers.create( name=self._server_name(), image=image, flavor=flavor_id, key_name=key_name, security_groups=security_groups, userdata=userdata, meta=instance_meta, scheduler_hints=scheduler_hints, nics=nics, availability_zone=availability_zone, block_device_mapping=block_device_mapping, block_device_mapping_v2=block_device_mapping_v2, reservation_id=reservation_id, config_drive=self._config_drive(), disk_config=disk_config, files=personality_files, admin_pass=admin_pass) finally: # Avoid a race condition where the thread could be canceled # before the ID is stored if server is not None: self.resource_id_set(server.id) return server.id def check_create_complete(self, server_id): check = self.client_plugin()._check_active(server_id) if check: self.store_external_ports() return check def handle_check(self): server = self.client().servers.get(self.resource_id) status = self.client_plugin().get_status(server) checks = [{'attr': 'status', 'expected': 'ACTIVE', 'current': status}] self._verify_check_conditions(checks) @classmethod def _build_block_device_mapping(cls, bdm): if not bdm: return None bdm_dict = {} for mapping in bdm: mapping_parts = [] snapshot_id = mapping.get(cls.BLOCK_DEVICE_MAPPING_SNAPSHOT_ID) if snapshot_id: mapping_parts.append(snapshot_id) mapping_parts.append('snap') else: volume_id = mapping.get(cls.BLOCK_DEVICE_MAPPING_VOLUME_ID) mapping_parts.append(volume_id) mapping_parts.append('') volume_size = mapping.get(cls.BLOCK_DEVICE_MAPPING_VOLUME_SIZE) delete = mapping.get(cls.BLOCK_DEVICE_MAPPING_DELETE_ON_TERM) if volume_size: mapping_parts.append(str(volume_size)) else: mapping_parts.append('') if delete: mapping_parts.append(str(delete)) device_name = mapping.get(cls.BLOCK_DEVICE_MAPPING_DEVICE_NAME) bdm_dict[device_name] = ':'.join(mapping_parts) return bdm_dict @classmethod def _build_block_device_mapping_v2(cls, bdm_v2): if not bdm_v2: return None bdm_v2_list = [] for mapping in bdm_v2: bmd_dict = None if mapping.get(cls.BLOCK_DEVICE_MAPPING_VOLUME_ID): bmd_dict = { 'uuid': mapping.get(cls.BLOCK_DEVICE_MAPPING_VOLUME_ID), 'source_type': 'volume', 'destination_type': 'volume', 'boot_index': 0, 'delete_on_termination': False, } elif mapping.get(cls.BLOCK_DEVICE_MAPPING_SNAPSHOT_ID): bmd_dict = { 'uuid': mapping.get(cls.BLOCK_DEVICE_MAPPING_SNAPSHOT_ID), 'source_type': 'snapshot', 'destination_type': 'volume', 'boot_index': 0, 'delete_on_termination': False, } elif mapping.get(cls.BLOCK_DEVICE_MAPPING_IMAGE_ID): bmd_dict = { 'uuid': mapping.get(cls.BLOCK_DEVICE_MAPPING_IMAGE_ID), 'source_type': 'image', 'destination_type': 'volume', 'boot_index': 0, 'delete_on_termination': False, } elif mapping.get(cls.BLOCK_DEVICE_MAPPING_SWAP_SIZE): bmd_dict = { 'source_type': 'blank', 'destination_type': 'local', 'boot_index': -1, 'delete_on_termination': True, 'guest_format': 'swap', 'volume_size': mapping.get( cls.BLOCK_DEVICE_MAPPING_SWAP_SIZE), } # NOTE(prazumovsky): In case of server doesn't take empty value of device_name = mapping.get(cls.BLOCK_DEVICE_MAPPING_DEVICE_NAME) if device_name: bmd_dict[cls.BLOCK_DEVICE_MAPPING_DEVICE_NAME] = device_name update_props = (cls.BLOCK_DEVICE_MAPPING_DEVICE_TYPE, cls.BLOCK_DEVICE_MAPPING_DISK_BUS, cls.BLOCK_DEVICE_MAPPING_BOOT_INDEX, cls.BLOCK_DEVICE_MAPPING_VOLUME_SIZE, cls.BLOCK_DEVICE_MAPPING_DELETE_ON_TERM) for update_prop in update_props: if mapping.get(update_prop) is not None: bmd_dict[update_prop] = mapping.get(update_prop) if bmd_dict: bdm_v2_list.append(bmd_dict) return bdm_v2_list def _add_port_for_address(self, server): nets = copy.deepcopy(server.addresses) ifaces = server.interface_list() ip_mac_mapping_on_port_id = dict(((iface.fixed_ips[0]['ip_address'], iface.mac_addr), iface.port_id) for iface in ifaces) for net_name in nets: for addr in nets[net_name]: addr['port'] = ip_mac_mapping_on_port_id.get( (addr['addr'], addr['OS-EXT-IPS-MAC:mac_addr'])) return self._extend_networks(nets) def _extend_networks(self, networks): nets = copy.deepcopy(networks) for key in list(nets.keys()): try: net_id = self.client_plugin().get_net_id_by_label(key) except (exception.NovaNetworkNotFound, exception.PhysicalResourceNameAmbiguity): net_id = None if net_id: nets[net_id] = nets[key] return nets def _resolve_attribute(self, name): if name == self.FIRST_ADDRESS: return self.client_plugin().server_to_ipaddress( self.resource_id) or '' if name == self.NAME_ATTR: return self._server_name() try: server = self.client().servers.get(self.resource_id) except Exception as e: self.client_plugin().ignore_not_found(e) return '' if name == self.ADDRESSES: return self._add_port_for_address(server) if name == self.NETWORKS_ATTR: return self._extend_networks(server.networks) if name == self.INSTANCE_NAME: return getattr(server, 'OS-EXT-SRV-ATTR:instance_name', None) if name == self.ACCESSIPV4: return server.accessIPv4 if name == self.ACCESSIPV6: return server.accessIPv6 if name == self.CONSOLE_URLS: return self.client_plugin('nova').get_console_urls(server) def add_dependencies(self, deps): super(Server, self).add_dependencies(deps) nets = self.properties[self.NETWORKS] if not nets: return for res in six.itervalues(self.stack): if res.has_interface('OS::Neutron::Subnet'): subnet_net = (res.properties.get(subnet.Subnet.NETWORK_ID) or res.properties.get(subnet.Subnet.NETWORK)) for net in nets: net_id = (net.get(self.NETWORK_ID) or net.get(self.NETWORK_UUID)) if net_id and net_id == subnet_net: deps += (self, res) break def _update_flavor(self, prop_diff): flavor = prop_diff[self.FLAVOR] flavor_id = self.client_plugin().get_flavor_id(flavor) handler_args = {'args': (flavor_id,)} checker_args = {'args': (flavor_id, flavor)} prg_resize = progress.ServerUpdateProgress(self.resource_id, 'resize', handler_extra=handler_args, checker_extra=checker_args) prg_verify = progress.ServerUpdateProgress(self.resource_id, 'verify_resize') return prg_resize, prg_verify def _update_image(self, prop_diff): image_update_policy = ( prop_diff.get(self.IMAGE_UPDATE_POLICY) or self.properties[self.IMAGE_UPDATE_POLICY]) image = prop_diff[self.IMAGE] image_id = self.client_plugin('glance').get_image_id(image) preserve_ephemeral = ( image_update_policy == 'REBUILD_PRESERVE_EPHEMERAL') password = (prop_diff.get(self.ADMIN_PASS) or self.properties[self.ADMIN_PASS]) kwargs = {'password': password, 'preserve_ephemeral': preserve_ephemeral} prg = progress.ServerUpdateProgress(self.resource_id, 'rebuild', handler_extra={'args': (image_id,), 'kwargs': kwargs}) return prg def _update_networks(self, server, prop_diff): updaters = [] new_networks = prop_diff.get(self.NETWORKS) old_networks = self.properties[self.NETWORKS] if not server: server = self.client().servers.get(self.resource_id) interfaces = server.interface_list() remove_ports, add_nets = self.calculate_networks( old_networks, new_networks, interfaces) for port in remove_ports: updaters.append( progress.ServerUpdateProgress( self.resource_id, 'interface_detach', complete=True, handler_extra={'args': (port,)}) ) for args in add_nets: updaters.append( progress.ServerUpdateProgress( self.resource_id, 'interface_attach', complete=True, handler_extra={'kwargs': args}) ) return updaters def _needs_update(self, after, before, after_props, before_props, prev_resource, check_init_complete=True): result = super(Server, self)._needs_update( after, before, after_props, before_props, prev_resource, check_init_complete=check_init_complete) prop_diff = self.update_template_diff_properties(after_props, before_props) if self.FLAVOR in prop_diff: flavor_update_policy = ( prop_diff.get(self.FLAVOR_UPDATE_POLICY) or self.properties[self.FLAVOR_UPDATE_POLICY]) if flavor_update_policy == 'REPLACE': raise exception.UpdateReplace(self.name) if self.IMAGE in prop_diff: image_update_policy = ( prop_diff.get(self.IMAGE_UPDATE_POLICY) or self.properties[self.IMAGE_UPDATE_POLICY]) if image_update_policy == 'REPLACE': raise exception.UpdateReplace(self.name) return result def handle_update(self, json_snippet, tmpl_diff, prop_diff): if 'Metadata' in tmpl_diff: if self.user_data_software_config(): metadata = self.metadata_get(True) or {} new_occ_md = tmpl_diff['Metadata'].get('os-collect-config', {}) occ_md = metadata.get('os-collect-config', {}) occ_md.update(new_occ_md) tmpl_diff['Metadata']['os-collect-config'] = occ_md deployment_md = metadata.get('deployments', []) tmpl_diff['Metadata']['deployments'] = deployment_md self.metadata_set(tmpl_diff['Metadata']) updaters = [] server = None if self.METADATA in prop_diff: server = self.client().servers.get(self.resource_id) self.client_plugin().meta_update(server, prop_diff[self.METADATA]) if self.FLAVOR in prop_diff: updaters.extend(self._update_flavor(prop_diff)) if self.IMAGE in prop_diff: updaters.append(self._update_image(prop_diff)) elif self.ADMIN_PASS in prop_diff: if not server: server = self.client().servers.get(self.resource_id) server.change_password(prop_diff[self.ADMIN_PASS]) if self.NAME in prop_diff: if not server: server = self.client().servers.get(self.resource_id) self.client_plugin().rename(server, prop_diff[self.NAME]) if self.NETWORKS in prop_diff: updaters.extend(self._update_networks(server, prop_diff)) # have called several APIs return updaters def check_update_complete(self, updaters): for prg in updaters: if not prg.called: handler = getattr(self.client_plugin(), prg.handler) prg.called = handler(*prg.handler_args, **prg.handler_kwargs) return False if not prg.complete: check_complete = getattr(self.client_plugin(), prg.checker) prg.complete = check_complete(*prg.checker_args, **prg.checker_kwargs) break status = all(prg.complete for prg in updaters) if status: self.store_external_ports() return status def metadata_update(self, new_metadata=None): if new_metadata is None: # Re-resolve the template metadata and merge it with the # current resource metadata. This is necessary because the # attributes referenced in the template metadata may change # and the resource itself adds keys to the metadata which # are not specified in the template (e.g the deployments data) meta = self.metadata_get(refresh=True) or {} tmpl_meta = self.t.metadata() meta.update(tmpl_meta) self.metadata_set(meta) @staticmethod def _check_maximum(count, maximum, msg): if maximum != -1 and count > maximum: raise exception.StackValidationFailed(message=msg) def _validate_block_device_mapping(self): # either volume_id or snapshot_id needs to be specified, but not both # for block device mapping. bdm = self.properties[self.BLOCK_DEVICE_MAPPING] or [] bootable_vol = False for mapping in bdm: device_name = mapping[self.BLOCK_DEVICE_MAPPING_DEVICE_NAME] if device_name == 'vda': bootable_vol = True volume_id = mapping.get(self.BLOCK_DEVICE_MAPPING_VOLUME_ID) snapshot_id = mapping.get(self.BLOCK_DEVICE_MAPPING_SNAPSHOT_ID) if volume_id is not None and snapshot_id is not None: raise exception.ResourcePropertyConflict( self.BLOCK_DEVICE_MAPPING_VOLUME_ID, self.BLOCK_DEVICE_MAPPING_SNAPSHOT_ID) if volume_id is None and snapshot_id is None: msg = _('Either volume_id or snapshot_id must be specified for' ' device mapping %s') % device_name raise exception.StackValidationFailed(message=msg) bdm_v2 = self.properties[self.BLOCK_DEVICE_MAPPING_V2] or [] if bdm and bdm_v2: raise exception.ResourcePropertyConflict( self.BLOCK_DEVICE_MAPPING, self.BLOCK_DEVICE_MAPPING_V2) for mapping in bdm_v2: volume_id = mapping.get(self.BLOCK_DEVICE_MAPPING_VOLUME_ID) snapshot_id = mapping.get(self.BLOCK_DEVICE_MAPPING_SNAPSHOT_ID) image_id = mapping.get(self.BLOCK_DEVICE_MAPPING_IMAGE_ID) swap_size = mapping.get(self.BLOCK_DEVICE_MAPPING_SWAP_SIZE) property_tuple = (volume_id, snapshot_id, image_id, swap_size) if property_tuple.count(None) < 3: raise exception.ResourcePropertyConflict( self.BLOCK_DEVICE_MAPPING_VOLUME_ID, self.BLOCK_DEVICE_MAPPING_SNAPSHOT_ID, self.BLOCK_DEVICE_MAPPING_IMAGE_ID, self.BLOCK_DEVICE_MAPPING_SWAP_SIZE) if property_tuple.count(None) == 4: msg = _('Either volume_id, snapshot_id, image_id or ' 'swap_size must be specified.') raise exception.StackValidationFailed(message=msg) if any((volume_id, snapshot_id, image_id)): bootable_vol = True return bootable_vol def validate(self): super(Server, self).validate() if self.user_data_software_config(): if 'deployments' in self.t.metadata(): msg = _('deployments key not allowed in resource metadata ' 'with user_data_format of SOFTWARE_CONFIG') raise exception.StackValidationFailed(message=msg) bootable_vol = self._validate_block_device_mapping() # make sure the image exists if specified. image = self.properties[self.IMAGE] if not image and not bootable_vol: msg = _('Neither image nor bootable volume is specified for' ' instance %s') % self.name raise exception.StackValidationFailed(message=msg) # network properties 'uuid' and 'network' shouldn't be used networks = self.properties[self.NETWORKS] or [] networks_with_port = False for network in networks: networks_with_port = (networks_with_port or network.get(self.NETWORK_PORT)) self._validate_network(network) metadata = self.properties[self.METADATA] personality = self.properties[self.PERSONALITY] if metadata is not None or personality: limits = self.client_plugin().absolute_limits() # if 'security_groups' present for the server and explict 'port' # in one or more entries in 'networks', raise validation error if networks_with_port and self.properties[self.SECURITY_GROUPS]: raise exception.ResourcePropertyConflict( self.SECURITY_GROUPS, "/".join([self.NETWORKS, self.NETWORK_PORT])) # verify that the number of metadata entries is not greater # than the maximum number allowed in the provider's absolute if metadata is not None: msg = _('Instance metadata must not contain greater than %s ' 'entries. This is the maximum number allowed by your ' 'service provider') % limits['maxServerMeta'] self._check_maximum(len(metadata), limits['maxServerMeta'], msg) if personality: msg = _("The personality property may not contain " "greater than %s entries.") % limits['maxPersonality'] self._check_maximum(len(personality), limits['maxPersonality'], msg) for path, contents in personality.items(): msg = (_("The contents of personality file \"%(path)s\" " "is larger than the maximum allowed personality " "file size (%(max_size)s bytes).") % {'path': path, 'max_size': limits['maxPersonalitySize']}) self._check_maximum(len(bytes(contents.encode('utf-8'))), limits['maxPersonalitySize'], msg) def _delete_temp_url(self): object_name = self.data().get('metadata_object_name') if not object_name: return try: container = self.physical_resource_name() swift = self.client('swift') swift.delete_object(container, object_name) headers = swift.head_container(container) if int(headers['x-container-object-count']) == 0: swift.delete_container(container) except Exception as ex: self.client_plugin('swift').ignore_not_found(ex) def _delete_queue(self): queue_id = self.data().get('metadata_queue_id') if not queue_id: return client_plugin = self.client_plugin('zaqar') zaqar = client_plugin.create_for_tenant( self.stack.stack_user_project_id) try: zaqar.queue(queue_id).delete() except Exception as ex: client_plugin.ignore_not_found(ex) self.data_delete('metadata_queue_id') def handle_snapshot_delete(self, state): if state[0] != self.FAILED: image_id = self.client().servers.create_image( self.resource_id, self.physical_resource_name()) return progress.ServerDeleteProgress( self.resource_id, image_id, False) return self.handle_delete() def handle_delete(self): if self.resource_id is None: return if self.user_data_software_config(): self._delete_user() self._delete_temp_url() self._delete_queue() # remove internal and external ports self._delete_internal_ports() self.data_delete('external_ports') try: self.client().servers.delete(self.resource_id) except Exception as e: self.client_plugin().ignore_not_found(e) return return progress.ServerDeleteProgress(self.resource_id) def check_delete_complete(self, prg): if not prg: return True if not prg.image_complete: image = self.client().images.get(prg.image_id) if image.status in ('DELETED', 'ERROR'): raise exception.Error(image.status) elif image.status == 'ACTIVE': prg.image_complete = True if not self.handle_delete(): return True return False return self.client_plugin().check_delete_server_complete( prg.server_id) def handle_suspend(self): if self.resource_id is None: raise exception.Error(_('Cannot suspend %s, resource_id not set') % self.name) try: server = self.client().servers.get(self.resource_id) except Exception as e: if self.client_plugin().is_not_found(e): raise exception.NotFound(_('Failed to find server %s') % self.resource_id) else: raise else: # if the server has been suspended successful, # no need to suspend again if self.client_plugin().get_status(server) != 'SUSPENDED': LOG.debug('suspending server %s' % self.resource_id) server.suspend() return server.id def check_suspend_complete(self, server_id): cp = self.client_plugin() server = cp.fetch_server(server_id) if not server: return False status = cp.get_status(server) LOG.debug('%(name)s check_suspend_complete status = %(status)s' % {'name': self.name, 'status': status}) if status in list(cp.deferred_server_statuses + ['ACTIVE']): return status == 'SUSPENDED' else: exc = exception.ResourceUnknownStatus( result=_('Suspend of server %s failed') % server.name, resource_status=status) raise exc def handle_resume(self): if self.resource_id is None: raise exception.Error(_('Cannot resume %s, resource_id not set') % self.name) try: server = self.client().servers.get(self.resource_id) except Exception as e: if self.client_plugin().is_not_found(e): raise exception.NotFound(_('Failed to find server %s') % self.resource_id) else: raise else: # if the server has been resumed successful, # no need to resume again if self.client_plugin().get_status(server) != 'ACTIVE': LOG.debug('resuming server %s' % self.resource_id) server.resume() return server.id def check_resume_complete(self, server_id): return self.client_plugin()._check_active(server_id) def handle_snapshot(self): image_id = self.client().servers.create_image( self.resource_id, self.physical_resource_name()) self.data_set('snapshot_image_id', image_id) return image_id def check_snapshot_complete(self, image_id): image = self.client().images.get(image_id) if image.status == 'ACTIVE': return True elif image.status == 'ERROR' or image.status == 'DELETED': raise exception.Error(image.status) return False def handle_delete_snapshot(self, snapshot): image_id = snapshot['resource_data'].get('snapshot_image_id') try: self.client().images.delete(image_id) except Exception as e: self.client_plugin().ignore_not_found(e) def handle_restore(self, defn, restore_data): image_id = restore_data['resource_data']['snapshot_image_id'] props = function.resolve(self.properties.data) props[self.IMAGE] = image_id return defn.freeze(properties=props) def prepare_for_replace(self): self.prepare_ports_for_replace() def restore_prev_rsrc(self, convergence=False): self.restore_ports_after_rollback(convergence=convergence) def resource_mapping(): return { 'OS::Nova::Server': Server, }
true
true
f72c9842321b24921292819e0294421b24b2f549
3,305
py
Python
src/draw.py
lRomul/argus-bengali-ai
e64374230f5390a17305769126ff4bfc9a2a8644
[ "MIT" ]
2
2020-05-08T09:25:38.000Z
2020-10-04T16:15:29.000Z
src/draw.py
lRomul/argus-bengali-ai
e64374230f5390a17305769126ff4bfc9a2a8644
[ "MIT" ]
2
2022-01-13T03:19:24.000Z
2022-03-12T00:48:13.000Z
src/draw.py
lRomul/argus-bengali-ai
e64374230f5390a17305769126ff4bfc9a2a8644
[ "MIT" ]
null
null
null
import time import random import numpy as np from pathlib import Path from PIL import Image, ImageDraw, ImageFont, ImageFilter import torch from torch.utils.data import Dataset from src import config def draw_grapheme(grapheme, font_path, size=(137, 236)): height, width = size image = Image.new('RGB', (width, height)) draw = ImageDraw.Draw(image) font_size = np.random.randint(70, 110) font = ImageFont.truetype(str(font_path), font_size) w, h = draw.textsize(grapheme, font=font) width_ratio = np.random.uniform(1.5, 2.5) height_ratio = np.random.uniform(2.5, 3.5) fill = np.random.randint(200, 255) draw.text(((width - w) / width_ratio, (height - h) / height_ratio), grapheme, font=font, fill=fill) image = image.filter(ImageFilter.BLUR) return np.array(image)[:, :, 0] def get_draw_data(): graphemes = [] for grapheme_root_idx, grapheme_root in config.class_map['grapheme_root'].items(): for vowel_diacritic_idx, vowel_diacritic in config.class_map['vowel_diacritic'].items(): for consonant_diacritic_idx, consonant_diacritic in config.class_map['consonant_diacritic'].items(): consonant_diacritic, grapheme_root, vowel_diacritic = [c if c != '0' else '' for c in [consonant_diacritic, grapheme_root, vowel_diacritic]] grapheme = consonant_diacritic + grapheme_root + vowel_diacritic graphemes.append({ 'grapheme': grapheme, 'grapheme_root': grapheme_root_idx, 'vowel_diacritic': vowel_diacritic_idx, 'consonant_diacritic': consonant_diacritic_idx }) return graphemes class BengaliDrawDataset(Dataset): def __init__(self, fonts_dir, transform=None, mixer=None): self.fonts_dir = fonts_dir self.transform = transform self.mixer = mixer self.data = get_draw_data() self.font_paths = sorted(Path(fonts_dir).glob('*.ttf')) def __len__(self): return len(self.data) def get_sample(self, idx): sample = self.data[idx] font_path = np.random.choice(self.font_paths) image = draw_grapheme(sample['grapheme'], font_path, size=config.raw_image_shape) grapheme = torch.tensor(sample['grapheme_root'], dtype=torch.int64) vowel = torch.tensor(sample['vowel_diacritic'], dtype=torch.int64) consonant = torch.tensor(sample['consonant_diacritic'], dtype=torch.int64) target = grapheme, vowel, consonant return image, target def _set_random_seed(self, idx): seed = int(time.time() * 1000.0) + idx random.seed(seed) np.random.seed(seed % (2**32 - 1)) @torch.no_grad() def __getitem__(self, idx): self._set_random_seed(idx) image, target = self.get_sample(idx) if self.mixer is not None: image, target = self.mixer(self, image, target) if self.transform is not None: image = self.transform(image) return image, target
36.318681
112
0.607867
import time import random import numpy as np from pathlib import Path from PIL import Image, ImageDraw, ImageFont, ImageFilter import torch from torch.utils.data import Dataset from src import config def draw_grapheme(grapheme, font_path, size=(137, 236)): height, width = size image = Image.new('RGB', (width, height)) draw = ImageDraw.Draw(image) font_size = np.random.randint(70, 110) font = ImageFont.truetype(str(font_path), font_size) w, h = draw.textsize(grapheme, font=font) width_ratio = np.random.uniform(1.5, 2.5) height_ratio = np.random.uniform(2.5, 3.5) fill = np.random.randint(200, 255) draw.text(((width - w) / width_ratio, (height - h) / height_ratio), grapheme, font=font, fill=fill) image = image.filter(ImageFilter.BLUR) return np.array(image)[:, :, 0] def get_draw_data(): graphemes = [] for grapheme_root_idx, grapheme_root in config.class_map['grapheme_root'].items(): for vowel_diacritic_idx, vowel_diacritic in config.class_map['vowel_diacritic'].items(): for consonant_diacritic_idx, consonant_diacritic in config.class_map['consonant_diacritic'].items(): consonant_diacritic, grapheme_root, vowel_diacritic = [c if c != '0' else '' for c in [consonant_diacritic, grapheme_root, vowel_diacritic]] grapheme = consonant_diacritic + grapheme_root + vowel_diacritic graphemes.append({ 'grapheme': grapheme, 'grapheme_root': grapheme_root_idx, 'vowel_diacritic': vowel_diacritic_idx, 'consonant_diacritic': consonant_diacritic_idx }) return graphemes class BengaliDrawDataset(Dataset): def __init__(self, fonts_dir, transform=None, mixer=None): self.fonts_dir = fonts_dir self.transform = transform self.mixer = mixer self.data = get_draw_data() self.font_paths = sorted(Path(fonts_dir).glob('*.ttf')) def __len__(self): return len(self.data) def get_sample(self, idx): sample = self.data[idx] font_path = np.random.choice(self.font_paths) image = draw_grapheme(sample['grapheme'], font_path, size=config.raw_image_shape) grapheme = torch.tensor(sample['grapheme_root'], dtype=torch.int64) vowel = torch.tensor(sample['vowel_diacritic'], dtype=torch.int64) consonant = torch.tensor(sample['consonant_diacritic'], dtype=torch.int64) target = grapheme, vowel, consonant return image, target def _set_random_seed(self, idx): seed = int(time.time() * 1000.0) + idx random.seed(seed) np.random.seed(seed % (2**32 - 1)) @torch.no_grad() def __getitem__(self, idx): self._set_random_seed(idx) image, target = self.get_sample(idx) if self.mixer is not None: image, target = self.mixer(self, image, target) if self.transform is not None: image = self.transform(image) return image, target
true
true
f72c98f625fd6ff9df578e247df919138a312028
1,260
py
Python
selectionsort.py
maxProgrammer/Entendendo_Algoritmos
8bc6ef9b7869150ef624333490b68d94b197cb75
[ "MIT" ]
null
null
null
selectionsort.py
maxProgrammer/Entendendo_Algoritmos
8bc6ef9b7869150ef624333490b68d94b197cb75
[ "MIT" ]
null
null
null
selectionsort.py
maxProgrammer/Entendendo_Algoritmos
8bc6ef9b7869150ef624333490b68d94b197cb75
[ "MIT" ]
null
null
null
#algoritmo utilizado para ordenação de uma lista. #a cada execução ele percorre toda lista e coloca o menor na posição (n-1) def encontraMenor(lista): #armazena o valor do indice 0 a variavel menorValor = lista[0] #considera que index zero tem o menor valor menorIndex = 0 #percorre lista do indice 1 ao ultimo for i in range(1,len(lista) - 1): #compra se lista[i] é menor que menor valor e #se verdadeiro atualiza menorValor e menorIndex if lista[i] < menorValor: menorValor = lista[i] menorIndex = i #retorna o index do menor valor encontrado return menorIndex #funcao que utiliza a funcaencontra menor #para gerar outra lista ordenada def ordenaSelecao(lista): #lista que receberá itens ordenados ordLista = [] #percorre todos elementos da lista for x in range(len(lista)): # a cada iteracao encontra menor item e o insere # na nova lista. Funcao pop armazena o item na nova lista # e apaga na antiga ao mesmo tempo. menor = encontraMenor(lista) ordLista.append(lista.pop(menor)) #retorna nova lista ordenada return ordLista #teste programa lista = [3,1,13,5,0,100] print(ordenaSelecao(lista))
28
74
0.674603
def encontraMenor(lista): menorValor = lista[0] menorIndex = 0 for i in range(1,len(lista) - 1): if lista[i] < menorValor: menorValor = lista[i] menorIndex = i return menorIndex def ordenaSelecao(lista): ordLista = [] for x in range(len(lista)): menor = encontraMenor(lista) ordLista.append(lista.pop(menor)) return ordLista lista = [3,1,13,5,0,100] print(ordenaSelecao(lista))
true
true
f72c99bc69fba8eb8ab5186eeff081f18b9e24a7
3,124
py
Python
src/dataset_prepare.py
dd-dos/Emotion-detection
23eb94cbceb70890cf6b0f63e84d80eae7336c85
[ "MIT" ]
null
null
null
src/dataset_prepare.py
dd-dos/Emotion-detection
23eb94cbceb70890cf6b0f63e84d80eae7336c85
[ "MIT" ]
null
null
null
src/dataset_prepare.py
dd-dos/Emotion-detection
23eb94cbceb70890cf6b0f63e84d80eae7336c85
[ "MIT" ]
null
null
null
import numpy as np import pandas as pd from PIL import Image from tqdm import tqdm import os # convert string to integer def atoi(s): n = 0 for i in s: n = n*10 + ord(i) - ord("0") return n # making folders outer_names = ['test','train'] inner_names = ['angry', 'disgusted', 'fearful', 'happy', 'sad', 'surprised', 'neutral'] os.makedirs('data', exist_ok=True) for outer_name in outer_names: os.makedirs(os.path.join('data',outer_name), exist_ok=True) for inner_name in inner_names: os.makedirs(os.path.join('data',outer_name,inner_name), exist_ok=True) # to keep count of each category angry = 0 disgusted = 0 fearful = 0 happy = 0 sad = 0 surprised = 0 neutral = 0 angry_test = 0 disgusted_test = 0 fearful_test = 0 happy_test = 0 sad_test = 0 surprised_test = 0 neutral_test = 0 df = pd.read_csv('./fer2013.csv') mat = np.zeros((48,48),dtype=np.uint8) print("Saving images...") # read the csv file line by line for i in tqdm(range(len(df))): txt = df['pixels'][i] words = txt.split() # the image size is 48x48 for j in range(2304): xind = j // 48 yind = j % 48 mat[xind][yind] = atoi(words[j]) img = Image.fromarray(mat) # train if i < 28709: if df['emotion'][i] == 0: img.save('./data/train/angry/im'+str(angry)+'.png') angry += 1 elif df['emotion'][i] == 1: img.save('./data/train/disgusted/im'+str(disgusted)+'.png') disgusted += 1 elif df['emotion'][i] == 2: img.save('./data/train/fearful/im'+str(fearful)+'.png') fearful += 1 elif df['emotion'][i] == 3: img.save('./data/train/happy/im'+str(happy)+'.png') happy += 1 elif df['emotion'][i] == 4: img.save('./data/train/sad/im'+str(sad)+'.png') sad += 1 elif df['emotion'][i] == 5: img.save('./data/train/surprised/im'+str(surprised)+'.png') surprised += 1 elif df['emotion'][i] == 6: img.save('./data/train/neutral/im'+str(neutral)+'.png') neutral += 1 # test else: if df['emotion'][i] == 0: img.save('./data/test/angry/im'+str(angry_test)+'.png') angry_test += 1 elif df['emotion'][i] == 1: img.save('./data/test/disgusted/im'+str(disgusted_test)+'.png') disgusted_test += 1 elif df['emotion'][i] == 2: img.save('./data/test/fearful/im'+str(fearful_test)+'.png') fearful_test += 1 elif df['emotion'][i] == 3: img.save('./data/test/happy/im'+str(happy_test)+'.png') happy_test += 1 elif df['emotion'][i] == 4: img.save('./data/test/sad/im'+str(sad_test)+'.png') sad_test += 1 elif df['emotion'][i] == 5: img.save('./data/test/surprised/im'+str(surprised_test)+'.png') surprised_test += 1 elif df['emotion'][i] == 6: img.save('./data/test/neutral/im'+str(neutral_test)+'.png') neutral_test += 1 print("Done!")
30.330097
87
0.546735
import numpy as np import pandas as pd from PIL import Image from tqdm import tqdm import os def atoi(s): n = 0 for i in s: n = n*10 + ord(i) - ord("0") return n outer_names = ['test','train'] inner_names = ['angry', 'disgusted', 'fearful', 'happy', 'sad', 'surprised', 'neutral'] os.makedirs('data', exist_ok=True) for outer_name in outer_names: os.makedirs(os.path.join('data',outer_name), exist_ok=True) for inner_name in inner_names: os.makedirs(os.path.join('data',outer_name,inner_name), exist_ok=True) angry = 0 disgusted = 0 fearful = 0 happy = 0 sad = 0 surprised = 0 neutral = 0 angry_test = 0 disgusted_test = 0 fearful_test = 0 happy_test = 0 sad_test = 0 surprised_test = 0 neutral_test = 0 df = pd.read_csv('./fer2013.csv') mat = np.zeros((48,48),dtype=np.uint8) print("Saving images...") for i in tqdm(range(len(df))): txt = df['pixels'][i] words = txt.split() for j in range(2304): xind = j // 48 yind = j % 48 mat[xind][yind] = atoi(words[j]) img = Image.fromarray(mat) if i < 28709: if df['emotion'][i] == 0: img.save('./data/train/angry/im'+str(angry)+'.png') angry += 1 elif df['emotion'][i] == 1: img.save('./data/train/disgusted/im'+str(disgusted)+'.png') disgusted += 1 elif df['emotion'][i] == 2: img.save('./data/train/fearful/im'+str(fearful)+'.png') fearful += 1 elif df['emotion'][i] == 3: img.save('./data/train/happy/im'+str(happy)+'.png') happy += 1 elif df['emotion'][i] == 4: img.save('./data/train/sad/im'+str(sad)+'.png') sad += 1 elif df['emotion'][i] == 5: img.save('./data/train/surprised/im'+str(surprised)+'.png') surprised += 1 elif df['emotion'][i] == 6: img.save('./data/train/neutral/im'+str(neutral)+'.png') neutral += 1 else: if df['emotion'][i] == 0: img.save('./data/test/angry/im'+str(angry_test)+'.png') angry_test += 1 elif df['emotion'][i] == 1: img.save('./data/test/disgusted/im'+str(disgusted_test)+'.png') disgusted_test += 1 elif df['emotion'][i] == 2: img.save('./data/test/fearful/im'+str(fearful_test)+'.png') fearful_test += 1 elif df['emotion'][i] == 3: img.save('./data/test/happy/im'+str(happy_test)+'.png') happy_test += 1 elif df['emotion'][i] == 4: img.save('./data/test/sad/im'+str(sad_test)+'.png') sad_test += 1 elif df['emotion'][i] == 5: img.save('./data/test/surprised/im'+str(surprised_test)+'.png') surprised_test += 1 elif df['emotion'][i] == 6: img.save('./data/test/neutral/im'+str(neutral_test)+'.png') neutral_test += 1 print("Done!")
true
true
f72c9a79f61fe1255118ac76e5e76311780f9ee8
1,612
py
Python
demos/grouped_mr_heart/demo_predict.py
mathpluscode/DeepReg
80854094feafec998fa6237199066556c73f31f9
[ "Apache-2.0" ]
null
null
null
demos/grouped_mr_heart/demo_predict.py
mathpluscode/DeepReg
80854094feafec998fa6237199066556c73f31f9
[ "Apache-2.0" ]
null
null
null
demos/grouped_mr_heart/demo_predict.py
mathpluscode/DeepReg
80854094feafec998fa6237199066556c73f31f9
[ "Apache-2.0" ]
null
null
null
import argparse from datetime import datetime from deepreg.predict import predict name = "grouped_mr_heart" # parser is used to simplify testing, by default it is not used # please run the script with --no-test flag to ensure non-testing mode # for instance: # python script.py --no-test parser = argparse.ArgumentParser() parser.add_argument( "--test", help="Execute the script for test purpose", dest="test", action="store_true", ) parser.add_argument( "--no-test", help="Execute the script for non-test purpose", dest="test", action="store_false", ) parser.set_defaults(test=False) args = parser.parse_args() print( "\n\n\n\n\n" "=========================================================\n" "The prediction can also be launched using the following command.\n" "deepreg_predict --gpu '' " f"--config_path demos/{name}/{name}.yaml " f"--ckpt_path demos/{name}/dataset/pretrained/ckpt-4000 " f"--log_root demos/{name} " "--log_dir logs_predict " "--save_png --mode test\n" "=========================================================\n" "\n\n\n\n\n" ) log_root = f"demos/{name}" log_dir = "logs_predict/" + datetime.now().strftime("%Y%m%d-%H%M%S") ckpt_path = f"{log_root}/dataset/pretrained/ckpt-4000" config_path = [f"{log_root}/{name}.yaml"] if args.test: config_path.append("config/test/demo_unpaired_grouped.yaml") predict( gpu="0", gpu_allow_growth=True, ckpt_path=ckpt_path, mode="test", batch_size=1, log_root=log_root, log_dir=log_dir, sample_label="all", config_path=config_path, )
26.866667
72
0.628412
import argparse from datetime import datetime from deepreg.predict import predict name = "grouped_mr_heart" parser = argparse.ArgumentParser() parser.add_argument( "--test", help="Execute the script for test purpose", dest="test", action="store_true", ) parser.add_argument( "--no-test", help="Execute the script for non-test purpose", dest="test", action="store_false", ) parser.set_defaults(test=False) args = parser.parse_args() print( "\n\n\n\n\n" "=========================================================\n" "The prediction can also be launched using the following command.\n" "deepreg_predict --gpu '' " f"--config_path demos/{name}/{name}.yaml " f"--ckpt_path demos/{name}/dataset/pretrained/ckpt-4000 " f"--log_root demos/{name} " "--log_dir logs_predict " "--save_png --mode test\n" "=========================================================\n" "\n\n\n\n\n" ) log_root = f"demos/{name}" log_dir = "logs_predict/" + datetime.now().strftime("%Y%m%d-%H%M%S") ckpt_path = f"{log_root}/dataset/pretrained/ckpt-4000" config_path = [f"{log_root}/{name}.yaml"] if args.test: config_path.append("config/test/demo_unpaired_grouped.yaml") predict( gpu="0", gpu_allow_growth=True, ckpt_path=ckpt_path, mode="test", batch_size=1, log_root=log_root, log_dir=log_dir, sample_label="all", config_path=config_path, )
true
true
f72c9cd27adbff3953b5021bda4fe373f564264d
2,110
py
Python
core/helper/config.py
caostorm/smng
f1cff4010a0645ae8e1182cd3c961d97cecf4a6e
[ "MIT" ]
null
null
null
core/helper/config.py
caostorm/smng
f1cff4010a0645ae8e1182cd3c961d97cecf4a6e
[ "MIT" ]
null
null
null
core/helper/config.py
caostorm/smng
f1cff4010a0645ae8e1182cd3c961d97cecf4a6e
[ "MIT" ]
1
2019-06-26T13:05:45.000Z
2019-06-26T13:05:45.000Z
#coding=utf-8 import json from core.helper.crypt import pwd_crypt from core.helper.globalvar import global_const import sys class options_config: class ErrorTypeNotSupport(BaseException): def __init__(self): pass def __str__(self): return "This type didn't support" def __init__(self): self._config_file_path = global_const().get_value('BASEDIR') + "/etc/options.json" with open(self._config_file_path, "a+") as f: try: # 读取文件,从文件初始化_config对象 f.seek(0) self._config = json.loads(f.read()) except: self._config = {} def _sync_file(self): with open(self._config_file_path, "w+") as f: f.write(json.dumps(self._config)) pass def write(self, key, value): obj = {} if type(value) == type('1.2'): # string obj['type'] = 'string' elif type(value) == type(1.2): # float obj['type'] = 'float' elif type(value) == type(1): # int obj['type'] = 'int' elif type(value) == type(True): # bool obj['type'] = 'bool' else: raise self.ErrorTypeNotSupport encrypto = pwd_crypt() obj['value'] = encrypto.encrypt(str(value)) self._config[key] = obj self._sync_file() def read(self, key): obj = self._config[key] encrypto = pwd_crypt() if obj['type'] == 'string': return str(encrypto.decrypt(obj['value'])) elif obj['type'] == 'float': return float(encrypto.decrypt(obj['value'])) elif obj['type'] == 'int': return int(encrypto.decrypt(obj['value'])) elif obj['type'] == 'bool': real_value = encrypto.decrypt(obj['value']) if 'True' == real_value: return True elif 'False' == real_value: return False elif obj['type'] == 'long': return long(encrypto.decrypt(obj['value']))
30.142857
90
0.519431
import json from core.helper.crypt import pwd_crypt from core.helper.globalvar import global_const import sys class options_config: class ErrorTypeNotSupport(BaseException): def __init__(self): pass def __str__(self): return "This type didn't support" def __init__(self): self._config_file_path = global_const().get_value('BASEDIR') + "/etc/options.json" with open(self._config_file_path, "a+") as f: try: # 读取文件,从文件初始化_config对象 f.seek(0) self._config = json.loads(f.read()) except: self._config = {} def _sync_file(self): with open(self._config_file_path, "w+") as f: f.write(json.dumps(self._config)) pass def write(self, key, value): obj = {} if type(value) == type('1.2'): # string obj['type'] = 'string' elif type(value) == type(1.2): # float obj['type'] = 'float' elif type(value) == type(1): # int obj['type'] = 'int' elif type(value) == type(True): # bool obj['type'] = 'bool' else: raise self.ErrorTypeNotSupport encrypto = pwd_crypt() obj['value'] = encrypto.encrypt(str(value)) self._config[key] = obj self._sync_file() def read(self, key): obj = self._config[key] encrypto = pwd_crypt() if obj['type'] == 'string': return str(encrypto.decrypt(obj['value'])) elif obj['type'] == 'float': return float(encrypto.decrypt(obj['value'])) elif obj['type'] == 'int': return int(encrypto.decrypt(obj['value'])) elif obj['type'] == 'bool': real_value = encrypto.decrypt(obj['value']) if 'True' == real_value: return True elif 'False' == real_value: return False elif obj['type'] == 'long': return long(encrypto.decrypt(obj['value']))
true
true
f72c9d1c53416fbc1312ed7ced97e6c382733715
12,177
py
Python
tensorflow_addons/layers/normalizations.py
tzachar/addons
e352207da32e4670a36a295ea477c476118cb0d9
[ "Apache-2.0" ]
null
null
null
tensorflow_addons/layers/normalizations.py
tzachar/addons
e352207da32e4670a36a295ea477c476118cb0d9
[ "Apache-2.0" ]
null
null
null
tensorflow_addons/layers/normalizations.py
tzachar/addons
e352207da32e4670a36a295ea477c476118cb0d9
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 The TensorFlow Authors. 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. # Orginal implementation from keras_contrib/layer/normalization # ============================================================================= from __future__ import absolute_import from __future__ import division from __future__ import print_function import logging import tensorflow as tf @tf.keras.utils.register_keras_serializable(package='Addons') class GroupNormalization(tf.keras.layers.Layer): """Group normalization layer. Group Normalization divides the channels into groups and computes within each group the mean and variance for normalization. Empirically, its accuracy is more stable than batch norm in a wide range of small batch sizes, if learning rate is adjusted linearly with batch sizes. Relation to Layer Normalization: If the number of groups is set to 1, then this operation becomes identical to Layer Normalization. Relation to Instance Normalization: If the number of groups is set to the input dimension (number of groups is equal to number of channels), then this operation becomes identical to Instance Normalization. Arguments groups: Integer, the number of groups for Group Normalization. Can be in the range [1, N] where N is the input dimension. The input dimension must be divisible by the number of groups. axis: Integer, the axis that should be normalized. epsilon: Small float added to variance to avoid dividing by zero. center: If True, add offset of `beta` to normalized tensor. If False, `beta` is ignored. scale: If True, multiply by `gamma`. If False, `gamma` is not used. beta_initializer: Initializer for the beta weight. gamma_initializer: Initializer for the gamma weight. beta_regularizer: Optional regularizer for the beta weight. gamma_regularizer: Optional regularizer for the gamma weight. beta_constraint: Optional constraint for the beta weight. gamma_constraint: Optional constraint for the gamma weight. Input shape Arbitrary. Use the keyword argument `input_shape` (tuple of integers, does not include the samples axis) when using this layer as the first layer in a model. Output shape Same shape as input. References - [Group Normalization](https://arxiv.org/abs/1803.08494) """ def __init__(self, groups=2, axis=-1, epsilon=1e-3, center=True, scale=True, beta_initializer='zeros', gamma_initializer='ones', beta_regularizer=None, gamma_regularizer=None, beta_constraint=None, gamma_constraint=None, **kwargs): super(GroupNormalization, self).__init__(**kwargs) self.supports_masking = True self.groups = groups self.axis = axis self.epsilon = epsilon self.center = center self.scale = scale self.beta_initializer = tf.keras.initializers.get(beta_initializer) self.gamma_initializer = tf.keras.initializers.get(gamma_initializer) self.beta_regularizer = tf.keras.regularizers.get(beta_regularizer) self.gamma_regularizer = tf.keras.regularizers.get(gamma_regularizer) self.beta_constraint = tf.keras.constraints.get(beta_constraint) self.gamma_constraint = tf.keras.constraints.get(gamma_constraint) self._check_axis() def build(self, input_shape): self._check_if_input_shape_is_none(input_shape) self._set_number_of_groups_for_instance_norm(input_shape) self._check_size_of_dimensions(input_shape) self._create_input_spec(input_shape) self._add_gamma_weight(input_shape) self._add_beta_weight(input_shape) self.built = True super(GroupNormalization, self).build(input_shape) def call(self, inputs): input_shape = tf.keras.backend.int_shape(inputs) tensor_input_shape = tf.shape(inputs) reshaped_inputs, group_shape = self._reshape_into_groups( inputs, input_shape, tensor_input_shape) normalized_inputs = self._apply_normalization(reshaped_inputs, input_shape) outputs = tf.reshape(normalized_inputs, tensor_input_shape) return outputs def get_config(self): config = { 'groups': self.groups, 'axis': self.axis, 'epsilon': self.epsilon, 'center': self.center, 'scale': self.scale, 'beta_initializer': tf.keras.initializers.serialize(self.beta_initializer), 'gamma_initializer': tf.keras.initializers.serialize(self.gamma_initializer), 'beta_regularizer': tf.keras.regularizers.serialize(self.beta_regularizer), 'gamma_regularizer': tf.keras.regularizers.serialize(self.gamma_regularizer), 'beta_constraint': tf.keras.constraints.serialize(self.beta_constraint), 'gamma_constraint': tf.keras.constraints.serialize(self.gamma_constraint) } base_config = super(GroupNormalization, self).get_config() return dict(list(base_config.items()) + list(config.items())) def compute_output_shape(self, input_shape): return input_shape def _reshape_into_groups(self, inputs, input_shape, tensor_input_shape): group_shape = [tensor_input_shape[i] for i in range(len(input_shape))] group_shape[self.axis] = input_shape[self.axis] // self.groups group_shape.insert(1, self.groups) group_shape = tf.stack(group_shape) reshaped_inputs = tf.reshape(inputs, group_shape) return reshaped_inputs, group_shape def _apply_normalization(self, reshaped_inputs, input_shape): group_shape = tf.keras.backend.int_shape(reshaped_inputs) group_reduction_axes = list(range(len(group_shape))) # Remember the ordering of the tensor is [batch, group , steps]. Jump # the first 2 to calculate the variance and the mean mean, variance = tf.nn.moments( reshaped_inputs, group_reduction_axes[2:], keepdims=True) gamma, beta = self._get_reshaped_weights(input_shape) normalized_inputs = tf.nn.batch_normalization( reshaped_inputs, mean=mean, variance=variance, scale=gamma, offset=beta, variance_epsilon=self.epsilon) return normalized_inputs def _get_reshaped_weights(self, input_shape): broadcast_shape = self._create_broadcast_shape(input_shape) gamma = None beta = None if self.scale: gamma = tf.reshape(self.gamma, broadcast_shape) if self.center: beta = tf.reshape(self.beta, broadcast_shape) return gamma, beta def _check_if_input_shape_is_none(self, input_shape): dim = input_shape[self.axis] if dim is None: raise ValueError('Axis ' + str(self.axis) + ' of ' 'input tensor should have a defined dimension ' 'but the layer received an input with shape ' + str(input_shape) + '.') def _set_number_of_groups_for_instance_norm(self, input_shape): dim = input_shape[self.axis] if self.groups == -1: self.groups = dim def _check_size_of_dimensions(self, input_shape): dim = input_shape[self.axis] if dim < self.groups: raise ValueError( 'Number of groups (' + str(self.groups) + ') cannot be ' 'more than the number of channels (' + str(dim) + ').') if dim % self.groups != 0: raise ValueError( 'Number of groups (' + str(self.groups) + ') must be a ' 'multiple of the number of channels (' + str(dim) + ').') def _check_axis(self): if self.axis == 0: raise ValueError( "You are trying to normalize your batch axis. Do you want to " "use tf.layer.batch_normalization instead") def _create_input_spec(self, input_shape): dim = input_shape[self.axis] self.input_spec = tf.keras.layers.InputSpec( ndim=len(input_shape), axes={self.axis: dim}) def _add_gamma_weight(self, input_shape): dim = input_shape[self.axis] shape = (dim,) if self.scale: self.gamma = self.add_weight( shape=shape, name='gamma', initializer=self.gamma_initializer, regularizer=self.gamma_regularizer, constraint=self.gamma_constraint) else: self.gamma = None def _add_beta_weight(self, input_shape): dim = input_shape[self.axis] shape = (dim,) if self.center: self.beta = self.add_weight( shape=shape, name='beta', initializer=self.beta_initializer, regularizer=self.beta_regularizer, constraint=self.beta_constraint) else: self.beta = None def _create_broadcast_shape(self, input_shape): broadcast_shape = [1] * len(input_shape) broadcast_shape[self.axis] = input_shape[self.axis] // self.groups broadcast_shape.insert(1, self.groups) return broadcast_shape @tf.keras.utils.register_keras_serializable(package='Addons') class InstanceNormalization(GroupNormalization): """Instance normalization layer. Instance Normalization is an specific case of ```GroupNormalization```since it normalizes all features of one channel. The Groupsize is equal to the channel size. Empirically, its accuracy is more stable than batch norm in a wide range of small batch sizes, if learning rate is adjusted linearly with batch sizes. Arguments axis: Integer, the axis that should be normalized. epsilon: Small float added to variance to avoid dividing by zero. center: If True, add offset of `beta` to normalized tensor. If False, `beta` is ignored. scale: If True, multiply by `gamma`. If False, `gamma` is not used. beta_initializer: Initializer for the beta weight. gamma_initializer: Initializer for the gamma weight. beta_regularizer: Optional regularizer for the beta weight. gamma_regularizer: Optional regularizer for the gamma weight. beta_constraint: Optional constraint for the beta weight. gamma_constraint: Optional constraint for the gamma weight. Input shape Arbitrary. Use the keyword argument `input_shape` (tuple of integers, does not include the samples axis) when using this layer as the first layer in a model. Output shape Same shape as input. References - [Instance Normalization: The Missing Ingredient for Fast Stylization] (https://arxiv.org/abs/1607.08022) """ def __init__(self, **kwargs): if "groups" in kwargs: logging.warning("The given value for groups will be overwritten.") kwargs["groups"] = -1 super(InstanceNormalization, self).__init__(**kwargs)
38.292453
79
0.642687
from __future__ import absolute_import from __future__ import division from __future__ import print_function import logging import tensorflow as tf @tf.keras.utils.register_keras_serializable(package='Addons') class GroupNormalization(tf.keras.layers.Layer): def __init__(self, groups=2, axis=-1, epsilon=1e-3, center=True, scale=True, beta_initializer='zeros', gamma_initializer='ones', beta_regularizer=None, gamma_regularizer=None, beta_constraint=None, gamma_constraint=None, **kwargs): super(GroupNormalization, self).__init__(**kwargs) self.supports_masking = True self.groups = groups self.axis = axis self.epsilon = epsilon self.center = center self.scale = scale self.beta_initializer = tf.keras.initializers.get(beta_initializer) self.gamma_initializer = tf.keras.initializers.get(gamma_initializer) self.beta_regularizer = tf.keras.regularizers.get(beta_regularizer) self.gamma_regularizer = tf.keras.regularizers.get(gamma_regularizer) self.beta_constraint = tf.keras.constraints.get(beta_constraint) self.gamma_constraint = tf.keras.constraints.get(gamma_constraint) self._check_axis() def build(self, input_shape): self._check_if_input_shape_is_none(input_shape) self._set_number_of_groups_for_instance_norm(input_shape) self._check_size_of_dimensions(input_shape) self._create_input_spec(input_shape) self._add_gamma_weight(input_shape) self._add_beta_weight(input_shape) self.built = True super(GroupNormalization, self).build(input_shape) def call(self, inputs): input_shape = tf.keras.backend.int_shape(inputs) tensor_input_shape = tf.shape(inputs) reshaped_inputs, group_shape = self._reshape_into_groups( inputs, input_shape, tensor_input_shape) normalized_inputs = self._apply_normalization(reshaped_inputs, input_shape) outputs = tf.reshape(normalized_inputs, tensor_input_shape) return outputs def get_config(self): config = { 'groups': self.groups, 'axis': self.axis, 'epsilon': self.epsilon, 'center': self.center, 'scale': self.scale, 'beta_initializer': tf.keras.initializers.serialize(self.beta_initializer), 'gamma_initializer': tf.keras.initializers.serialize(self.gamma_initializer), 'beta_regularizer': tf.keras.regularizers.serialize(self.beta_regularizer), 'gamma_regularizer': tf.keras.regularizers.serialize(self.gamma_regularizer), 'beta_constraint': tf.keras.constraints.serialize(self.beta_constraint), 'gamma_constraint': tf.keras.constraints.serialize(self.gamma_constraint) } base_config = super(GroupNormalization, self).get_config() return dict(list(base_config.items()) + list(config.items())) def compute_output_shape(self, input_shape): return input_shape def _reshape_into_groups(self, inputs, input_shape, tensor_input_shape): group_shape = [tensor_input_shape[i] for i in range(len(input_shape))] group_shape[self.axis] = input_shape[self.axis] // self.groups group_shape.insert(1, self.groups) group_shape = tf.stack(group_shape) reshaped_inputs = tf.reshape(inputs, group_shape) return reshaped_inputs, group_shape def _apply_normalization(self, reshaped_inputs, input_shape): group_shape = tf.keras.backend.int_shape(reshaped_inputs) group_reduction_axes = list(range(len(group_shape))) mean, variance = tf.nn.moments( reshaped_inputs, group_reduction_axes[2:], keepdims=True) gamma, beta = self._get_reshaped_weights(input_shape) normalized_inputs = tf.nn.batch_normalization( reshaped_inputs, mean=mean, variance=variance, scale=gamma, offset=beta, variance_epsilon=self.epsilon) return normalized_inputs def _get_reshaped_weights(self, input_shape): broadcast_shape = self._create_broadcast_shape(input_shape) gamma = None beta = None if self.scale: gamma = tf.reshape(self.gamma, broadcast_shape) if self.center: beta = tf.reshape(self.beta, broadcast_shape) return gamma, beta def _check_if_input_shape_is_none(self, input_shape): dim = input_shape[self.axis] if dim is None: raise ValueError('Axis ' + str(self.axis) + ' of ' 'input tensor should have a defined dimension ' 'but the layer received an input with shape ' + str(input_shape) + '.') def _set_number_of_groups_for_instance_norm(self, input_shape): dim = input_shape[self.axis] if self.groups == -1: self.groups = dim def _check_size_of_dimensions(self, input_shape): dim = input_shape[self.axis] if dim < self.groups: raise ValueError( 'Number of groups (' + str(self.groups) + ') cannot be ' 'more than the number of channels (' + str(dim) + ').') if dim % self.groups != 0: raise ValueError( 'Number of groups (' + str(self.groups) + ') must be a ' 'multiple of the number of channels (' + str(dim) + ').') def _check_axis(self): if self.axis == 0: raise ValueError( "You are trying to normalize your batch axis. Do you want to " "use tf.layer.batch_normalization instead") def _create_input_spec(self, input_shape): dim = input_shape[self.axis] self.input_spec = tf.keras.layers.InputSpec( ndim=len(input_shape), axes={self.axis: dim}) def _add_gamma_weight(self, input_shape): dim = input_shape[self.axis] shape = (dim,) if self.scale: self.gamma = self.add_weight( shape=shape, name='gamma', initializer=self.gamma_initializer, regularizer=self.gamma_regularizer, constraint=self.gamma_constraint) else: self.gamma = None def _add_beta_weight(self, input_shape): dim = input_shape[self.axis] shape = (dim,) if self.center: self.beta = self.add_weight( shape=shape, name='beta', initializer=self.beta_initializer, regularizer=self.beta_regularizer, constraint=self.beta_constraint) else: self.beta = None def _create_broadcast_shape(self, input_shape): broadcast_shape = [1] * len(input_shape) broadcast_shape[self.axis] = input_shape[self.axis] // self.groups broadcast_shape.insert(1, self.groups) return broadcast_shape @tf.keras.utils.register_keras_serializable(package='Addons') class InstanceNormalization(GroupNormalization): def __init__(self, **kwargs): if "groups" in kwargs: logging.warning("The given value for groups will be overwritten.") kwargs["groups"] = -1 super(InstanceNormalization, self).__init__(**kwargs)
true
true
f72c9e1c750207443829a4d4625294cef174db04
4,966
py
Python
restaurants/views.py
sunilsm7/django_resto
b7698653093af7e6f26dd0d0c7b8d6046b402ea4
[ "MIT" ]
1
2017-08-03T01:40:12.000Z
2017-08-03T01:40:12.000Z
restaurants/views.py
sunilsm7/django_resto
b7698653093af7e6f26dd0d0c7b8d6046b402ea4
[ "MIT" ]
null
null
null
restaurants/views.py
sunilsm7/django_resto
b7698653093af7e6f26dd0d0c7b8d6046b402ea4
[ "MIT" ]
null
null
null
from django.contrib.auth.decorators import login_required from django.contrib.auth.mixins import LoginRequiredMixin from django.contrib import messages from django.contrib.contenttypes.models import ContentType from django.core.paginator import Paginator from django.core.urlresolvers import reverse, reverse_lazy from django.db.models import Q from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render, get_object_or_404, redirect from django.views import View from django.views.generic import ( CreateView, DetailView, ListView, TemplateView, UpdateView ) from django.views.generic.edit import FormView, FormMixin from django.views.generic.detail import SingleObjectMixin from comments.forms import CommentForm from comments.models import Comment from .forms import ( RestaurantCreateForm, RestaurantLocationCreateForm, RestaurantSearchForm ) from .models import RestaurantLocations # Create your views here. class RestaurantListView(ListView): template_name = 'restaurants/restaurants_list_all.html' paginate_by = 10 form_class = RestaurantSearchForm def get_queryset(self): query = self.request.GET.get('q') queryset = RestaurantLocations.objects.search(query) return queryset class RestaurantDetailView(DetailView, FormView): #form_class = CommentForm template_name = 'restaurants/restaurantlocations_detail.html' queryset = RestaurantLocations.objects.all() # def get_queryset(self): # queryset = RestaurantLocations.objects.all() # return queryset def get_context_data(self, **kwargs): comments = Comment.objects.filter(object_id=objects.id) context = super(RestaurantDetailView, self).get_context_data(**kwargs) return context def render(self, request): objects = get_object_or_404(RestaurantLocations, slug=self.kwargs.get('slug')) comments = Comment.objects.filter(object_id=objects.id) return render(request, 'restaurants/restaurantlocations_detail.html', {'comment_form': self.form, 'comments':comments, 'object':objects}) def get(self, request, *args, **kwargs): self.object = self.get_object() # initial_data = { # "content_type": self.object.get_content_type, # "object_id": self.object.id # } self.form = CommentForm(initial={"content_type": self.object.get_content_type,"object_id": self.object.id}) return self.render(request) #return super(RestaurantDetailView, self).get(request, *args, **kwargs) def post(self, request, *args, **kwargs): if not request.user.is_authenticated: return HttpResponseForbidden() self.object = self.get_object() self.form = CommentForm(request.POST or None) form = self.form if form.is_valid() and request.user.is_authenticated: c_type = form.cleaned_data["content_type"] content_qs = ContentType.objects.filter(app_label ='restaurants') content_type = content_qs.get(model='restaurantlocations') obj_id = form.cleaned_data['object_id'] content_data = form.cleaned_data["content"] parent_obj = None try: parent_id = int(request.POST.get("parent_id")) except: parent_id = None if parent_id: parent_qs = Comment.objects.filter(id=parent_id) if parent_qs.exists() and parent_qs.count() == 1: parent_obj = parent_qs.first() new_comment, created = Comment.objects.get_or_create( user = request.user, content_type= content_type, object_id = obj_id, content = content_data, parent = parent_obj, ) return HttpResponseRedirect(new_comment.get_absolute_url()) else: return self.render(request) #return super(RetaurantComment, self).post(request, *args, **kwargs) class MyRestaurantListView(LoginRequiredMixin, ListView): template_name = 'restaurants/restaurants_list.html' paginate_by = 10 def get_queryset(self): return RestaurantLocations.objects.filter(owner=self.request.user) class RestaurantCreateView(LoginRequiredMixin, CreateView): form_class = RestaurantLocationCreateForm template_name = 'form.html' # success_url = '/restaurants/' login_url = '/login/' def form_valid(self, form): instance = form.save(commit=False) instance.owner = self.request.user return super(RestaurantCreateView, self).form_valid(form) def get_context_data(self, *args, **kwargs): context = super(RestaurantCreateView, self).get_context_data(*args, **kwargs) context['title'] = 'Add Restaurant' return context class RestaurantUpdateView(LoginRequiredMixin, UpdateView): form_class = RestaurantLocationCreateForm template_name = 'restaurants/detail-update.html' # success_url = '/restaurants/' login_url = '/login/' def get_context_data(self, *args, **kwargs): context = super(RestaurantUpdateView, self).get_context_data(*args, **kwargs) name = self.get_object().name context['title'] = '{} {}'.format('Update Restaurant: ', name) return context def get_queryset(self): return RestaurantLocations.objects.filter(owner=self.request.user)
31.833333
139
0.762384
from django.contrib.auth.decorators import login_required from django.contrib.auth.mixins import LoginRequiredMixin from django.contrib import messages from django.contrib.contenttypes.models import ContentType from django.core.paginator import Paginator from django.core.urlresolvers import reverse, reverse_lazy from django.db.models import Q from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render, get_object_or_404, redirect from django.views import View from django.views.generic import ( CreateView, DetailView, ListView, TemplateView, UpdateView ) from django.views.generic.edit import FormView, FormMixin from django.views.generic.detail import SingleObjectMixin from comments.forms import CommentForm from comments.models import Comment from .forms import ( RestaurantCreateForm, RestaurantLocationCreateForm, RestaurantSearchForm ) from .models import RestaurantLocations class RestaurantListView(ListView): template_name = 'restaurants/restaurants_list_all.html' paginate_by = 10 form_class = RestaurantSearchForm def get_queryset(self): query = self.request.GET.get('q') queryset = RestaurantLocations.objects.search(query) return queryset class RestaurantDetailView(DetailView, FormView): template_name = 'restaurants/restaurantlocations_detail.html' queryset = RestaurantLocations.objects.all() def get_context_data(self, **kwargs): comments = Comment.objects.filter(object_id=objects.id) context = super(RestaurantDetailView, self).get_context_data(**kwargs) return context def render(self, request): objects = get_object_or_404(RestaurantLocations, slug=self.kwargs.get('slug')) comments = Comment.objects.filter(object_id=objects.id) return render(request, 'restaurants/restaurantlocations_detail.html', {'comment_form': self.form, 'comments':comments, 'object':objects}) def get(self, request, *args, **kwargs): self.object = self.get_object() self.form = CommentForm(initial={"content_type": self.object.get_content_type,"object_id": self.object.id}) return self.render(request) def post(self, request, *args, **kwargs): if not request.user.is_authenticated: return HttpResponseForbidden() self.object = self.get_object() self.form = CommentForm(request.POST or None) form = self.form if form.is_valid() and request.user.is_authenticated: c_type = form.cleaned_data["content_type"] content_qs = ContentType.objects.filter(app_label ='restaurants') content_type = content_qs.get(model='restaurantlocations') obj_id = form.cleaned_data['object_id'] content_data = form.cleaned_data["content"] parent_obj = None try: parent_id = int(request.POST.get("parent_id")) except: parent_id = None if parent_id: parent_qs = Comment.objects.filter(id=parent_id) if parent_qs.exists() and parent_qs.count() == 1: parent_obj = parent_qs.first() new_comment, created = Comment.objects.get_or_create( user = request.user, content_type= content_type, object_id = obj_id, content = content_data, parent = parent_obj, ) return HttpResponseRedirect(new_comment.get_absolute_url()) else: return self.render(request) class MyRestaurantListView(LoginRequiredMixin, ListView): template_name = 'restaurants/restaurants_list.html' paginate_by = 10 def get_queryset(self): return RestaurantLocations.objects.filter(owner=self.request.user) class RestaurantCreateView(LoginRequiredMixin, CreateView): form_class = RestaurantLocationCreateForm template_name = 'form.html' login_url = '/login/' def form_valid(self, form): instance = form.save(commit=False) instance.owner = self.request.user return super(RestaurantCreateView, self).form_valid(form) def get_context_data(self, *args, **kwargs): context = super(RestaurantCreateView, self).get_context_data(*args, **kwargs) context['title'] = 'Add Restaurant' return context class RestaurantUpdateView(LoginRequiredMixin, UpdateView): form_class = RestaurantLocationCreateForm template_name = 'restaurants/detail-update.html' login_url = '/login/' def get_context_data(self, *args, **kwargs): context = super(RestaurantUpdateView, self).get_context_data(*args, **kwargs) name = self.get_object().name context['title'] = '{} {}'.format('Update Restaurant: ', name) return context def get_queryset(self): return RestaurantLocations.objects.filter(owner=self.request.user)
true
true
f72c9ff03b849eba70778f598d05555ab5123a75
1,072
py
Python
core/tests/test_managers/test_project.py
erexer/polyaxon
be14dae1ed56d568983388736bcdaf27a7baa4a4
[ "Apache-2.0" ]
null
null
null
core/tests/test_managers/test_project.py
erexer/polyaxon
be14dae1ed56d568983388736bcdaf27a7baa4a4
[ "Apache-2.0" ]
null
null
null
core/tests/test_managers/test_project.py
erexer/polyaxon
be14dae1ed56d568983388736bcdaf27a7baa4a4
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/python # # Copyright 2018-2020 Polyaxon, Inc. # # 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 pytest from polyaxon_sdk import V1Project from tests.utils import BaseTestCase from polyaxon.managers.project import ProjectManager @pytest.mark.managers_mark class TestProjectManager(BaseTestCase): def test_default_props(self): assert ProjectManager.is_all_visibility() is True assert ProjectManager.IS_POLYAXON_DIR is True assert ProjectManager.CONFIG_FILE_NAME == ".project" assert ProjectManager.CONFIG == V1Project
33.5
74
0.767724
import pytest from polyaxon_sdk import V1Project from tests.utils import BaseTestCase from polyaxon.managers.project import ProjectManager @pytest.mark.managers_mark class TestProjectManager(BaseTestCase): def test_default_props(self): assert ProjectManager.is_all_visibility() is True assert ProjectManager.IS_POLYAXON_DIR is True assert ProjectManager.CONFIG_FILE_NAME == ".project" assert ProjectManager.CONFIG == V1Project
true
true
f72ca02b98c9b0c00c8385d82a02c58fe350bf58
16,524
py
Python
src/ner_model/typer/data_translator.py
fracivilization/distant_ner_using_thesaurus
cebfb2bd950123ce3ef18e501314778cc41de71e
[ "Apache-2.0" ]
null
null
null
src/ner_model/typer/data_translator.py
fracivilization/distant_ner_using_thesaurus
cebfb2bd950123ce3ef18e501314778cc41de71e
[ "Apache-2.0" ]
null
null
null
src/ner_model/typer/data_translator.py
fracivilization/distant_ner_using_thesaurus
cebfb2bd950123ce3ef18e501314778cc41de71e
[ "Apache-2.0" ]
null
null
null
import dataclasses from enum import unique import click import datasets from datasets import features from datasets.arrow_dataset import Dataset from datasets.dataset_dict import DatasetDict from src.ner_model.chunker.abstract_model import Chunker from src.utils.utils import remove_BIE import dataclasses from seqeval.metrics.sequence_labeling import get_entities from collections import defaultdict from logging import getLogger from src.utils.params import span_length from hydra.utils import get_original_cwd from hashlib import md5 import prettytable from src.ner_model.chunker import ChunkerConfig from omegaconf import MISSING logger = getLogger(__name__) @dataclasses.dataclass class MSCConfig: ner_dataset: str = MISSING output_dir: str = MISSING with_o: bool = False chunker: ChunkerConfig = ChunkerConfig() o_sampling_ratio: float = 1.0 # hard_o_sampling: bool = False # o_outside_entity: bool = False # weight_of_hard_o_for_easy_o: float = 0.5 # from tqdm import tqdm from collections import Counter import random def remove_misguided_fns(starts, ends, labels): new_starts, new_ends, new_labels = [], [], [] misguided_tokens = set() for s, e, l in zip(starts, ends, labels): if l == "MISGUIDANCE": for i in range(s, e): misguided_tokens.add(i) for s, e, l in zip(starts, ends, labels): if l != "MISGUIDANCE": if l.startswith("nc"): span = set(range(s, e)) if span & misguided_tokens: continue new_starts.append(s) new_ends.append(e) new_labels.append(l) return new_starts, new_ends, new_labels def undersample_thesaurus_negatives(pre_span_classification_dataset): label_counter = Counter( [label for snt in pre_span_classification_dataset["labels"] for label in snt] ) pass positive_labels = [ label for label in label_counter.keys() if not label.startswith("nc-") ] max_positive_count = max(label_counter[label] for label in positive_labels) thesaurus_negative_class_sampling_ratio = { label: max_positive_count / count for label, count in label_counter.items() if label != "nc-O" and label.startswith("nc-") } new_pre_span_classification_dataset = defaultdict(list) pscd = pre_span_classification_dataset for tokens, starts, ends, labels in zip( pscd["tokens"], pscd["starts"], pscd["ends"], pscd["labels"] ): new_starts = [] new_ends = [] new_labels = [] for s, e, l in zip(starts, ends, labels): if ( l != "nc-O" and l.startswith("nc-") and random.random() > thesaurus_negative_class_sampling_ratio[l] ): continue new_starts.append(s) new_ends.append(e) new_labels.append(l) new_pre_span_classification_dataset["tokens"].append(tokens) new_pre_span_classification_dataset["starts"].append(new_starts) new_pre_span_classification_dataset["ends"].append(new_ends) new_pre_span_classification_dataset["labels"].append(new_labels) return new_pre_span_classification_dataset def ner_datasets_to_span_classification_datasets( ner_datasets: datasets.DatasetDict, data_args: MSCConfig, enumerator: Chunker, ) -> datasets.DatasetDict: pre_span_classification_datasets = dict() label_names = sorted( set( [ remove_BIE(tag) for tag in ner_datasets["test"].features["ner_tags"].feature.names if tag != "O" ] ) ) if data_args.with_o: if "nc-O" not in label_names: label_names = ["nc-O"] + label_names info = datasets.DatasetInfo( features=datasets.Features( { "tokens": datasets.Sequence(datasets.Value("string")), "starts": datasets.Sequence(datasets.Value("int32")), "ends": datasets.Sequence(datasets.Value("int32")), "labels": datasets.Sequence(datasets.ClassLabel(names=label_names)), } ) ) for key in ner_datasets: pre_span_classification_dataset = defaultdict(list) ner_tag_labels = ner_datasets[key].features["ner_tags"].feature.names for snt in tqdm(ner_datasets[key]): registered_chunks = set() ner_tags = [ner_tag_labels[tag] for tag in snt["ner_tags"]] starts = [] ends = [] labels = [] for label, s, e in get_entities(ner_tags): starts.append(s) ends.append(e + 1) labels.append(label) registered_chunks.add((s, e)) if data_args.with_o and key in {"train", "validation"}: for s, e in enumerator.predict(snt["tokens"]): if ( (s, e) not in registered_chunks and data_args.o_sampling_ratio > random.random() ): starts.append(s) ends.append(e) labels.append("nc-O") starts, ends, labels = remove_misguided_fns(starts, ends, labels) if labels: pre_span_classification_dataset["tokens"].append(snt["tokens"]) pre_span_classification_dataset["starts"].append(starts) pre_span_classification_dataset["ends"].append(ends) pre_span_classification_dataset["labels"].append(labels) # if key == "train": # pre_span_classification_dataset = undersample_thesaurus_negatives( # pre_span_classification_dataset # ) pre_span_classification_datasets[key] = datasets.Dataset.from_dict( pre_span_classification_dataset, info=info ) return datasets.DatasetDict(pre_span_classification_datasets) import numpy as np def label_balancing_span_classification_datasets( span_classification_datasets: datasets.DatasetDict, o_and_min_label_count_ratio=1 ): ret_datasets = dict() if "test" in span_classification_datasets: info = datasets.DatasetInfo( features=span_classification_datasets["test"].features ) else: info = datasets.DatasetInfo( features=span_classification_datasets["train"].features ) for split_key, dataset_split in span_classification_datasets.items(): if split_key != "test": if "labels" in dataset_split.features: # for multi span classification datasets span_classification_dataset = { "tokens": [], "starts": [], "ends": [], "labels": [], } label_count = Counter( [l for snt in dataset_split["labels"] for l in snt] ) min_label_count = min(label_count.values()) logger.info("min label count: %d" % min_label_count) undersampling_ratio = { label: min_label_count / count for label, count in label_count.items() } for snt in tqdm(dataset_split): starts = [] ends = [] labels = [] for s, e, l in zip(snt["starts"], snt["ends"], snt["labels"]): if random.random() < undersampling_ratio[l]: starts.append(s) ends.append(e) labels.append(l) if labels: span_classification_dataset["tokens"].append(snt["tokens"]) span_classification_dataset["starts"].append(starts) span_classification_dataset["ends"].append(ends) span_classification_dataset["labels"].append(labels) ret_datasets[split_key] = datasets.Dataset.from_dict( span_classification_dataset, info=info ) elif "label" in dataset_split.features: # for one span classification datasets span_classification_dataset = { "tokens": [], "start": [], "end": [], "label": [], } label_names = dataset_split.features["label"].names label_count = Counter(dataset_split["label"]) min_label_count = min(label_count.values()) logger.info("min label count: %d" % min_label_count) undersampling_ratio = dict() for label, count in label_count.items(): if label_names[label] == "O": undersampling_ratio[label] = ( min_label_count / count * o_and_min_label_count_ratio ) else: undersampling_ratio[label] = min_label_count / count for snt in tqdm(dataset_split): if random.random() < undersampling_ratio[snt["label"]]: for key, value in snt.items(): span_classification_dataset[key].append(value) ret_datasets[split_key] = datasets.Dataset.from_dict( span_classification_dataset, info=info ) else: raise NotImplementedError else: ret_datasets[split_key] = dataset_split return datasets.DatasetDict(ret_datasets) import os from pathlib import Path def print_label_statistics(span_classification_datasets: datasets.DatasetDict): for split_key, dataset_split in span_classification_datasets.items(): if "label" in dataset_split.features: label_names = dataset_split.features["label"].names label_count = Counter([label_names[l] for l in dataset_split["label"]]) else: pass label_names = dataset_split.features["labels"].feature.names label_count = Counter( [label_names[l] for snt in dataset_split["labels"] for l in snt] ) logger.info("label count of %s split: %s" % (split_key, label_count)) from copy import deepcopy from typing import Dict, List import random def load_o_label_spans(unlabelled_corpus: Dataset, span_num: int) -> List: # 各文から取得するスパン数を指定 # 各文に対してspan_length長のスパンをかき集めてくる # 各文に定められた個数になるまでサンプリング # 全体の断片から決められたスパン数になるまでサンプリング pass snt_num = len(unlabelled_corpus) span_num_per_snt = int(span_num / snt_num) + 100 o_label_spans = [] for snt in unlabelled_corpus["tokens"]: spans = [ (s, e) for s in range(len(snt)) for e in range(s + 1, len(snt) + 1) if e - s <= MSCConfig.span_length ] for s, e in random.sample(spans, min(span_num_per_snt, len(spans))): o_label_spans.append(snt[s:e]) return random.sample(o_label_spans, min(span_num, len(o_label_spans))) import spacy from itertools import islice from dataclasses import MISSING, dataclass @dataclass class Term2CatBasedDatasetArgs: label_balance: bool = False pass def load_term2cat_based_span_classification_dataset( term2cat: Dict, unlabelled_corpus: Dataset, args: Term2CatBasedDatasetArgs ): tokenizer = spacy.load("en_core_sci_sm") tokenizer.remove_pipe("ner") dataset = {"tokens": [], "start": [], "end": [], "label": []} label_names = ["O"] + sorted(set(term2cat.values())) dict_label_count = Counter(term2cat.values()) if args.label_balance: over_sampling_ratio = { l: dict_label_count.most_common()[0][1] / dict_label_count[l] for l in dict_label_count } else: over_sampling_ratio = {l: 1 for l in dict_label_count} for term, cat in tqdm(term2cat.items()): osr = over_sampling_ratio[cat] tokenized_terms = tokenizer(term) while True: if 0 < osr < 1: if osr > random.random(): break elif osr <= 0: break dataset["tokens"].append([w.text for w in tokenized_terms]) dataset["start"].append(0) dataset["end"].append(len(tokenized_terms)) dataset["label"].append(label_names.index(cat)) osr -= 1 if args.label_balance: span_num = dict_label_count.most_common()[0][1] else: span_num = sum(dict_label_count.values()) o_labeled_spans = load_o_label_spans(unlabelled_corpus, span_num) for span in o_labeled_spans: dataset["tokens"].append(span) dataset["start"].append(0) dataset["end"].append(len(span)) dataset["label"].append(label_names.index("O")) features = datasets.Features( { "tokens": datasets.Sequence(datasets.Value("string")), "start": datasets.Value("int32"), "end": datasets.Value("int32"), "label": datasets.ClassLabel(names=label_names), } ) # new_dataset_dictに追加 return Dataset.from_dict(dataset, features=features) def split_span_classification_dataset(datasets: Dataset): features = datasets.features split_num = int(len(datasets) * 0.9) splitted_datasets = dict() from random import shuffle indexes = list(range(len(datasets))) shuffle(indexes) splitted_datasets["train"] = Dataset.from_dict( datasets.__getitem__(indexes[:split_num]), features=features ) splitted_datasets["validation"] = Dataset.from_dict( datasets.__getitem__(indexes[split_num:]), features=features ) return DatasetDict(splitted_datasets) def join_span_classification_datasets( main_datasets: DatasetDict, sub_datasets: DatasetDict ): pass new_dataset_dict = dict() for key, split in main_datasets.items(): if key in sub_datasets: sub_split = sub_datasets[key] new_dataset = {feature: split[feature] for feature in split.features} main_label_names = split.features["label"].names sub_label_names = sub_split.features["label"].names assert len(main_label_names) == len(sub_label_names) assert len(split.features) == len(sub_split.features) label_map = { i: sub_label_names.index(l) for i, l in enumerate(main_label_names) } for feature in sub_split.features: if feature == "label": new_dataset[feature] += [label_map[l] for l in sub_split[feature]] else: new_dataset[feature] += sub_split[feature] new_dataset_dict[key] = Dataset.from_dict(new_dataset, split.features) else: new_dataset_dict[key] = split return DatasetDict(new_dataset_dict) def log_label_ratio(msc_datasets: DatasetDict): table = prettytable.PrettyTable(["Label", "Count", "Ratio (%)"]) pass train_dataset = msc_datasets["train"] label_names = train_dataset.features["labels"].feature.names c = Counter([label for snt in train_dataset["labels"] for label in snt]) label_sum = sum(c.values()) for lid, count in c.most_common(): table.add_row([label_names[lid], count, "%.2f" % (100 * count / label_sum)]) logger.info(table.get_string()) def translate_into_msc_datasets( ner_datasets: DatasetDict, msc_args: MSCConfig, enumerator: Chunker, ): input_hash = {k: v._fingerprint for k, v in ner_datasets.items()} input_hash["msc_args"] = str(msc_args) input_hash["enumerator"] = str(enumerator.config) output_dir = Path(get_original_cwd()).joinpath( "data", "buffer", md5(str(input_hash).encode()).hexdigest() ) logger.info("output_dir of msc_datasets: " + str(output_dir)) if not output_dir.exists(): msc_datasets = ner_datasets_to_span_classification_datasets( ner_datasets, msc_args, enumerator ) msc_datasets.save_to_disk(output_dir) else: msc_datasets = DatasetDict.load_from_disk(output_dir) log_label_ratio(msc_datasets) return msc_datasets
37.216216
86
0.60633
import dataclasses from enum import unique import click import datasets from datasets import features from datasets.arrow_dataset import Dataset from datasets.dataset_dict import DatasetDict from src.ner_model.chunker.abstract_model import Chunker from src.utils.utils import remove_BIE import dataclasses from seqeval.metrics.sequence_labeling import get_entities from collections import defaultdict from logging import getLogger from src.utils.params import span_length from hydra.utils import get_original_cwd from hashlib import md5 import prettytable from src.ner_model.chunker import ChunkerConfig from omegaconf import MISSING logger = getLogger(__name__) @dataclasses.dataclass class MSCConfig: ner_dataset: str = MISSING output_dir: str = MISSING with_o: bool = False chunker: ChunkerConfig = ChunkerConfig() o_sampling_ratio: float = 1.0 from tqdm import tqdm from collections import Counter import random def remove_misguided_fns(starts, ends, labels): new_starts, new_ends, new_labels = [], [], [] misguided_tokens = set() for s, e, l in zip(starts, ends, labels): if l == "MISGUIDANCE": for i in range(s, e): misguided_tokens.add(i) for s, e, l in zip(starts, ends, labels): if l != "MISGUIDANCE": if l.startswith("nc"): span = set(range(s, e)) if span & misguided_tokens: continue new_starts.append(s) new_ends.append(e) new_labels.append(l) return new_starts, new_ends, new_labels def undersample_thesaurus_negatives(pre_span_classification_dataset): label_counter = Counter( [label for snt in pre_span_classification_dataset["labels"] for label in snt] ) pass positive_labels = [ label for label in label_counter.keys() if not label.startswith("nc-") ] max_positive_count = max(label_counter[label] for label in positive_labels) thesaurus_negative_class_sampling_ratio = { label: max_positive_count / count for label, count in label_counter.items() if label != "nc-O" and label.startswith("nc-") } new_pre_span_classification_dataset = defaultdict(list) pscd = pre_span_classification_dataset for tokens, starts, ends, labels in zip( pscd["tokens"], pscd["starts"], pscd["ends"], pscd["labels"] ): new_starts = [] new_ends = [] new_labels = [] for s, e, l in zip(starts, ends, labels): if ( l != "nc-O" and l.startswith("nc-") and random.random() > thesaurus_negative_class_sampling_ratio[l] ): continue new_starts.append(s) new_ends.append(e) new_labels.append(l) new_pre_span_classification_dataset["tokens"].append(tokens) new_pre_span_classification_dataset["starts"].append(new_starts) new_pre_span_classification_dataset["ends"].append(new_ends) new_pre_span_classification_dataset["labels"].append(new_labels) return new_pre_span_classification_dataset def ner_datasets_to_span_classification_datasets( ner_datasets: datasets.DatasetDict, data_args: MSCConfig, enumerator: Chunker, ) -> datasets.DatasetDict: pre_span_classification_datasets = dict() label_names = sorted( set( [ remove_BIE(tag) for tag in ner_datasets["test"].features["ner_tags"].feature.names if tag != "O" ] ) ) if data_args.with_o: if "nc-O" not in label_names: label_names = ["nc-O"] + label_names info = datasets.DatasetInfo( features=datasets.Features( { "tokens": datasets.Sequence(datasets.Value("string")), "starts": datasets.Sequence(datasets.Value("int32")), "ends": datasets.Sequence(datasets.Value("int32")), "labels": datasets.Sequence(datasets.ClassLabel(names=label_names)), } ) ) for key in ner_datasets: pre_span_classification_dataset = defaultdict(list) ner_tag_labels = ner_datasets[key].features["ner_tags"].feature.names for snt in tqdm(ner_datasets[key]): registered_chunks = set() ner_tags = [ner_tag_labels[tag] for tag in snt["ner_tags"]] starts = [] ends = [] labels = [] for label, s, e in get_entities(ner_tags): starts.append(s) ends.append(e + 1) labels.append(label) registered_chunks.add((s, e)) if data_args.with_o and key in {"train", "validation"}: for s, e in enumerator.predict(snt["tokens"]): if ( (s, e) not in registered_chunks and data_args.o_sampling_ratio > random.random() ): starts.append(s) ends.append(e) labels.append("nc-O") starts, ends, labels = remove_misguided_fns(starts, ends, labels) if labels: pre_span_classification_dataset["tokens"].append(snt["tokens"]) pre_span_classification_dataset["starts"].append(starts) pre_span_classification_dataset["ends"].append(ends) pre_span_classification_dataset["labels"].append(labels) pre_span_classification_datasets[key] = datasets.Dataset.from_dict( pre_span_classification_dataset, info=info ) return datasets.DatasetDict(pre_span_classification_datasets) import numpy as np def label_balancing_span_classification_datasets( span_classification_datasets: datasets.DatasetDict, o_and_min_label_count_ratio=1 ): ret_datasets = dict() if "test" in span_classification_datasets: info = datasets.DatasetInfo( features=span_classification_datasets["test"].features ) else: info = datasets.DatasetInfo( features=span_classification_datasets["train"].features ) for split_key, dataset_split in span_classification_datasets.items(): if split_key != "test": if "labels" in dataset_split.features: span_classification_dataset = { "tokens": [], "starts": [], "ends": [], "labels": [], } label_count = Counter( [l for snt in dataset_split["labels"] for l in snt] ) min_label_count = min(label_count.values()) logger.info("min label count: %d" % min_label_count) undersampling_ratio = { label: min_label_count / count for label, count in label_count.items() } for snt in tqdm(dataset_split): starts = [] ends = [] labels = [] for s, e, l in zip(snt["starts"], snt["ends"], snt["labels"]): if random.random() < undersampling_ratio[l]: starts.append(s) ends.append(e) labels.append(l) if labels: span_classification_dataset["tokens"].append(snt["tokens"]) span_classification_dataset["starts"].append(starts) span_classification_dataset["ends"].append(ends) span_classification_dataset["labels"].append(labels) ret_datasets[split_key] = datasets.Dataset.from_dict( span_classification_dataset, info=info ) elif "label" in dataset_split.features: span_classification_dataset = { "tokens": [], "start": [], "end": [], "label": [], } label_names = dataset_split.features["label"].names label_count = Counter(dataset_split["label"]) min_label_count = min(label_count.values()) logger.info("min label count: %d" % min_label_count) undersampling_ratio = dict() for label, count in label_count.items(): if label_names[label] == "O": undersampling_ratio[label] = ( min_label_count / count * o_and_min_label_count_ratio ) else: undersampling_ratio[label] = min_label_count / count for snt in tqdm(dataset_split): if random.random() < undersampling_ratio[snt["label"]]: for key, value in snt.items(): span_classification_dataset[key].append(value) ret_datasets[split_key] = datasets.Dataset.from_dict( span_classification_dataset, info=info ) else: raise NotImplementedError else: ret_datasets[split_key] = dataset_split return datasets.DatasetDict(ret_datasets) import os from pathlib import Path def print_label_statistics(span_classification_datasets: datasets.DatasetDict): for split_key, dataset_split in span_classification_datasets.items(): if "label" in dataset_split.features: label_names = dataset_split.features["label"].names label_count = Counter([label_names[l] for l in dataset_split["label"]]) else: pass label_names = dataset_split.features["labels"].feature.names label_count = Counter( [label_names[l] for snt in dataset_split["labels"] for l in snt] ) logger.info("label count of %s split: %s" % (split_key, label_count)) from copy import deepcopy from typing import Dict, List import random def load_o_label_spans(unlabelled_corpus: Dataset, span_num: int) -> List: pass snt_num = len(unlabelled_corpus) span_num_per_snt = int(span_num / snt_num) + 100 o_label_spans = [] for snt in unlabelled_corpus["tokens"]: spans = [ (s, e) for s in range(len(snt)) for e in range(s + 1, len(snt) + 1) if e - s <= MSCConfig.span_length ] for s, e in random.sample(spans, min(span_num_per_snt, len(spans))): o_label_spans.append(snt[s:e]) return random.sample(o_label_spans, min(span_num, len(o_label_spans))) import spacy from itertools import islice from dataclasses import MISSING, dataclass @dataclass class Term2CatBasedDatasetArgs: label_balance: bool = False pass def load_term2cat_based_span_classification_dataset( term2cat: Dict, unlabelled_corpus: Dataset, args: Term2CatBasedDatasetArgs ): tokenizer = spacy.load("en_core_sci_sm") tokenizer.remove_pipe("ner") dataset = {"tokens": [], "start": [], "end": [], "label": []} label_names = ["O"] + sorted(set(term2cat.values())) dict_label_count = Counter(term2cat.values()) if args.label_balance: over_sampling_ratio = { l: dict_label_count.most_common()[0][1] / dict_label_count[l] for l in dict_label_count } else: over_sampling_ratio = {l: 1 for l in dict_label_count} for term, cat in tqdm(term2cat.items()): osr = over_sampling_ratio[cat] tokenized_terms = tokenizer(term) while True: if 0 < osr < 1: if osr > random.random(): break elif osr <= 0: break dataset["tokens"].append([w.text for w in tokenized_terms]) dataset["start"].append(0) dataset["end"].append(len(tokenized_terms)) dataset["label"].append(label_names.index(cat)) osr -= 1 if args.label_balance: span_num = dict_label_count.most_common()[0][1] else: span_num = sum(dict_label_count.values()) o_labeled_spans = load_o_label_spans(unlabelled_corpus, span_num) for span in o_labeled_spans: dataset["tokens"].append(span) dataset["start"].append(0) dataset["end"].append(len(span)) dataset["label"].append(label_names.index("O")) features = datasets.Features( { "tokens": datasets.Sequence(datasets.Value("string")), "start": datasets.Value("int32"), "end": datasets.Value("int32"), "label": datasets.ClassLabel(names=label_names), } ) return Dataset.from_dict(dataset, features=features) def split_span_classification_dataset(datasets: Dataset): features = datasets.features split_num = int(len(datasets) * 0.9) splitted_datasets = dict() from random import shuffle indexes = list(range(len(datasets))) shuffle(indexes) splitted_datasets["train"] = Dataset.from_dict( datasets.__getitem__(indexes[:split_num]), features=features ) splitted_datasets["validation"] = Dataset.from_dict( datasets.__getitem__(indexes[split_num:]), features=features ) return DatasetDict(splitted_datasets) def join_span_classification_datasets( main_datasets: DatasetDict, sub_datasets: DatasetDict ): pass new_dataset_dict = dict() for key, split in main_datasets.items(): if key in sub_datasets: sub_split = sub_datasets[key] new_dataset = {feature: split[feature] for feature in split.features} main_label_names = split.features["label"].names sub_label_names = sub_split.features["label"].names assert len(main_label_names) == len(sub_label_names) assert len(split.features) == len(sub_split.features) label_map = { i: sub_label_names.index(l) for i, l in enumerate(main_label_names) } for feature in sub_split.features: if feature == "label": new_dataset[feature] += [label_map[l] for l in sub_split[feature]] else: new_dataset[feature] += sub_split[feature] new_dataset_dict[key] = Dataset.from_dict(new_dataset, split.features) else: new_dataset_dict[key] = split return DatasetDict(new_dataset_dict) def log_label_ratio(msc_datasets: DatasetDict): table = prettytable.PrettyTable(["Label", "Count", "Ratio (%)"]) pass train_dataset = msc_datasets["train"] label_names = train_dataset.features["labels"].feature.names c = Counter([label for snt in train_dataset["labels"] for label in snt]) label_sum = sum(c.values()) for lid, count in c.most_common(): table.add_row([label_names[lid], count, "%.2f" % (100 * count / label_sum)]) logger.info(table.get_string()) def translate_into_msc_datasets( ner_datasets: DatasetDict, msc_args: MSCConfig, enumerator: Chunker, ): input_hash = {k: v._fingerprint for k, v in ner_datasets.items()} input_hash["msc_args"] = str(msc_args) input_hash["enumerator"] = str(enumerator.config) output_dir = Path(get_original_cwd()).joinpath( "data", "buffer", md5(str(input_hash).encode()).hexdigest() ) logger.info("output_dir of msc_datasets: " + str(output_dir)) if not output_dir.exists(): msc_datasets = ner_datasets_to_span_classification_datasets( ner_datasets, msc_args, enumerator ) msc_datasets.save_to_disk(output_dir) else: msc_datasets = DatasetDict.load_from_disk(output_dir) log_label_ratio(msc_datasets) return msc_datasets
true
true
f72ca25004c0c4905aca487d4e9c73657cbe9a5d
482
py
Python
app/http/middleware/HelloWorldMiddleware.py
llaski/masonite-tutorial
f89dc88ccf7924b477dfe971fdb981a82e63d5fe
[ "MIT" ]
null
null
null
app/http/middleware/HelloWorldMiddleware.py
llaski/masonite-tutorial
f89dc88ccf7924b477dfe971fdb981a82e63d5fe
[ "MIT" ]
1
2021-06-02T00:33:40.000Z
2021-06-02T00:33:40.000Z
app/http/middleware/HelloWorldMiddleware.py
llaski/masonite-tutorial
f89dc88ccf7924b477dfe971fdb981a82e63d5fe
[ "MIT" ]
null
null
null
"""HelloWorld Middleware.""" from masonite.request import Request class HelloWorldMiddleware: """HelloWorld Middleware.""" def __init__(self, request: Request): """Inject Any Dependencies From The Service Container. Arguments: Request {masonite.request.Request} -- The Masonite request object """ self.request = request def before(self): print('Hello World') def after(self): print('Goodbye World')
21.909091
77
0.636929
from masonite.request import Request class HelloWorldMiddleware: def __init__(self, request: Request): self.request = request def before(self): print('Hello World') def after(self): print('Goodbye World')
true
true
f72ca260e47ced61e897e70195c321f15e9d783d
3,962
py
Python
misc/learnpy/k-means/loadiris.py
mutazag/mdsi
efecc8f650ddf6866154389f98d4ce0a9803db18
[ "MIT" ]
null
null
null
misc/learnpy/k-means/loadiris.py
mutazag/mdsi
efecc8f650ddf6866154389f98d4ce0a9803db18
[ "MIT" ]
null
null
null
misc/learnpy/k-means/loadiris.py
mutazag/mdsi
efecc8f650ddf6866154389f98d4ce0a9803db18
[ "MIT" ]
null
null
null
import pandas as pd from sklearn import datasets # load iris data set iris = datasets.load_iris() print(iris) species = [iris.target_names[x] for x in iris.target] iris = pd.DataFrame(iris['data'], columns = ['Sepal_Length', 'Sepal_Width', 'Petal_Length', 'Petal_Width']) iris['Species'] = species iris.head() iris.dtypes # quick count iris['count'] = 1 iris[['Species', 'count']].groupby('Species').count() iris.groupby('Species').count() # plot the data set # %matplotlib inline def plot_iris(iris, col1, col2): print("plot_iris") import seaborn as sns import matplotlib.pyplot as plt sns.lmplot(x = col1, y=col2, data = iris, hue = "Species", fit_reg=False) plt.xlabel(col1) plt.ylabel(col2) plt.title('Iris species show by color') plt.show() plot_iris(iris, 'Petal_Width', 'Sepal_Length') plot_iris(iris, 'Sepal_Width', 'Sepal_Length') # preparing numeric featurs by scaling from sklearn.preprocessing import scale import pandas as pd num_cols = ['Sepal_Length', 'Sepal_Width', 'Petal_Length', 'Petal_Width'] iris_scaled = scale(iris[num_cols]) iris_scaled = pd.DataFrame(iris_scaled, columns = num_cols) print(iris_scaled.describe().round(3)) # coding string col 'species' as numeric using a dictionary levels = {'setosa':0, 'versicolor':1, 'virginica':2} # add coded species to the new scaled iris data frame iris_scaled['Species'] = [levels[x] for x in iris['Species']] iris_scaled.head() plot_iris(iris_scaled, 'Sepal_Width', 'Sepal_Length') ## split the data into training and tes using Bernoulli sampling from sklearn.model_selection import train_test_split import numpy as np np.random.seed(3456) iris_split = train_test_split(np.asmatrix(iris_scaled), test_size = 75) iris_train_features = iris_split[0][:,:4] iris_train_labels = np.ravel(iris_split[0][:,4]) iris_test_features = iris_split[1][:,:4] iris_test_labels = np.ravel(iris_split[1][:,4]) print(iris_train_features.shape) print(iris_train_labels.shape) print(iris_test_features.shape) print(iris_test_labels.shape) # Train and Eval KNN model #fit model from sklearn.neighbors import KNeighborsClassifier KNN_mod = KNeighborsClassifier(n_neighbors=3) # this is K KNN_mod.fit(iris_train_features, iris_train_labels) #test model on test data set iris_test = pd.DataFrame(iris_test_features, columns = num_cols) iris_test['predicted'] = KNN_mod.predict(iris_test_features) iris_test['actuals'] = iris_test_labels iris_test['correct'] = [1 if x == z else 0 for x, z in zip(iris_test['predicted'], iris_test_labels)] # calculate some accuracy measure accuracy = 100 * float(sum(iris_test['correct'])) / float(iris_test.shape[0]) print(accuracy) iris_test[iris_test.correct != 1] iris_test.loc[iris_test["correct"] != 1] # plotting the predicted values and highliting incorrectly classified observations levels = {0:'setosa', 1:'versicolor', 2:'virginica'} iris_test['Species'] = [levels[x] for x in iris_test['predicted']] markers = {1:'^', 0:'o'} colors = {'setosa':'blue', 'versicolor':'green', 'virginica':'red'} def plot_shapes(df, col1,col2, markers, colors): import matplotlib.pyplot as plt import seaborn as sns ax = plt.figure(figsize=(6, 6)).gca() # define plot axis for m in markers: # iterate over marker dictioary keys for c in colors: # iterate over color dictionary keys df_temp = df[(df['correct'] == m) & (df['Species'] == c)] sns.regplot(x = col1, y = col2, data = df_temp, fit_reg = False, scatter_kws={'color': colors[c]}, marker = markers[m], ax = ax) plt.xlabel(col1) plt.ylabel(col2) plt.title('Iris species by color') return 'Done' plot_shapes(iris_test, 'Petal_Width', 'Sepal_Length', markers, colors) plot_shapes(iris_test, 'Sepal_Width', 'Sepal_Length', markers, colors)
29.132353
108
0.694346
import pandas as pd from sklearn import datasets iris = datasets.load_iris() print(iris) species = [iris.target_names[x] for x in iris.target] iris = pd.DataFrame(iris['data'], columns = ['Sepal_Length', 'Sepal_Width', 'Petal_Length', 'Petal_Width']) iris['Species'] = species iris.head() iris.dtypes iris['count'] = 1 iris[['Species', 'count']].groupby('Species').count() iris.groupby('Species').count() def plot_iris(iris, col1, col2): print("plot_iris") import seaborn as sns import matplotlib.pyplot as plt sns.lmplot(x = col1, y=col2, data = iris, hue = "Species", fit_reg=False) plt.xlabel(col1) plt.ylabel(col2) plt.title('Iris species show by color') plt.show() plot_iris(iris, 'Petal_Width', 'Sepal_Length') plot_iris(iris, 'Sepal_Width', 'Sepal_Length') from sklearn.preprocessing import scale import pandas as pd num_cols = ['Sepal_Length', 'Sepal_Width', 'Petal_Length', 'Petal_Width'] iris_scaled = scale(iris[num_cols]) iris_scaled = pd.DataFrame(iris_scaled, columns = num_cols) print(iris_scaled.describe().round(3)) levels = {'setosa':0, 'versicolor':1, 'virginica':2} iris_scaled['Species'] = [levels[x] for x in iris['Species']] iris_scaled.head() plot_iris(iris_scaled, 'Sepal_Width', 'Sepal_Length') mpy as np np.random.seed(3456) iris_split = train_test_split(np.asmatrix(iris_scaled), test_size = 75) iris_train_features = iris_split[0][:,:4] iris_train_labels = np.ravel(iris_split[0][:,4]) iris_test_features = iris_split[1][:,:4] iris_test_labels = np.ravel(iris_split[1][:,4]) print(iris_train_features.shape) print(iris_train_labels.shape) print(iris_test_features.shape) print(iris_test_labels.shape) from sklearn.neighbors import KNeighborsClassifier KNN_mod = KNeighborsClassifier(n_neighbors=3) KNN_mod.fit(iris_train_features, iris_train_labels) iris_test = pd.DataFrame(iris_test_features, columns = num_cols) iris_test['predicted'] = KNN_mod.predict(iris_test_features) iris_test['actuals'] = iris_test_labels iris_test['correct'] = [1 if x == z else 0 for x, z in zip(iris_test['predicted'], iris_test_labels)] accuracy = 100 * float(sum(iris_test['correct'])) / float(iris_test.shape[0]) print(accuracy) iris_test[iris_test.correct != 1] iris_test.loc[iris_test["correct"] != 1] levels = {0:'setosa', 1:'versicolor', 2:'virginica'} iris_test['Species'] = [levels[x] for x in iris_test['predicted']] markers = {1:'^', 0:'o'} colors = {'setosa':'blue', 'versicolor':'green', 'virginica':'red'} def plot_shapes(df, col1,col2, markers, colors): import matplotlib.pyplot as plt import seaborn as sns ax = plt.figure(figsize=(6, 6)).gca() for m in markers: for c in colors: df_temp = df[(df['correct'] == m) & (df['Species'] == c)] sns.regplot(x = col1, y = col2, data = df_temp, fit_reg = False, scatter_kws={'color': colors[c]}, marker = markers[m], ax = ax) plt.xlabel(col1) plt.ylabel(col2) plt.title('Iris species by color') return 'Done' plot_shapes(iris_test, 'Petal_Width', 'Sepal_Length', markers, colors) plot_shapes(iris_test, 'Sepal_Width', 'Sepal_Length', markers, colors)
true
true
f72ca2f478e2f86936751094fd9d66c1fab0a9ee
1,734
py
Python
run-gat-2-8.py
urialon/bottleneck
481fbb95edc6ae711da40b6305b40c12ce6a6d29
[ "MIT" ]
null
null
null
run-gat-2-8.py
urialon/bottleneck
481fbb95edc6ae711da40b6305b40c12ce6a6d29
[ "MIT" ]
null
null
null
run-gat-2-8.py
urialon/bottleneck
481fbb95edc6ae711da40b6305b40c12ce6a6d29
[ "MIT" ]
null
null
null
import main from common import Task, STOP, GNN_TYPE from attrdict import AttrDict from experiment import Experiment import torch override_params = { 2: {'batch_size': 64, 'eval_every': 1000}, 3: {'batch_size': 64}, 4: {'batch_size': 1024}, 5: {'batch_size': 1024}, 6: {'batch_size': 1024}, 7: {'batch_size': 2048}, 8: {'batch_size': 1024, 'accum_grad': 2}, # effective batch size of 2048, with less GPU memory } class Results: def __init__(self, train_acc, test_acc, epoch): self.train_acc = train_acc self.test_acc = test_acc self.epoch = epoch if __name__ == '__main__': task = Task.DICTIONARY gnn_type = GNN_TYPE.GAT stopping_criterion = STOP.TRAIN min_depth = 2 max_depth = 8 results_all_depths = {} for depth in range(min_depth, max_depth + 1): num_layers = depth + 1 args = main.get_fake_args(task=task, depth=depth, num_layers=num_layers, loader_workers=7, type=gnn_type, stop=stopping_criterion, no_activation=True, no_residual=False) if depth in override_params: for key, value in AttrDict(override_params[depth]).items(): args[key] = value train_acc, test_acc, epoch = Experiment(args).run() torch.cuda.empty_cache() results_all_depths[depth] = Results(train_acc=train_acc, test_acc=test_acc, epoch=epoch) print() print(f'Task: {task}') print('depth, train_acc, test_acc, epoch, train_acc, test_acc, epoch,') for depth in range(min_depth, max_depth + 1): res = results_all_depths[depth] print(f'{depth}, {res.train_acc}, {res.test_acc}, {res.epoch}')
33.346154
99
0.632641
import main from common import Task, STOP, GNN_TYPE from attrdict import AttrDict from experiment import Experiment import torch override_params = { 2: {'batch_size': 64, 'eval_every': 1000}, 3: {'batch_size': 64}, 4: {'batch_size': 1024}, 5: {'batch_size': 1024}, 6: {'batch_size': 1024}, 7: {'batch_size': 2048}, 8: {'batch_size': 1024, 'accum_grad': 2}, } class Results: def __init__(self, train_acc, test_acc, epoch): self.train_acc = train_acc self.test_acc = test_acc self.epoch = epoch if __name__ == '__main__': task = Task.DICTIONARY gnn_type = GNN_TYPE.GAT stopping_criterion = STOP.TRAIN min_depth = 2 max_depth = 8 results_all_depths = {} for depth in range(min_depth, max_depth + 1): num_layers = depth + 1 args = main.get_fake_args(task=task, depth=depth, num_layers=num_layers, loader_workers=7, type=gnn_type, stop=stopping_criterion, no_activation=True, no_residual=False) if depth in override_params: for key, value in AttrDict(override_params[depth]).items(): args[key] = value train_acc, test_acc, epoch = Experiment(args).run() torch.cuda.empty_cache() results_all_depths[depth] = Results(train_acc=train_acc, test_acc=test_acc, epoch=epoch) print() print(f'Task: {task}') print('depth, train_acc, test_acc, epoch, train_acc, test_acc, epoch,') for depth in range(min_depth, max_depth + 1): res = results_all_depths[depth] print(f'{depth}, {res.train_acc}, {res.test_acc}, {res.epoch}')
true
true
f72ca4cbe79a2f6143b41e5d9b7ad5d70a93a0a8
884
py
Python
enrich/followthemoney_enrich/cache.py
achievement008/followthemoney
bda06d62c81c82e62cd0c53117d8804939b40f62
[ "MIT" ]
137
2017-10-20T09:36:32.000Z
2022-03-24T18:49:16.000Z
enrich/followthemoney_enrich/cache.py
achievement008/followthemoney
bda06d62c81c82e62cd0c53117d8804939b40f62
[ "MIT" ]
505
2017-10-24T13:14:06.000Z
2022-03-28T20:21:45.000Z
enrich/followthemoney_enrich/cache.py
achievement008/followthemoney
bda06d62c81c82e62cd0c53117d8804939b40f62
[ "MIT" ]
32
2017-12-19T15:22:07.000Z
2022-02-18T11:01:28.000Z
import os import json from redis import Redis from normality import stringify class Cache(object): def get(self, key): return None def has(self, key): return self.get(key) is not None def store(self, key, value): pass class RedisCache(Cache): EXPIRE = 84600 * 90 URL = os.environ.get("ENRICH_REDIS_URL") def __init__(self): self.redis = Redis.from_url(self.URL) def _prefix_key(self, key): return "ftm:enrich:%s" % stringify(key) def store(self, key, value): key = self._prefix_key(key) self.redis.set(key, json.dumps(value), ex=self.EXPIRE) def get(self, key): value = self.redis.get(self._prefix_key(key)) if value is not None: return json.loads(value) def has(self, key): key = self._prefix_key(key) return self.redis.exists(key)
22.1
62
0.61991
import os import json from redis import Redis from normality import stringify class Cache(object): def get(self, key): return None def has(self, key): return self.get(key) is not None def store(self, key, value): pass class RedisCache(Cache): EXPIRE = 84600 * 90 URL = os.environ.get("ENRICH_REDIS_URL") def __init__(self): self.redis = Redis.from_url(self.URL) def _prefix_key(self, key): return "ftm:enrich:%s" % stringify(key) def store(self, key, value): key = self._prefix_key(key) self.redis.set(key, json.dumps(value), ex=self.EXPIRE) def get(self, key): value = self.redis.get(self._prefix_key(key)) if value is not None: return json.loads(value) def has(self, key): key = self._prefix_key(key) return self.redis.exists(key)
true
true
f72ca4f157e0f5d299e44df76de3bb9ba9ff45ad
13,454
py
Python
env/lib/python3.7/encodings/mac_cyrillic.py
JacobMiske/nuclear-database-APIs
bc9fb6afb9aa0d98dde5d744d8f22b2791597e78
[ "MIT" ]
null
null
null
env/lib/python3.7/encodings/mac_cyrillic.py
JacobMiske/nuclear-database-APIs
bc9fb6afb9aa0d98dde5d744d8f22b2791597e78
[ "MIT" ]
null
null
null
env/lib/python3.7/encodings/mac_cyrillic.py
JacobMiske/nuclear-database-APIs
bc9fb6afb9aa0d98dde5d744d8f22b2791597e78
[ "MIT" ]
1
2020-05-01T20:23:35.000Z
2020-05-01T20:23:35.000Z
""" Python Character Mapping Codec mac_cyrillic generated from 'MAPPINGS/VENDORS/APPLE/CYRILLIC.TXT' with gencodec.py. """#" import codecs ### Codec APIs class Codec(codecs.Codec): def encode(self,input,errors='strict'): return codecs.charmap_encode(input,errors,encoding_table) def decode(self,input,errors='strict'): return codecs.charmap_decode(input,errors,decoding_table) class IncrementalEncoder(codecs.IncrementalEncoder): def encode(self, input, final=False): return codecs.charmap_encode(input,self.errors,encoding_table)[0] class IncrementalDecoder(codecs.IncrementalDecoder): def decode(self, input, final=False): return codecs.charmap_decode(input,self.errors,decoding_table)[0] class StreamWriter(Codec,codecs.StreamWriter): pass class StreamReader(Codec,codecs.StreamReader): pass ### encodings module src def getregentry(): return codecs.CodecInfo( name='mac-cyrillic', encode=Codec().encode, decode=Codec().decode, incrementalencoder=IncrementalEncoder, incrementaldecoder=IncrementalDecoder, streamreader=StreamReader, streamwriter=StreamWriter, ) ### Decoding Table decoding_table = ( '\x00' # 0x00 -> CONTROL CHARACTER '\x01' # 0x01 -> CONTROL CHARACTER '\x02' # 0x02 -> CONTROL CHARACTER '\x03' # 0x03 -> CONTROL CHARACTER '\x04' # 0x04 -> CONTROL CHARACTER '\x05' # 0x05 -> CONTROL CHARACTER '\x06' # 0x06 -> CONTROL CHARACTER '\x07' # 0x07 -> CONTROL CHARACTER '\x08' # 0x08 -> CONTROL CHARACTER '\t' # 0x09 -> CONTROL CHARACTER '\n' # 0x0A -> CONTROL CHARACTER '\x0b' # 0x0B -> CONTROL CHARACTER '\x0c' # 0x0C -> CONTROL CHARACTER '\r' # 0x0D -> CONTROL CHARACTER '\x0e' # 0x0E -> CONTROL CHARACTER '\x0f' # 0x0F -> CONTROL CHARACTER '\x10' # 0x10 -> CONTROL CHARACTER '\x11' # 0x11 -> CONTROL CHARACTER '\x12' # 0x12 -> CONTROL CHARACTER '\x13' # 0x13 -> CONTROL CHARACTER '\x14' # 0x14 -> CONTROL CHARACTER '\x15' # 0x15 -> CONTROL CHARACTER '\x16' # 0x16 -> CONTROL CHARACTER '\x17' # 0x17 -> CONTROL CHARACTER '\x18' # 0x18 -> CONTROL CHARACTER '\x19' # 0x19 -> CONTROL CHARACTER '\x1a' # 0x1A -> CONTROL CHARACTER '\x1b' # 0x1B -> CONTROL CHARACTER '\x1c' # 0x1C -> CONTROL CHARACTER '\x1d' # 0x1D -> CONTROL CHARACTER '\x1e' # 0x1E -> CONTROL CHARACTER '\x1f' # 0x1F -> CONTROL CHARACTER ' ' # 0x20 -> SPACE '!' # 0x21 -> EXCLAMATION MARK '"' # 0x22 -> QUOTATION MARK '#' # 0x23 -> NUMBER SIGN '$' # 0x24 -> DOLLAR SIGN '%' # 0x25 -> PERCENT SIGN '&' # 0x26 -> AMPERSAND "'" # 0x27 -> APOSTROPHE '(' # 0x28 -> LEFT PARENTHESIS ')' # 0x29 -> RIGHT PARENTHESIS '*' # 0x2A -> ASTERISK '+' # 0x2B -> PLUS SIGN ',' # 0x2C -> COMMA '-' # 0x2D -> HYPHEN-MINUS '.' # 0x2E -> FULL STOP '/' # 0x2F -> SOLIDUS '0' # 0x30 -> DIGIT ZERO '1' # 0x31 -> DIGIT ONE '2' # 0x32 -> DIGIT TWO '3' # 0x33 -> DIGIT THREE '4' # 0x34 -> DIGIT FOUR '5' # 0x35 -> DIGIT FIVE '6' # 0x36 -> DIGIT SIX '7' # 0x37 -> DIGIT SEVEN '8' # 0x38 -> DIGIT EIGHT '9' # 0x39 -> DIGIT NINE ':' # 0x3A -> COLON ';' # 0x3B -> SEMICOLON '<' # 0x3C -> LESS-THAN SIGN '=' # 0x3D -> EQUALS SIGN '>' # 0x3E -> GREATER-THAN SIGN '?' # 0x3F -> QUESTION MARK '@' # 0x40 -> COMMERCIAL AT 'A' # 0x41 -> LATIN CAPITAL LETTER A 'B' # 0x42 -> LATIN CAPITAL LETTER B 'C' # 0x43 -> LATIN CAPITAL LETTER C 'D' # 0x44 -> LATIN CAPITAL LETTER D 'E' # 0x45 -> LATIN CAPITAL LETTER E 'F' # 0x46 -> LATIN CAPITAL LETTER F 'G' # 0x47 -> LATIN CAPITAL LETTER G 'H' # 0x48 -> LATIN CAPITAL LETTER H 'I' # 0x49 -> LATIN CAPITAL LETTER I 'J' # 0x4A -> LATIN CAPITAL LETTER J 'K' # 0x4B -> LATIN CAPITAL LETTER K 'L' # 0x4C -> LATIN CAPITAL LETTER L 'M' # 0x4D -> LATIN CAPITAL LETTER M 'N' # 0x4E -> LATIN CAPITAL LETTER N 'O' # 0x4F -> LATIN CAPITAL LETTER O 'P' # 0x50 -> LATIN CAPITAL LETTER P 'Q' # 0x51 -> LATIN CAPITAL LETTER Q 'R' # 0x52 -> LATIN CAPITAL LETTER R 'S' # 0x53 -> LATIN CAPITAL LETTER S 'T' # 0x54 -> LATIN CAPITAL LETTER T 'U' # 0x55 -> LATIN CAPITAL LETTER U 'V' # 0x56 -> LATIN CAPITAL LETTER V 'W' # 0x57 -> LATIN CAPITAL LETTER W 'X' # 0x58 -> LATIN CAPITAL LETTER X 'Y' # 0x59 -> LATIN CAPITAL LETTER Y 'Z' # 0x5A -> LATIN CAPITAL LETTER Z '[' # 0x5B -> LEFT SQUARE BRACKET '\\' # 0x5C -> REVERSE SOLIDUS ']' # 0x5D -> RIGHT SQUARE BRACKET '^' # 0x5E -> CIRCUMFLEX ACCENT '_' # 0x5F -> LOW LINE '`' # 0x60 -> GRAVE ACCENT 'a' # 0x61 -> LATIN SMALL LETTER A 'b' # 0x62 -> LATIN SMALL LETTER B 'c' # 0x63 -> LATIN SMALL LETTER C 'd' # 0x64 -> LATIN SMALL LETTER D 'e' # 0x65 -> LATIN SMALL LETTER E 'f' # 0x66 -> LATIN SMALL LETTER F 'g' # 0x67 -> LATIN SMALL LETTER G 'h' # 0x68 -> LATIN SMALL LETTER H 'i' # 0x69 -> LATIN SMALL LETTER I 'j' # 0x6A -> LATIN SMALL LETTER J 'k' # 0x6B -> LATIN SMALL LETTER K 'l' # 0x6C -> LATIN SMALL LETTER L 'm' # 0x6D -> LATIN SMALL LETTER M 'n' # 0x6E -> LATIN SMALL LETTER N 'o' # 0x6F -> LATIN SMALL LETTER O 'p' # 0x70 -> LATIN SMALL LETTER P 'q' # 0x71 -> LATIN SMALL LETTER Q 'r' # 0x72 -> LATIN SMALL LETTER R 's' # 0x73 -> LATIN SMALL LETTER S 't' # 0x74 -> LATIN SMALL LETTER T 'u' # 0x75 -> LATIN SMALL LETTER U 'v' # 0x76 -> LATIN SMALL LETTER V 'w' # 0x77 -> LATIN SMALL LETTER W 'x' # 0x78 -> LATIN SMALL LETTER X 'y' # 0x79 -> LATIN SMALL LETTER Y 'z' # 0x7A -> LATIN SMALL LETTER Z '{' # 0x7B -> LEFT CURLY BRACKET '|' # 0x7C -> VERTICAL LINE '}' # 0x7D -> RIGHT CURLY BRACKET '~' # 0x7E -> TILDE '\x7f' # 0x7F -> CONTROL CHARACTER '\u0410' # 0x80 -> CYRILLIC CAPITAL LETTER A '\u0411' # 0x81 -> CYRILLIC CAPITAL LETTER BE '\u0412' # 0x82 -> CYRILLIC CAPITAL LETTER VE '\u0413' # 0x83 -> CYRILLIC CAPITAL LETTER GHE '\u0414' # 0x84 -> CYRILLIC CAPITAL LETTER DE '\u0415' # 0x85 -> CYRILLIC CAPITAL LETTER IE '\u0416' # 0x86 -> CYRILLIC CAPITAL LETTER ZHE '\u0417' # 0x87 -> CYRILLIC CAPITAL LETTER ZE '\u0418' # 0x88 -> CYRILLIC CAPITAL LETTER I '\u0419' # 0x89 -> CYRILLIC CAPITAL LETTER SHORT I '\u041a' # 0x8A -> CYRILLIC CAPITAL LETTER KA '\u041b' # 0x8B -> CYRILLIC CAPITAL LETTER EL '\u041c' # 0x8C -> CYRILLIC CAPITAL LETTER EM '\u041d' # 0x8D -> CYRILLIC CAPITAL LETTER EN '\u041e' # 0x8E -> CYRILLIC CAPITAL LETTER O '\u041f' # 0x8F -> CYRILLIC CAPITAL LETTER PE '\u0420' # 0x90 -> CYRILLIC CAPITAL LETTER ER '\u0421' # 0x91 -> CYRILLIC CAPITAL LETTER ES '\u0422' # 0x92 -> CYRILLIC CAPITAL LETTER TE '\u0423' # 0x93 -> CYRILLIC CAPITAL LETTER U '\u0424' # 0x94 -> CYRILLIC CAPITAL LETTER EF '\u0425' # 0x95 -> CYRILLIC CAPITAL LETTER HA '\u0426' # 0x96 -> CYRILLIC CAPITAL LETTER TSE '\u0427' # 0x97 -> CYRILLIC CAPITAL LETTER CHE '\u0428' # 0x98 -> CYRILLIC CAPITAL LETTER SHA '\u0429' # 0x99 -> CYRILLIC CAPITAL LETTER SHCHA '\u042a' # 0x9A -> CYRILLIC CAPITAL LETTER HARD SIGN '\u042b' # 0x9B -> CYRILLIC CAPITAL LETTER YERU '\u042c' # 0x9C -> CYRILLIC CAPITAL LETTER SOFT SIGN '\u042d' # 0x9D -> CYRILLIC CAPITAL LETTER E '\u042e' # 0x9E -> CYRILLIC CAPITAL LETTER YU '\u042f' # 0x9F -> CYRILLIC CAPITAL LETTER YA '\u2020' # 0xA0 -> DAGGER '\xb0' # 0xA1 -> DEGREE SIGN '\u0490' # 0xA2 -> CYRILLIC CAPITAL LETTER GHE WITH UPTURN '\xa3' # 0xA3 -> POUND SIGN '\xa7' # 0xA4 -> SECTION SIGN '\u2022' # 0xA5 -> BULLET '\xb6' # 0xA6 -> PILCROW SIGN '\u0406' # 0xA7 -> CYRILLIC CAPITAL LETTER BYELORUSSIAN-UKRAINIAN I '\xae' # 0xA8 -> REGISTERED SIGN '\xa9' # 0xA9 -> COPYRIGHT SIGN '\u2122' # 0xAA -> TRADE MARK SIGN '\u0402' # 0xAB -> CYRILLIC CAPITAL LETTER DJE '\u0452' # 0xAC -> CYRILLIC SMALL LETTER DJE '\u2260' # 0xAD -> NOT EQUAL TO '\u0403' # 0xAE -> CYRILLIC CAPITAL LETTER GJE '\u0453' # 0xAF -> CYRILLIC SMALL LETTER GJE '\u221e' # 0xB0 -> INFINITY '\xb1' # 0xB1 -> PLUS-MINUS SIGN '\u2264' # 0xB2 -> LESS-THAN OR EQUAL TO '\u2265' # 0xB3 -> GREATER-THAN OR EQUAL TO '\u0456' # 0xB4 -> CYRILLIC SMALL LETTER BYELORUSSIAN-UKRAINIAN I '\xb5' # 0xB5 -> MICRO SIGN '\u0491' # 0xB6 -> CYRILLIC SMALL LETTER GHE WITH UPTURN '\u0408' # 0xB7 -> CYRILLIC CAPITAL LETTER JE '\u0404' # 0xB8 -> CYRILLIC CAPITAL LETTER UKRAINIAN IE '\u0454' # 0xB9 -> CYRILLIC SMALL LETTER UKRAINIAN IE '\u0407' # 0xBA -> CYRILLIC CAPITAL LETTER YI '\u0457' # 0xBB -> CYRILLIC SMALL LETTER YI '\u0409' # 0xBC -> CYRILLIC CAPITAL LETTER LJE '\u0459' # 0xBD -> CYRILLIC SMALL LETTER LJE '\u040a' # 0xBE -> CYRILLIC CAPITAL LETTER NJE '\u045a' # 0xBF -> CYRILLIC SMALL LETTER NJE '\u0458' # 0xC0 -> CYRILLIC SMALL LETTER JE '\u0405' # 0xC1 -> CYRILLIC CAPITAL LETTER DZE '\xac' # 0xC2 -> NOT SIGN '\u221a' # 0xC3 -> SQUARE ROOT '\u0192' # 0xC4 -> LATIN SMALL LETTER F WITH HOOK '\u2248' # 0xC5 -> ALMOST EQUAL TO '\u2206' # 0xC6 -> INCREMENT '\xab' # 0xC7 -> LEFT-POINTING DOUBLE ANGLE QUOTATION MARK '\xbb' # 0xC8 -> RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK '\u2026' # 0xC9 -> HORIZONTAL ELLIPSIS '\xa0' # 0xCA -> NO-BREAK SPACE '\u040b' # 0xCB -> CYRILLIC CAPITAL LETTER TSHE '\u045b' # 0xCC -> CYRILLIC SMALL LETTER TSHE '\u040c' # 0xCD -> CYRILLIC CAPITAL LETTER KJE '\u045c' # 0xCE -> CYRILLIC SMALL LETTER KJE '\u0455' # 0xCF -> CYRILLIC SMALL LETTER DZE '\u2013' # 0xD0 -> EN DASH '\u2014' # 0xD1 -> EM DASH '\u201c' # 0xD2 -> LEFT DOUBLE QUOTATION MARK '\u201d' # 0xD3 -> RIGHT DOUBLE QUOTATION MARK '\u2018' # 0xD4 -> LEFT SINGLE QUOTATION MARK '\u2019' # 0xD5 -> RIGHT SINGLE QUOTATION MARK '\xf7' # 0xD6 -> DIVISION SIGN '\u201e' # 0xD7 -> DOUBLE LOW-9 QUOTATION MARK '\u040e' # 0xD8 -> CYRILLIC CAPITAL LETTER SHORT U '\u045e' # 0xD9 -> CYRILLIC SMALL LETTER SHORT U '\u040f' # 0xDA -> CYRILLIC CAPITAL LETTER DZHE '\u045f' # 0xDB -> CYRILLIC SMALL LETTER DZHE '\u2116' # 0xDC -> NUMERO SIGN '\u0401' # 0xDD -> CYRILLIC CAPITAL LETTER IO '\u0451' # 0xDE -> CYRILLIC SMALL LETTER IO '\u044f' # 0xDF -> CYRILLIC SMALL LETTER YA '\u0430' # 0xE0 -> CYRILLIC SMALL LETTER A '\u0431' # 0xE1 -> CYRILLIC SMALL LETTER BE '\u0432' # 0xE2 -> CYRILLIC SMALL LETTER VE '\u0433' # 0xE3 -> CYRILLIC SMALL LETTER GHE '\u0434' # 0xE4 -> CYRILLIC SMALL LETTER DE '\u0435' # 0xE5 -> CYRILLIC SMALL LETTER IE '\u0436' # 0xE6 -> CYRILLIC SMALL LETTER ZHE '\u0437' # 0xE7 -> CYRILLIC SMALL LETTER ZE '\u0438' # 0xE8 -> CYRILLIC SMALL LETTER I '\u0439' # 0xE9 -> CYRILLIC SMALL LETTER SHORT I '\u043a' # 0xEA -> CYRILLIC SMALL LETTER KA '\u043b' # 0xEB -> CYRILLIC SMALL LETTER EL '\u043c' # 0xEC -> CYRILLIC SMALL LETTER EM '\u043d' # 0xED -> CYRILLIC SMALL LETTER EN '\u043e' # 0xEE -> CYRILLIC SMALL LETTER O '\u043f' # 0xEF -> CYRILLIC SMALL LETTER PE '\u0440' # 0xF0 -> CYRILLIC SMALL LETTER ER '\u0441' # 0xF1 -> CYRILLIC SMALL LETTER ES '\u0442' # 0xF2 -> CYRILLIC SMALL LETTER TE '\u0443' # 0xF3 -> CYRILLIC SMALL LETTER U '\u0444' # 0xF4 -> CYRILLIC SMALL LETTER EF '\u0445' # 0xF5 -> CYRILLIC SMALL LETTER HA '\u0446' # 0xF6 -> CYRILLIC SMALL LETTER TSE '\u0447' # 0xF7 -> CYRILLIC SMALL LETTER CHE '\u0448' # 0xF8 -> CYRILLIC SMALL LETTER SHA '\u0449' # 0xF9 -> CYRILLIC SMALL LETTER SHCHA '\u044a' # 0xFA -> CYRILLIC SMALL LETTER HARD SIGN '\u044b' # 0xFB -> CYRILLIC SMALL LETTER YERU '\u044c' # 0xFC -> CYRILLIC SMALL LETTER SOFT SIGN '\u044d' # 0xFD -> CYRILLIC SMALL LETTER E '\u044e' # 0xFE -> CYRILLIC SMALL LETTER YU '\u20ac' # 0xFF -> EURO SIGN ) ### Encoding table encoding_table=codecs.charmap_build(decoding_table)
43.681818
118
0.549353
import codecs c): def encode(self,input,errors='strict'): return codecs.charmap_encode(input,errors,encoding_table) def decode(self,input,errors='strict'): return codecs.charmap_decode(input,errors,decoding_table) class IncrementalEncoder(codecs.IncrementalEncoder): def encode(self, input, final=False): return codecs.charmap_encode(input,self.errors,encoding_table)[0] class IncrementalDecoder(codecs.IncrementalDecoder): def decode(self, input, final=False): return codecs.charmap_decode(input,self.errors,decoding_table)[0] class StreamWriter(Codec,codecs.StreamWriter): pass class StreamReader(Codec,codecs.StreamReader): pass nfo( name='mac-cyrillic', encode=Codec().encode, decode=Codec().decode, incrementalencoder=IncrementalEncoder, incrementaldecoder=IncrementalDecoder, streamreader=StreamReader, streamwriter=StreamWriter, ) '\x01' '\x02' '\x03' '\x04' '\x05' '\x06' '\x07' '\x08' '\t' '\n' '\x0b' '\x0c' '\r' '\x0e' '\x0f' '\x10' '\x11' '\x12' '\x13' '\x14' '\x15' '\x16' '\x17' '\x18' '\x19' '\x1a' '\x1b' '\x1c' '\x1d' '\x1e' '\x1f' ' ' '!' '"' # 0x22 -> QUOTATION MARK '#' # 0x23 -> NUMBER SIGN '$' # 0x24 -> DOLLAR SIGN '%' # 0x25 -> PERCENT SIGN '&' # 0x26 -> AMPERSAND "'" # 0x27 -> APOSTROPHE '(' # 0x28 -> LEFT PARENTHESIS ')' # 0x29 -> RIGHT PARENTHESIS '*' # 0x2A -> ASTERISK '+' # 0x2B -> PLUS SIGN ',' # 0x2C -> COMMA '-' # 0x2D -> HYPHEN-MINUS '.' # 0x2E -> FULL STOP '/' # 0x2F -> SOLIDUS '0' # 0x30 -> DIGIT ZERO '1' # 0x31 -> DIGIT ONE '2' # 0x32 -> DIGIT TWO '3' # 0x33 -> DIGIT THREE '4' # 0x34 -> DIGIT FOUR '5' # 0x35 -> DIGIT FIVE '6' # 0x36 -> DIGIT SIX '7' # 0x37 -> DIGIT SEVEN '8' # 0x38 -> DIGIT EIGHT '9' # 0x39 -> DIGIT NINE ':' # 0x3A -> COLON ';' # 0x3B -> SEMICOLON '<' # 0x3C -> LESS-THAN SIGN '=' # 0x3D -> EQUALS SIGN '>' # 0x3E -> GREATER-THAN SIGN '?' # 0x3F -> QUESTION MARK '@' # 0x40 -> COMMERCIAL AT 'A' # 0x41 -> LATIN CAPITAL LETTER A 'B' # 0x42 -> LATIN CAPITAL LETTER B 'C' # 0x43 -> LATIN CAPITAL LETTER C 'D' # 0x44 -> LATIN CAPITAL LETTER D 'E' # 0x45 -> LATIN CAPITAL LETTER E 'F' # 0x46 -> LATIN CAPITAL LETTER F 'G' # 0x47 -> LATIN CAPITAL LETTER G 'H' # 0x48 -> LATIN CAPITAL LETTER H 'I' # 0x49 -> LATIN CAPITAL LETTER I 'J' # 0x4A -> LATIN CAPITAL LETTER J 'K' # 0x4B -> LATIN CAPITAL LETTER K 'L' # 0x4C -> LATIN CAPITAL LETTER L 'M' # 0x4D -> LATIN CAPITAL LETTER M 'N' # 0x4E -> LATIN CAPITAL LETTER N 'O' # 0x4F -> LATIN CAPITAL LETTER O 'P' # 0x50 -> LATIN CAPITAL LETTER P 'Q' # 0x51 -> LATIN CAPITAL LETTER Q 'R' # 0x52 -> LATIN CAPITAL LETTER R 'S' # 0x53 -> LATIN CAPITAL LETTER S 'T' # 0x54 -> LATIN CAPITAL LETTER T 'U' # 0x55 -> LATIN CAPITAL LETTER U 'V' # 0x56 -> LATIN CAPITAL LETTER V 'W' # 0x57 -> LATIN CAPITAL LETTER W 'X' # 0x58 -> LATIN CAPITAL LETTER X 'Y' # 0x59 -> LATIN CAPITAL LETTER Y 'Z' # 0x5A -> LATIN CAPITAL LETTER Z '[' # 0x5B -> LEFT SQUARE BRACKET '\\' # 0x5C -> REVERSE SOLIDUS ']' # 0x5D -> RIGHT SQUARE BRACKET '^' # 0x5E -> CIRCUMFLEX ACCENT '_' # 0x5F -> LOW LINE '`' # 0x60 -> GRAVE ACCENT 'a' # 0x61 -> LATIN SMALL LETTER A 'b' # 0x62 -> LATIN SMALL LETTER B 'c' # 0x63 -> LATIN SMALL LETTER C 'd' # 0x64 -> LATIN SMALL LETTER D 'e' # 0x65 -> LATIN SMALL LETTER E 'f' # 0x66 -> LATIN SMALL LETTER F 'g' # 0x67 -> LATIN SMALL LETTER G 'h' # 0x68 -> LATIN SMALL LETTER H 'i' # 0x69 -> LATIN SMALL LETTER I 'j' # 0x6A -> LATIN SMALL LETTER J 'k' # 0x6B -> LATIN SMALL LETTER K 'l' # 0x6C -> LATIN SMALL LETTER L 'm' # 0x6D -> LATIN SMALL LETTER M 'n' # 0x6E -> LATIN SMALL LETTER N 'o' # 0x6F -> LATIN SMALL LETTER O 'p' # 0x70 -> LATIN SMALL LETTER P 'q' # 0x71 -> LATIN SMALL LETTER Q 'r' # 0x72 -> LATIN SMALL LETTER R 's' # 0x73 -> LATIN SMALL LETTER S 't' # 0x74 -> LATIN SMALL LETTER T 'u' # 0x75 -> LATIN SMALL LETTER U 'v' # 0x76 -> LATIN SMALL LETTER V 'w' # 0x77 -> LATIN SMALL LETTER W 'x' # 0x78 -> LATIN SMALL LETTER X 'y' # 0x79 -> LATIN SMALL LETTER Y 'z' # 0x7A -> LATIN SMALL LETTER Z '{' # 0x7B -> LEFT CURLY BRACKET '|' # 0x7C -> VERTICAL LINE '}' # 0x7D -> RIGHT CURLY BRACKET '~' # 0x7E -> TILDE '\x7f' # 0x7F -> CONTROL CHARACTER '\u0410' # 0x80 -> CYRILLIC CAPITAL LETTER A '\u0411' # 0x81 -> CYRILLIC CAPITAL LETTER BE '\u0412' # 0x82 -> CYRILLIC CAPITAL LETTER VE '\u0413' # 0x83 -> CYRILLIC CAPITAL LETTER GHE '\u0414' # 0x84 -> CYRILLIC CAPITAL LETTER DE '\u0415' # 0x85 -> CYRILLIC CAPITAL LETTER IE '\u0416' # 0x86 -> CYRILLIC CAPITAL LETTER ZHE '\u0417' # 0x87 -> CYRILLIC CAPITAL LETTER ZE '\u0418' # 0x88 -> CYRILLIC CAPITAL LETTER I '\u0419' # 0x89 -> CYRILLIC CAPITAL LETTER SHORT I '\u041a' # 0x8A -> CYRILLIC CAPITAL LETTER KA '\u041b' # 0x8B -> CYRILLIC CAPITAL LETTER EL '\u041c' # 0x8C -> CYRILLIC CAPITAL LETTER EM '\u041d' # 0x8D -> CYRILLIC CAPITAL LETTER EN '\u041e' # 0x8E -> CYRILLIC CAPITAL LETTER O '\u041f' # 0x8F -> CYRILLIC CAPITAL LETTER PE '\u0420' # 0x90 -> CYRILLIC CAPITAL LETTER ER '\u0421' # 0x91 -> CYRILLIC CAPITAL LETTER ES '\u0422' # 0x92 -> CYRILLIC CAPITAL LETTER TE '\u0423' # 0x93 -> CYRILLIC CAPITAL LETTER U '\u0424' # 0x94 -> CYRILLIC CAPITAL LETTER EF '\u0425' # 0x95 -> CYRILLIC CAPITAL LETTER HA '\u0426' # 0x96 -> CYRILLIC CAPITAL LETTER TSE '\u0427' # 0x97 -> CYRILLIC CAPITAL LETTER CHE '\u0428' # 0x98 -> CYRILLIC CAPITAL LETTER SHA '\u0429' # 0x99 -> CYRILLIC CAPITAL LETTER SHCHA '\u042a' # 0x9A -> CYRILLIC CAPITAL LETTER HARD SIGN '\u042b' # 0x9B -> CYRILLIC CAPITAL LETTER YERU '\u042c' # 0x9C -> CYRILLIC CAPITAL LETTER SOFT SIGN '\u042d' # 0x9D -> CYRILLIC CAPITAL LETTER E '\u042e' # 0x9E -> CYRILLIC CAPITAL LETTER YU '\u042f' # 0x9F -> CYRILLIC CAPITAL LETTER YA '\u2020' # 0xA0 -> DAGGER '\xb0' # 0xA1 -> DEGREE SIGN '\u0490' # 0xA2 -> CYRILLIC CAPITAL LETTER GHE WITH UPTURN '\xa3' # 0xA3 -> POUND SIGN '\xa7' # 0xA4 -> SECTION SIGN '\u2022' # 0xA5 -> BULLET '\xb6' # 0xA6 -> PILCROW SIGN '\u0406' # 0xA7 -> CYRILLIC CAPITAL LETTER BYELORUSSIAN-UKRAINIAN I '\xae' # 0xA8 -> REGISTERED SIGN '\xa9' # 0xA9 -> COPYRIGHT SIGN '\u2122' # 0xAA -> TRADE MARK SIGN '\u0402' # 0xAB -> CYRILLIC CAPITAL LETTER DJE '\u0452' # 0xAC -> CYRILLIC SMALL LETTER DJE '\u2260' # 0xAD -> NOT EQUAL TO '\u0403' # 0xAE -> CYRILLIC CAPITAL LETTER GJE '\u0453' # 0xAF -> CYRILLIC SMALL LETTER GJE '\u221e' # 0xB0 -> INFINITY '\xb1' # 0xB1 -> PLUS-MINUS SIGN '\u2264' # 0xB2 -> LESS-THAN OR EQUAL TO '\u2265' # 0xB3 -> GREATER-THAN OR EQUAL TO '\u0456' # 0xB4 -> CYRILLIC SMALL LETTER BYELORUSSIAN-UKRAINIAN I '\xb5' # 0xB5 -> MICRO SIGN '\u0491' # 0xB6 -> CYRILLIC SMALL LETTER GHE WITH UPTURN '\u0408' # 0xB7 -> CYRILLIC CAPITAL LETTER JE '\u0404' # 0xB8 -> CYRILLIC CAPITAL LETTER UKRAINIAN IE '\u0454' # 0xB9 -> CYRILLIC SMALL LETTER UKRAINIAN IE '\u0407' # 0xBA -> CYRILLIC CAPITAL LETTER YI '\u0457' # 0xBB -> CYRILLIC SMALL LETTER YI '\u0409' # 0xBC -> CYRILLIC CAPITAL LETTER LJE '\u0459' # 0xBD -> CYRILLIC SMALL LETTER LJE '\u040a' # 0xBE -> CYRILLIC CAPITAL LETTER NJE '\u045a' # 0xBF -> CYRILLIC SMALL LETTER NJE '\u0458' # 0xC0 -> CYRILLIC SMALL LETTER JE '\u0405' # 0xC1 -> CYRILLIC CAPITAL LETTER DZE '\xac' # 0xC2 -> NOT SIGN '\u221a' # 0xC3 -> SQUARE ROOT '\u0192' # 0xC4 -> LATIN SMALL LETTER F WITH HOOK '\u2248' # 0xC5 -> ALMOST EQUAL TO '\u2206' # 0xC6 -> INCREMENT '\xab' # 0xC7 -> LEFT-POINTING DOUBLE ANGLE QUOTATION MARK '\xbb' # 0xC8 -> RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK '\u2026' # 0xC9 -> HORIZONTAL ELLIPSIS '\xa0' # 0xCA -> NO-BREAK SPACE '\u040b' # 0xCB -> CYRILLIC CAPITAL LETTER TSHE '\u045b' # 0xCC -> CYRILLIC SMALL LETTER TSHE '\u040c' # 0xCD -> CYRILLIC CAPITAL LETTER KJE '\u045c' # 0xCE -> CYRILLIC SMALL LETTER KJE '\u0455' # 0xCF -> CYRILLIC SMALL LETTER DZE '\u2013' # 0xD0 -> EN DASH '\u2014' # 0xD1 -> EM DASH '\u201c' # 0xD2 -> LEFT DOUBLE QUOTATION MARK '\u201d' # 0xD3 -> RIGHT DOUBLE QUOTATION MARK '\u2018' # 0xD4 -> LEFT SINGLE QUOTATION MARK '\u2019' # 0xD5 -> RIGHT SINGLE QUOTATION MARK '\xf7' # 0xD6 -> DIVISION SIGN '\u201e' # 0xD7 -> DOUBLE LOW-9 QUOTATION MARK '\u040e' # 0xD8 -> CYRILLIC CAPITAL LETTER SHORT U '\u045e' # 0xD9 -> CYRILLIC SMALL LETTER SHORT U '\u040f' # 0xDA -> CYRILLIC CAPITAL LETTER DZHE '\u045f' # 0xDB -> CYRILLIC SMALL LETTER DZHE '\u2116' # 0xDC -> NUMERO SIGN '\u0401' # 0xDD -> CYRILLIC CAPITAL LETTER IO '\u0451' # 0xDE -> CYRILLIC SMALL LETTER IO '\u044f' # 0xDF -> CYRILLIC SMALL LETTER YA '\u0430' # 0xE0 -> CYRILLIC SMALL LETTER A '\u0431' # 0xE1 -> CYRILLIC SMALL LETTER BE '\u0432' # 0xE2 -> CYRILLIC SMALL LETTER VE '\u0433' # 0xE3 -> CYRILLIC SMALL LETTER GHE '\u0434' # 0xE4 -> CYRILLIC SMALL LETTER DE '\u0435' # 0xE5 -> CYRILLIC SMALL LETTER IE '\u0436' # 0xE6 -> CYRILLIC SMALL LETTER ZHE '\u0437' # 0xE7 -> CYRILLIC SMALL LETTER ZE '\u0438' # 0xE8 -> CYRILLIC SMALL LETTER I '\u0439' # 0xE9 -> CYRILLIC SMALL LETTER SHORT I '\u043a' # 0xEA -> CYRILLIC SMALL LETTER KA '\u043b' # 0xEB -> CYRILLIC SMALL LETTER EL '\u043c' # 0xEC -> CYRILLIC SMALL LETTER EM '\u043d' # 0xED -> CYRILLIC SMALL LETTER EN '\u043e' # 0xEE -> CYRILLIC SMALL LETTER O '\u043f' # 0xEF -> CYRILLIC SMALL LETTER PE '\u0440' # 0xF0 -> CYRILLIC SMALL LETTER ER '\u0441' # 0xF1 -> CYRILLIC SMALL LETTER ES '\u0442' # 0xF2 -> CYRILLIC SMALL LETTER TE '\u0443' # 0xF3 -> CYRILLIC SMALL LETTER U '\u0444' # 0xF4 -> CYRILLIC SMALL LETTER EF '\u0445' # 0xF5 -> CYRILLIC SMALL LETTER HA '\u0446' # 0xF6 -> CYRILLIC SMALL LETTER TSE '\u0447' # 0xF7 -> CYRILLIC SMALL LETTER CHE '\u0448' # 0xF8 -> CYRILLIC SMALL LETTER SHA '\u0449' # 0xF9 -> CYRILLIC SMALL LETTER SHCHA '\u044a' # 0xFA -> CYRILLIC SMALL LETTER HARD SIGN '\u044b' # 0xFB -> CYRILLIC SMALL LETTER YERU '\u044c' # 0xFC -> CYRILLIC SMALL LETTER SOFT SIGN '\u044d' # 0xFD -> CYRILLIC SMALL LETTER E '\u044e' # 0xFE -> CYRILLIC SMALL LETTER YU '\u20ac' # 0xFF -> EURO SIGN ) ### Encoding table encoding_table=codecs.charmap_build(decoding_table)
true
true
f72ca5261e26e28890b2ead99f9ab8ea92310208
9,487
py
Python
test/fb_cases_util.py
savinshynu/turbo_seti
7d756f130af5a323403affcdcb9f9bfa62325836
[ "MIT" ]
33
2017-05-09T03:31:38.000Z
2022-03-26T01:29:35.000Z
test/fb_cases_util.py
savinshynu/turbo_seti
7d756f130af5a323403affcdcb9f9bfa62325836
[ "MIT" ]
284
2018-03-13T13:57:09.000Z
2022-03-30T21:59:34.000Z
test/fb_cases_util.py
savinshynu/turbo_seti
7d756f130af5a323403affcdcb9f9bfa62325836
[ "MIT" ]
116
2017-08-08T17:27:30.000Z
2022-03-24T21:24:40.000Z
r''' Utility functions for test_fb_cases.py ''' from os import mkdir, remove from os.path import dirname from shutil import rmtree import logging import pandas as pd import numpy as np import setigen as stg from turbo_seti.find_doppler.find_doppler import FindDoppler from fb_cases_def import HERE, DEBUGGING, RTOL_DIFF, TestResultRecord, SetigenParms DF_REFERENCE = HERE + '/fb_dat_reference.txt' SEP = r'\s+' def initialize(arg_dir): r''' Recreate working directory, TESTDIR. Load result reference tables (2). ''' rmtree(arg_dir, ignore_errors=True) mkdir(arg_dir) df = pd.read_csv(DF_REFERENCE, sep=SEP, engine='python', comment='#') nrows = len(df) if nrows < 1: raise ValueError('initialize: Empty reference table') if nrows % 2 != 0: raise ValueError('initialize: Reference table row count ({}) is not divisible by 2' .format(nrows)) if DEBUGGING: print('initialize: Test case reference results: \n', df) ref_tophit_1 = [] ref_tophit_2 = [] jj = 0 while jj < nrows: record = TestResultRecord() record.fdir = int(df['fdir'][jj]) record.drsign = int(df['drsign'][jj]) record.tophit_id = int(df['tophit'][jj]) record.drate = float(df['drate'][jj]) record.snr = float(df['snr'][jj]) record.freq = float(df['freq'][jj]) record.index = int(df['index'][jj]) ref_tophit_1.append(record) if DEBUGGING: print('initialize: appended for hit_1:\n', record.to_string() ) jj += 1 del record record = TestResultRecord() record.fdir = int(df['fdir'][jj]) record.drsign = int(df['drsign'][jj]) record.tophit_id = int(df['tophit'][jj]) record.drate = float(df['drate'][jj]) record.snr = float(df['snr'][jj]) record.freq = float(df['freq'][jj]) record.index = int(df['index'][jj]) ref_tophit_2.append(record) if DEBUGGING: print('initialize: appended for hit_2:\n', record.to_string() ) jj += 1 if DEBUGGING: print('initialize: {} test cases loaded.'.format(len(ref_tophit_1))) return ref_tophit_1, ref_tophit_2 def generate_fil_file(outpath, flag_fascending, flag_sign_drift_rate): r''' Using setigen, generate a filterbank file. Parameters: outpath - full path of where to store the resultant filterbank file. flag_fascending - use an ascending (+1) or descending (-1) sequence of frequencies flag_sign_drift_rate - use a positive (+1) or negative (-1) drift rate ''' if DEBUGGING: print('generate_fil_file: flag_fascending={}, flag_sign_drift_rate={}' .format(flag_fascending, flag_sign_drift_rate)) # Set up setigne parameters stg_parms = SetigenParms() if flag_sign_drift_rate < 0: stg_parms.drift_rate_1 = -stg_parms.drift_rate_1 stg_parms.drift_rate_2 = -stg_parms.drift_rate_2 stg_parms.drift_rate_3 = -stg_parms.drift_rate_3 stg_parms.drift_rate_4 = -stg_parms.drift_rate_4 stg_parms.drift_rate_5 = -stg_parms.drift_rate_5 # Instantiate a setigen Frame object frame = stg.Frame(fchans=stg_parms.fchans, tchans=stg_parms.tchans, df=stg_parms.df, dt=stg_parms.dt, fch1=stg_parms.fch1, ascending=(flag_fascending > 0)) # Add noise to stg object. frame.add_noise(x_mean=0, x_std=stg_parms.noise_std, noise_type='gaussian') # Signal 1 will be detected. signal_1_intensity = frame.get_intensity(snr=stg_parms.snr_1) frame.add_constant_signal(f_start=frame.get_frequency(stg_parms.signal_start_1), drift_rate=stg_parms.drift_rate_1, level=signal_1_intensity, width=stg_parms.width_1, f_profile_type='gaussian') # Signal 2 will be detected. signal_2_intensity = frame.get_intensity(snr=stg_parms.snr_2) frame.add_constant_signal(f_start=frame.get_frequency(stg_parms.signal_start_2), drift_rate=stg_parms.drift_rate_2, level=signal_2_intensity, width=stg_parms.width_2, f_profile_type='gaussian') # Signal 3 is a symmetric signal with three Gaussians # that will fall below the SNR requirements. signal_3_intensity = frame.get_intensity(snr=stg_parms.snr_3) frame.add_signal(stg.constant_path(f_start=frame.get_frequency(stg_parms.signal_start_3), drift_rate=stg_parms.drift_rate_3), stg.constant_t_profile(level=1), stg.multiple_gaussian_f_profile(width=stg_parms.width_3), stg.constant_bp_profile(level=signal_3_intensity)) # Signal 4 is a symmetric signal with three Gaussians # that will be drifting too quickly. signal_4_intensity = frame.get_intensity(snr=stg_parms.snr_4) frame.add_signal(stg.constant_path(f_start=frame.get_frequency(stg_parms.signal_start_4), drift_rate=stg_parms.drift_rate_4), stg.constant_t_profile(level=1), stg.multiple_gaussian_f_profile(width=stg_parms.width_4), stg.constant_bp_profile(level=signal_4_intensity)) # Signal 5 is similar to signal 4 but drifting in the opposite direction. signal_5_intensity = frame.get_intensity(snr=stg_parms.snr_5) frame.add_signal(stg.constant_path(f_start=frame.get_frequency(stg_parms.signal_start_5), drift_rate=stg_parms.drift_rate_5), stg.constant_t_profile(level=1), stg.multiple_gaussian_f_profile(width=stg_parms.width_5), stg.constant_bp_profile(level=signal_5_intensity)) # Save the frame as a filterbank file. frame.save_fil(filename=outpath) print("generate_fil_file: generated {}".format(outpath)) del frame def make_one_dat_file(arg_path_fil, min_drift=0.0, max_drift=4.0, min_snr=25.0, remove_h5=True): r''' Make a single DAT file: * Instantiate the FindDoppler class object. * With the object, search the H5, creating the DAT file and a LOG file (not used). ''' if max_drift is None: raise ValueError('make_one_dat_file: max_drift not set') woutdir = dirname(arg_path_fil) fdop = FindDoppler(datafile=arg_path_fil, min_drift=min_drift, max_drift=max_drift, snr=min_snr, log_level_int=logging.WARNING, out_dir=woutdir) fdop.search() path_h5_file = arg_path_fil.replace('.fil', '.h5') if remove_h5: remove(path_h5_file) def get_case_results(arg_path_dat): r'''From the DAT file, extract the data for all top hits.''' df = pd.read_csv(arg_path_dat, header=None, sep=SEP, engine='python', comment='#') nrows = len(df) if nrows != 2: raise ValueError('get_case_results: Expected 2 rows in DAT but observed {} rows' .format(nrows)) obs_tophit_1 = TestResultRecord() obs_tophit_1.tophit_id = int(df[0][0]) # 1st col, 1st row obs_tophit_1.drate = float(df[1][0]) obs_tophit_1.snr = float(df[2][0]) obs_tophit_1.freq = float(df[4][0]) obs_tophit_1.index = int(df[5][0]) obs_tophit_2 = TestResultRecord() obs_tophit_2.tophit_id = int(df[0][1]) # 1st col, 2nd row obs_tophit_2.drate = float(df[1][1]) obs_tophit_2.snr = float(df[2][1]) obs_tophit_2.freq = float(df[4][1]) obs_tophit_2.index = int(df[5][1]) return obs_tophit_1, obs_tophit_2 def case_comparison(obs_tophit, ref_tophit, max_drift): r'''Compare DAT file observations to the reference.''' if obs_tophit is None: if ref_tophit is None: return # success, both None # ref_tophit defined, obs_tophit is None raise ValueError('case_comparison: FAILED, max_drift={}\nobs_tophit is None\nref_tophit:::{}' .format(max_drift, ref_tophit.to_string())) if ref_tophit is None: # obs_tophit defined, ref_tophit is None raise ValueError('case_comparison: FAILED, max_drift={}\nref_tophit is None\nobs_tophit:::{}' .format(max_drift, obs_tophit.to_string())) if obs_tophit.tophit_id == ref_tophit.tophit_id \ and np.isclose(obs_tophit.drate, ref_tophit.drate, rtol=RTOL_DIFF) \ and np.isclose(obs_tophit.snr, ref_tophit.snr, rtol=RTOL_DIFF) \ and np.isclose(obs_tophit.freq, ref_tophit.freq, rtol=RTOL_DIFF) \ and obs_tophit.index == ref_tophit.index: return # success # Some field(s) did not compare correctly. raise ValueError('case_comparison: FAILED, max_drift={}\nobs_tophit:::{}\nref_tophit:::{}' .format(max_drift, obs_tophit.to_string(), ref_tophit.to_string())) if __name__ == '__main__': # __main__ is a developer unit test, not normally to be executed. from fb_cases_def import TESTDIR, PATH_FIL_FILE, MIN_SNR rmtree(TESTDIR, ignore_errors=True) mkdir(TESTDIR) generate_fil_file(PATH_FIL_FILE, -1, -1) make_one_dat_file(PATH_FIL_FILE, max_drift=5, min_snr=MIN_SNR)
41.792952
101
0.64288
from os import mkdir, remove from os.path import dirname from shutil import rmtree import logging import pandas as pd import numpy as np import setigen as stg from turbo_seti.find_doppler.find_doppler import FindDoppler from fb_cases_def import HERE, DEBUGGING, RTOL_DIFF, TestResultRecord, SetigenParms DF_REFERENCE = HERE + '/fb_dat_reference.txt' SEP = r'\s+' def initialize(arg_dir): rmtree(arg_dir, ignore_errors=True) mkdir(arg_dir) df = pd.read_csv(DF_REFERENCE, sep=SEP, engine='python', comment='#') nrows = len(df) if nrows < 1: raise ValueError('initialize: Empty reference table') if nrows % 2 != 0: raise ValueError('initialize: Reference table row count ({}) is not divisible by 2' .format(nrows)) if DEBUGGING: print('initialize: Test case reference results: \n', df) ref_tophit_1 = [] ref_tophit_2 = [] jj = 0 while jj < nrows: record = TestResultRecord() record.fdir = int(df['fdir'][jj]) record.drsign = int(df['drsign'][jj]) record.tophit_id = int(df['tophit'][jj]) record.drate = float(df['drate'][jj]) record.snr = float(df['snr'][jj]) record.freq = float(df['freq'][jj]) record.index = int(df['index'][jj]) ref_tophit_1.append(record) if DEBUGGING: print('initialize: appended for hit_1:\n', record.to_string() ) jj += 1 del record record = TestResultRecord() record.fdir = int(df['fdir'][jj]) record.drsign = int(df['drsign'][jj]) record.tophit_id = int(df['tophit'][jj]) record.drate = float(df['drate'][jj]) record.snr = float(df['snr'][jj]) record.freq = float(df['freq'][jj]) record.index = int(df['index'][jj]) ref_tophit_2.append(record) if DEBUGGING: print('initialize: appended for hit_2:\n', record.to_string() ) jj += 1 if DEBUGGING: print('initialize: {} test cases loaded.'.format(len(ref_tophit_1))) return ref_tophit_1, ref_tophit_2 def generate_fil_file(outpath, flag_fascending, flag_sign_drift_rate): if DEBUGGING: print('generate_fil_file: flag_fascending={}, flag_sign_drift_rate={}' .format(flag_fascending, flag_sign_drift_rate)) stg_parms = SetigenParms() if flag_sign_drift_rate < 0: stg_parms.drift_rate_1 = -stg_parms.drift_rate_1 stg_parms.drift_rate_2 = -stg_parms.drift_rate_2 stg_parms.drift_rate_3 = -stg_parms.drift_rate_3 stg_parms.drift_rate_4 = -stg_parms.drift_rate_4 stg_parms.drift_rate_5 = -stg_parms.drift_rate_5 frame = stg.Frame(fchans=stg_parms.fchans, tchans=stg_parms.tchans, df=stg_parms.df, dt=stg_parms.dt, fch1=stg_parms.fch1, ascending=(flag_fascending > 0)) frame.add_noise(x_mean=0, x_std=stg_parms.noise_std, noise_type='gaussian') signal_1_intensity = frame.get_intensity(snr=stg_parms.snr_1) frame.add_constant_signal(f_start=frame.get_frequency(stg_parms.signal_start_1), drift_rate=stg_parms.drift_rate_1, level=signal_1_intensity, width=stg_parms.width_1, f_profile_type='gaussian') signal_2_intensity = frame.get_intensity(snr=stg_parms.snr_2) frame.add_constant_signal(f_start=frame.get_frequency(stg_parms.signal_start_2), drift_rate=stg_parms.drift_rate_2, level=signal_2_intensity, width=stg_parms.width_2, f_profile_type='gaussian') signal_3_intensity = frame.get_intensity(snr=stg_parms.snr_3) frame.add_signal(stg.constant_path(f_start=frame.get_frequency(stg_parms.signal_start_3), drift_rate=stg_parms.drift_rate_3), stg.constant_t_profile(level=1), stg.multiple_gaussian_f_profile(width=stg_parms.width_3), stg.constant_bp_profile(level=signal_3_intensity)) signal_4_intensity = frame.get_intensity(snr=stg_parms.snr_4) frame.add_signal(stg.constant_path(f_start=frame.get_frequency(stg_parms.signal_start_4), drift_rate=stg_parms.drift_rate_4), stg.constant_t_profile(level=1), stg.multiple_gaussian_f_profile(width=stg_parms.width_4), stg.constant_bp_profile(level=signal_4_intensity)) signal_5_intensity = frame.get_intensity(snr=stg_parms.snr_5) frame.add_signal(stg.constant_path(f_start=frame.get_frequency(stg_parms.signal_start_5), drift_rate=stg_parms.drift_rate_5), stg.constant_t_profile(level=1), stg.multiple_gaussian_f_profile(width=stg_parms.width_5), stg.constant_bp_profile(level=signal_5_intensity)) frame.save_fil(filename=outpath) print("generate_fil_file: generated {}".format(outpath)) del frame def make_one_dat_file(arg_path_fil, min_drift=0.0, max_drift=4.0, min_snr=25.0, remove_h5=True): if max_drift is None: raise ValueError('make_one_dat_file: max_drift not set') woutdir = dirname(arg_path_fil) fdop = FindDoppler(datafile=arg_path_fil, min_drift=min_drift, max_drift=max_drift, snr=min_snr, log_level_int=logging.WARNING, out_dir=woutdir) fdop.search() path_h5_file = arg_path_fil.replace('.fil', '.h5') if remove_h5: remove(path_h5_file) def get_case_results(arg_path_dat): df = pd.read_csv(arg_path_dat, header=None, sep=SEP, engine='python', comment='#') nrows = len(df) if nrows != 2: raise ValueError('get_case_results: Expected 2 rows in DAT but observed {} rows' .format(nrows)) obs_tophit_1 = TestResultRecord() obs_tophit_1.tophit_id = int(df[0][0]) obs_tophit_1.drate = float(df[1][0]) obs_tophit_1.snr = float(df[2][0]) obs_tophit_1.freq = float(df[4][0]) obs_tophit_1.index = int(df[5][0]) obs_tophit_2 = TestResultRecord() obs_tophit_2.tophit_id = int(df[0][1]) obs_tophit_2.drate = float(df[1][1]) obs_tophit_2.snr = float(df[2][1]) obs_tophit_2.freq = float(df[4][1]) obs_tophit_2.index = int(df[5][1]) return obs_tophit_1, obs_tophit_2 def case_comparison(obs_tophit, ref_tophit, max_drift): if obs_tophit is None: if ref_tophit is None: return raise ValueError('case_comparison: FAILED, max_drift={}\nobs_tophit is None\nref_tophit:::{}' .format(max_drift, ref_tophit.to_string())) if ref_tophit is None: raise ValueError('case_comparison: FAILED, max_drift={}\nref_tophit is None\nobs_tophit:::{}' .format(max_drift, obs_tophit.to_string())) if obs_tophit.tophit_id == ref_tophit.tophit_id \ and np.isclose(obs_tophit.drate, ref_tophit.drate, rtol=RTOL_DIFF) \ and np.isclose(obs_tophit.snr, ref_tophit.snr, rtol=RTOL_DIFF) \ and np.isclose(obs_tophit.freq, ref_tophit.freq, rtol=RTOL_DIFF) \ and obs_tophit.index == ref_tophit.index: return raise ValueError('case_comparison: FAILED, max_drift={}\nobs_tophit:::{}\nref_tophit:::{}' .format(max_drift, obs_tophit.to_string(), ref_tophit.to_string())) if __name__ == '__main__': from fb_cases_def import TESTDIR, PATH_FIL_FILE, MIN_SNR rmtree(TESTDIR, ignore_errors=True) mkdir(TESTDIR) generate_fil_file(PATH_FIL_FILE, -1, -1) make_one_dat_file(PATH_FIL_FILE, max_drift=5, min_snr=MIN_SNR)
true
true
f72ca647ec6c0d280fd1a1ba4d668d4a17a782b2
5,517
py
Python
backend/course/migrations/0001_initial.py
crowdbotics-apps/utawala-main-altar-29305
f450b7e301bc63a8400e7a9b0e39f4b7f931e2fd
[ "FTL", "AML", "RSA-MD" ]
null
null
null
backend/course/migrations/0001_initial.py
crowdbotics-apps/utawala-main-altar-29305
f450b7e301bc63a8400e7a9b0e39f4b7f931e2fd
[ "FTL", "AML", "RSA-MD" ]
null
null
null
backend/course/migrations/0001_initial.py
crowdbotics-apps/utawala-main-altar-29305
f450b7e301bc63a8400e7a9b0e39f4b7f931e2fd
[ "FTL", "AML", "RSA-MD" ]
null
null
null
# Generated by Django 2.2.24 on 2021-07-31 08:35 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Category', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=256)), ], ), migrations.CreateModel( name='Course', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('title', models.CharField(blank=True, max_length=256, null=True)), ('description', models.TextField(blank=True, null=True)), ('author', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='course_author', to=settings.AUTH_USER_MODEL)), ('categories', models.ManyToManyField(blank=True, related_name='course_categories', to='course.Category')), ], ), migrations.CreateModel( name='Event', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=256)), ('date', models.DateTimeField()), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='event_user', to=settings.AUTH_USER_MODEL)), ], ), migrations.CreateModel( name='Group', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=256)), ], ), migrations.CreateModel( name='SubscriptionType', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=256)), ], ), migrations.CreateModel( name='Subscription', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('subscription_type', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='subscription_subscription_type', to='course.SubscriptionType')), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='subscription_user', to=settings.AUTH_USER_MODEL)), ], ), migrations.CreateModel( name='Recording', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('media', models.URLField()), ('published', models.DateTimeField()), ('event', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='recording_event', to='course.Event')), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='recording_user', to=settings.AUTH_USER_MODEL)), ], ), migrations.CreateModel( name='PaymentMethod', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('primary', models.BooleanField()), ('token', models.CharField(max_length=256)), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='paymentmethod_user', to=settings.AUTH_USER_MODEL)), ], ), migrations.CreateModel( name='Module', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('title', models.CharField(max_length=256)), ('description', models.TextField()), ('course', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='module_course', to='course.Course')), ], ), migrations.CreateModel( name='Lesson', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('title', models.CharField(max_length=256)), ('description', models.TextField()), ('media', models.URLField()), ('module', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='lesson_module', to='course.Module')), ], ), migrations.CreateModel( name='Enrollment', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('course', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='enrollment_course', to='course.Course')), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='enrollment_user', to=settings.AUTH_USER_MODEL)), ], ), ]
49.258929
179
0.595251
from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Category', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=256)), ], ), migrations.CreateModel( name='Course', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('title', models.CharField(blank=True, max_length=256, null=True)), ('description', models.TextField(blank=True, null=True)), ('author', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='course_author', to=settings.AUTH_USER_MODEL)), ('categories', models.ManyToManyField(blank=True, related_name='course_categories', to='course.Category')), ], ), migrations.CreateModel( name='Event', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=256)), ('date', models.DateTimeField()), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='event_user', to=settings.AUTH_USER_MODEL)), ], ), migrations.CreateModel( name='Group', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=256)), ], ), migrations.CreateModel( name='SubscriptionType', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=256)), ], ), migrations.CreateModel( name='Subscription', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('subscription_type', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='subscription_subscription_type', to='course.SubscriptionType')), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='subscription_user', to=settings.AUTH_USER_MODEL)), ], ), migrations.CreateModel( name='Recording', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('media', models.URLField()), ('published', models.DateTimeField()), ('event', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='recording_event', to='course.Event')), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='recording_user', to=settings.AUTH_USER_MODEL)), ], ), migrations.CreateModel( name='PaymentMethod', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('primary', models.BooleanField()), ('token', models.CharField(max_length=256)), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='paymentmethod_user', to=settings.AUTH_USER_MODEL)), ], ), migrations.CreateModel( name='Module', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('title', models.CharField(max_length=256)), ('description', models.TextField()), ('course', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='module_course', to='course.Course')), ], ), migrations.CreateModel( name='Lesson', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('title', models.CharField(max_length=256)), ('description', models.TextField()), ('media', models.URLField()), ('module', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='lesson_module', to='course.Module')), ], ), migrations.CreateModel( name='Enrollment', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('course', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='enrollment_course', to='course.Course')), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='enrollment_user', to=settings.AUTH_USER_MODEL)), ], ), ]
true
true
f72ca651974209e177cd6e0b852ffe740ce4bc1b
57,027
py
Python
tensorflow/python/ipu/utils.py
DebeshJha/tensorflow-1
2b5a225c49d25273532d11c424d37ce394d7579a
[ "Apache-2.0" ]
2
2021-03-08T23:32:06.000Z
2022-01-13T03:43:49.000Z
tensorflow/python/ipu/utils.py
DebeshJha/tensorflow-1
2b5a225c49d25273532d11c424d37ce394d7579a
[ "Apache-2.0" ]
null
null
null
tensorflow/python/ipu/utils.py
DebeshJha/tensorflow-1
2b5a225c49d25273532d11c424d37ce394d7579a
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 The TensorFlow Authors. 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. # ============================================================================= """ General utilities ~~~~~~~~~~~~~~~~~ """ import collections from enum import Enum import os import time import numpy as np from tensorflow.compiler.plugin.poplar.driver.config_pb2 import IpuOptions from tensorflow.compiler.plugin.poplar.driver.trace_pb2 import IpuTraceEvent from tensorflow.compiler.plugin.poplar.driver import config_pb2 from tensorflow.compiler.plugin.poplar.ops import gen_ipu_ops # pylint: disable=unused-import # These imports are only here to make it easier for the Tensorflow Wheel users # to use these functions: # ``` # from tensorflow.python import ipu # ... # ipu.utils.export_variables_from_live_session(...) # ``` from tensorflow.compiler.plugin.poplar.tools.tensorflow_weights_extractor import ( export_variables_from_live_session, export_variables_from_live_model, import_data_in_live_session, import_data_in_live_model) # pylint: enable=unused-import from tensorflow.compat.v1 import executing_eagerly from tensorflow.core.framework import attr_value_pb2 from tensorflow.python.client import session as session_lib from tensorflow.python.distribute import values from tensorflow.python.framework import ops from tensorflow.python.ops import control_flow_ops from tensorflow.python.util import deprecation from tensorflow.python.data.ops import dataset_ops from tensorflow.python.ipu import ipu_infeed_queue from tensorflow.python.ipu import dataset_extractor class SelectionOrder(Enum): """Depending on the communication pattern of the model, the order in which the IPUs are selected and mapped to shards can impact the performance. For example, given a model which executes on multiple IPUs: .. code-block:: python def sharded_graph(pa, pb, pc, pd): with ipu.scopes.ipu_shard(0): o1 = pa + pb with ipu.scopes.ipu_shard(1): o2 = o1 + pc with ipu.scopes.ipu_shard(2): o3 = o2 + pd return o3 and a typical machine with 8 Graphcore C2 cards: .. code-block:: none _______ _______ | | | | | 14 |=============| 15 | |_______| |_______| || || _______ _______ | | | | | 12 |=============| 13 | |_______| |_______| || || _______ _______ | | | | | 10 |=============| 11 | |_______| |_______| || || _______ _______ | | | | | 8 |=============| 9 | |_______| |_______| || || _______ _______ | | | | | 6 |=============| 7 | |_______| |_______| || || _______ _______ | | | | | 4 |=============| 5 | |_______| |_______| || || _______ _______ | | | | | 2 |=============| 3 | |_______| |_______| || || _______ _______ | | | | | 0 |=============| 1 | |_______| |_______| (where each numbered square represents an IPU with the given device ID and the == and || connections represent IPUs being directly connected via IPU-Links) we can see that the `ipu_shard(0)` directly communicates with `ipu_shard(1)` and that `ipu_shard(1)` directly communicates with `ipu_shard(2)`. If the shards 0, 1, 2 were mapped to IPUs 0, 1, 2 in that order, then the communication between shards 1 and 2 would not have a direct connection via an IPU-Link and would have to perform a "hop" via an IPU. If the shards 0, 1, 2 were mapped to IPUs 0, 1, 3 in that order, then the communication between shards 1 and 2 would have a direct connection via an IPU-Link which will reduce the communication cost. This Enum class is used to control the order in which the IPUs are selected. Currently, the following IPU selection orderings are supported: * `AUTO`: automatically try and select the best selection given the network. * `ZIGZAG`: follow the natural ordering of IPUs. In the above example, the IPUs would be selected in the following order: `0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15`. * `SNAKE`: select IPUs such that each consecutive shard is directly connected via IPU-Links to the shard before and after. In the above example, the IPUs would be selected in the following order: `0, 1, 3, 2, 4, 5, 7, 6, 8, 9, 11, 10, 12, 13, 15, 14`. * `HOOF`: select IPUs such that each consecutive shard is directly connected via IPU-Links to the shard before and after and the last and first shard are on the same C2 cards. In the above example, the IPUs would be selected in the following order: `0, 2, 4, 6, 8, 10, 12, 14, 15, 13, 11, 9, 7, 5, 3, 1`. The `SNAKE` and `HOOF` IPU selection orders are particularly beneficial for pipelined models. """ AUTO = config_pb2.IpuSelectionOrder.Value("AUTO") ZIGZAG = config_pb2.IpuSelectionOrder.Value("ZIGZAG") SNAKE = config_pb2.IpuSelectionOrder.Value("SNAKE") HOOF = config_pb2.IpuSelectionOrder.Value("HOOF") class ExecutionProfileType(Enum): """The execution profile type indicates the desired information in the execution profile. * `NO_PROFILE` indicates that there should be no execution profiling. * `DEVICE_PROFILE` indicates that the execution profile should contain only device wide events. * `IPU_PROFILE` indicates that the profile should contain IPU level execution events. * `TILE_PROFILE` indicates that the profile should contain Tile level execution events. """ NO_PROFILE = config_pb2.IpuExecutionProfileType.Value("NO_PROFILE") DEVICE_PROFILE = config_pb2.IpuExecutionProfileType.Value("DEVICE_PROFILE") IPU_PROFILE = config_pb2.IpuExecutionProfileType.Value("IPU_PROFILE") TILE_PROFILE = config_pb2.IpuExecutionProfileType.Value("TILE_PROFILE") class DeviceConnectionType(Enum): """Enumeration to describe the mechanism used to attach to the Poplar device. * `ALWAYS` indicates that the system will attach when configuring the device. * `ON_DEMAND` will defer connection to when the IPU is needed. * `NEVER` will never try to attach to a device. Used when compiling offline. """ ALWAYS = config_pb2.IpuDeviceConnectionType.Value("ALWAYS") ON_DEMAND = config_pb2.IpuDeviceConnectionType.Value("ON_DEMAND") NEVER = config_pb2.IpuDeviceConnectionType.Value("NEVER") def configure_ipu_system(config, device="cpu"): """Configure an IPU system. Passing an IpuOptions protobuf created by the ``create_ipu_config`` function. Args: config: An IpuOptions configuration protobuf device: The CPU device which is local to the IPU hardware Returns: None """ if not isinstance(config, config_pb2.IpuOptions): raise Exception("`config` must be an IpuOptions instance") g = ops.Graph() with g.as_default(): with ops.device(device): cfg_op = gen_ipu_ops.ipu_configure_hardware(config.SerializeToString()) with session_lib.Session(graph=g) as sess: sess.run(cfg_op) def get_ipu_config(session=None): """Get the configuration of an IPU system. Args: session: An optional session on which to execute. Returns: A list of IpuOption instances, one for each PoplarExecutor. """ configurations = None # Get the serialized output. if executing_eagerly(): assert not session, "No session is required for eager execution." configurations = gen_ipu_ops.ipu_get_configuration().numpy() else: s = session if session else session_lib.Session() configurations = s.run(gen_ipu_ops.ipu_get_configuration()) # Deserialize and determine if a valid config exists, # i.e. user has succesfully called ipu_configure_hardware. deserialized = [] valid = False for conf in configurations: # Deserialize. opt = IpuOptions() opt.ParseFromString(conf) deserialized.append(opt) valid |= len(opt.device_config) > 0 if not valid: raise RuntimeError("No IPU devices configured.") return deserialized def get_num_of_ipus_in_device(ipu_device, device="cpu"): """Get the number of physical IPUs Args: ipu_device: The IPU device for which to get the number of devices for. device: The CPU device which is local to the IPU hardware. Returns: A number of physical IPUs configured for a particular TF device. """ g = ops.Graph() with g.as_default(): with ops.device(device): cfg_op = gen_ipu_ops.ipu_get_num_devices(ipu_device) with session_lib.Session(graph=g) as sess: return sess.run(cfg_op) def running_on_ipu_model(): """ Check if XLA is configured to run on the ipu model. Returns: True if XLA is configured to run on the ipu model. False if XLA is configured to run on real hardware. """ return "--use_ipu_model" in os.environ.get("TF_POPLAR_FLAGS", "") @deprecation.deprecated_args(None, "Use set_optimization_options() instead.", "max_cross_replica_sum_buffer_size", "max_inter_ipu_copies_buffer_size") def create_ipu_config(profiling=False, enable_ipu_events=False, use_poplar_text_report=False, use_poplar_cbor_report=False, profile_execution=None, enable_poplar_serialized_graph=False, report_every_nth_execution=0, max_report_size=0x10000000, report_directory="", scheduler_selection="", always_rearrange_copies_on_the_host=False, merge_infeed_io_copies=False, disable_graph_convolution_caching=False, disable_graph_outlining=False, retain_control_dependencies=False, max_cross_replica_sum_buffer_size=0, max_inter_ipu_copies_buffer_size=0, max_scheduler_lookahead_depth=5, max_scheduler_search_space_size=64, prefetch_data_streams=True, selection_order=None, enable_experimental_remote_buffer_embedding=False): """Create an empty IPU session configuration structure. Args: profiling: Enable compilation reports, and IPU trace events. enable_ipu_events: Enable IPU trace events without poplar reports. use_poplar_text_report: Enable the Poplar textual report summary. use_poplar_cbor_report: Enable the Poplar CBOR reports. profile_execution: Include Poplar execution profiles in the execution events. Can only be enabled if `profiling` is also enabled. If set, can be `True`, 'False`, or a member of the `ExecutionProfileType` enumeration. A `True` value indicates `ExecutionProfileType.DEVICE_PROFILE`. enable_poplar_serialized_graph: Create the Poplar serialized graph and include in the IPU compilation trace events. report_every_nth_execution: Only produce an execution report on every Nth execution. 0 = One report only. max_report_size: The maximum size of Poplar profiles to include in the profile events. report_directory: When set, reports will be written to files in this directory, instead of being written into the events. The events will contain the full paths of the report files. scheduler_selection: When set, this forces the compiler to use a specific scheduler when ordering the instructions. See the documentation for a list of valid schedulers. always_rearrange_copies_on_the_host: *** Experimental Flag *** The data which is streamed to/from the device might be stored in different layouts on the device and on the host. If that is the case the rearrangment is performed on the device by default. By enabling this option the rearrangment will be performed on the host at the expense of latency. merge_infeed_io_copies: When true, this flag will merge the streamed host->device input copies into one larger copy. This may reduce the time to copy data from the host, at the expense of increasing the live tensor memory on the device. disable_graph_convolution_caching: By default, the convolution operation searches for an equivalent cached operation, and uses this instead of creating a new convolution. Setting this flag forces the creation of a new convolution. This can improve runtime at the expense of graph size. disable_graph_outlining: By default, some operations, such as matrix multiplications, which occur in the graph multiple times but with different input tensors might be optimised to reduce the total code size of the graph at the expense of the execution time. Setting this flag will disable these optimisations. This option is not valid for the convolution operation (also see disable_graph_convolution_caching) retain_control_dependencies: Deprecated. max_cross_replica_sum_buffer_size: The maximum number of bytes that can be waiting before a cross replica sum op is scheduled. max_inter_ipu_copies_buffer_size: The maximum number of bytes that can be waiting before a inter IPU copy between IPUs is scheduled. max_scheduler_lookahead_depth: The maximum distance to look into the future when considering valid schedules. max_scheduler_search_space_size: The maximum number of nodes to consider when building the tree of future schedules. prefetch_data_streams: When set to true, the prefetching of data for data streams on the host will be overlapped with execution on the IPU. selection_order: the order in which IPUs are selected and mapped to physical IPU devices when using a multi-IPU devices (see `SelectionOrder`). When not specified, then automatic selection order is used, otherwise an instance of `SelectionOrder`. enable_experimental_remote_buffer_embedding: When set to true, `HostEmbedding` will make use of poplar remote buffers. Returns: An IpuOptions configuration protobuf, suitable for passing to ``configure_ipu_system`` """ if profiling and enable_ipu_events: raise Exception( "`profiling` and `enable_ipu_events` are mutually exclusive") if retain_control_dependencies: raise Exception("`retain_control_dependencies` is deprecated") selection_order = selection_order if selection_order else SelectionOrder.AUTO profile_execution = profile_execution if profile_execution \ else ExecutionProfileType.NO_PROFILE if isinstance(profile_execution, (np.bool_, bool)): if profile_execution: profile_execution = ExecutionProfileType.DEVICE_PROFILE else: profile_execution = ExecutionProfileType.NO_PROFILE if (profile_execution != ExecutionProfileType.NO_PROFILE and not profiling): raise Exception("`profiling` is required when `profile_execution` is set") if not isinstance(profile_execution, ExecutionProfileType): raise Exception("`profile_execution` must be True, False, or an " "ExecutionProfileType instance") opts = config_pb2.IpuOptions() # Default initialize IpuOptions() attributes here. opts.creator_id = config_pb2.IpuOptionsCreator.IPU_UTILS opts.ipu_model_config.compile_ipu_code = True opts.enable_multi_slice_combiner = False opts.enable_matmul_combiner = False opts.enable_gather_simplifier = False opts.device_connection_type = DeviceConnectionType.ALWAYS.value opts.speed_size_config.allow_recompute = False # Configure IpuOptions according to the passed arguments. opts.profiling.enable_ipu_trace_events = profiling or enable_ipu_events opts.profiling.enable_compilation_trace = profiling opts.profiling.enable_io_trace = profiling opts.profiling.execution_trace_type = profile_execution.value opts.profiling.enable_poplar_reports_text = use_poplar_text_report opts.profiling.enable_poplar_reports_cbor = use_poplar_cbor_report opts.profiling.enable_poplar_graph = enable_poplar_serialized_graph opts.profiling.report_every_nth_execution = report_every_nth_execution opts.profiling.max_report_size = max_report_size opts.profiling.report_directory = report_directory opts.speed_size_config.always_rearrange_copies_on_the_host = \ always_rearrange_copies_on_the_host opts.speed_size_config.merge_infeed_io_copies = merge_infeed_io_copies opts.speed_size_config.disable_graph_convolution_caching = \ disable_graph_convolution_caching opts.speed_size_config.disable_graph_outlining = \ disable_graph_outlining opts.speed_size_config.scheduler_selection = scheduler_selection opts.max_cross_replica_sum_buffer_size = max_cross_replica_sum_buffer_size opts.max_inter_ipu_copies_buffer_size = max_inter_ipu_copies_buffer_size opts.max_scheduler_lookahead_depth = max_scheduler_lookahead_depth opts.max_scheduler_search_space_size = max_scheduler_search_space_size opts.prefetch_data_streams = prefetch_data_streams opts.selection_order = selection_order.value opts.verified_transfers.enabled = False opts = set_verification_options(opts, VerificationOptions()) opts.enable_experimental_remote_buffer_embedding = \ enable_experimental_remote_buffer_embedding return opts def set_serialization_options(opts, output_folder=""): """ Enable / disable the serialization to disk of the compiled executables. .. code-block:: python # Create a device that will save to disk all the compiled executables. opts = create_ipu_config() opts = set_serialization_options(opts, output_folder="/tmp/my_network") ipu.utils.configure_ipu_system(opts) with tf.Session() as s: ... Args: output_folder: Where to save the compiled executables. Set to "" to disable serialization. Returns: The IpuOptions configuration protobuf. """ opts.serialization_folder = output_folder return opts def set_optimization_options(opts, combine_embedding_lookups=False, combine_matmuls=False, max_cross_replica_sum_buffer_size=0, max_reduce_scatter_buffer_size=0, max_inter_ipu_copies_buffer_size=0, max_send_recv_cluster_size=0, gather_simplifier=False, triangular_solve_expander_block_size=0): """Set the IPU options related to performance / optimizations. .. code-block:: python # Create a device with fusion for multiSlices sharing the same input # enabled. opts = create_ipu_config() opts = set_optimization_options(opts, combine_embedding_lookups=True) ipu.utils.configure_ipu_system(opts) with tf.Session() as s: ... Args: combine_embedding_lookups: Fuse embedding lookups on the same tensor. This might improve performance but increase memory usage. combine_matmuls: Fuse matmul operations if they share the same weights or the same input. max_cross_replica_sum_buffer_size: The maximum number of bytes that can be waiting before a cross replica sum op is scheduled. max_reduce_scatter_buffer_size: The maximum number of bytes that can be waiting before a reduce scatter op is scheduled. max_inter_ipu_copies_buffer_size: The maximum number of bytes that can be waiting before a inter IPU copy between IPUs is scheduled. max_send_recv_cluster_size: The maximum number of bytes that can be waiting before a cluster of send/recv instructions to/from the host is scheduled. These are lowered to stream copies that can be merged by Poplar. gather_simplifier: Will enable more aggressive optimisation for embedding lookups. triangular_solve_expander_block_size: Defines size for triangular solver expander blocks. 0 - implementation defined default. Returns: The IpuOptions configuration protobuf. """ # Internally embedding lookups are implemented using multiSlice operations. opts.enable_multi_slice_combiner = combine_embedding_lookups opts.enable_matmul_combiner = combine_matmuls opts.max_cross_replica_sum_buffer_size = max_cross_replica_sum_buffer_size opts.max_reduce_scatter_buffer_size = max_reduce_scatter_buffer_size opts.max_inter_ipu_copies_buffer_size = max_inter_ipu_copies_buffer_size opts.max_send_recv_cluster_size = max_send_recv_cluster_size opts.enable_gather_simplifier = gather_simplifier opts.triangular_solve_expander_block_size = \ triangular_solve_expander_block_size return opts def set_norm_options(opts, use_stable_statistics=False): """Set the IPU options related to norms. Args: use_stable_statistics: If True, computes the mean first and subtracts the activations by it before computing the variance. The implementation with this flag set to True is slower than when set to False. Returns: The IpuOptions configuration protobuf. """ opts.use_stable_norm_statistics = use_stable_statistics return opts def set_transfer_options(opts, use_verified_transfers=False): """Set the IPU options related to Poplar data transfers. Args: opts: An IpuOptions session control protobuf. use_verified_transfers: If True, use Poplar's verified transfers. Returns: The IpuOptions configuration protobuf. """ opts.verified_transfers.enabled = use_verified_transfers return opts class KeyId: def __init__(self, key=0, start_id=-1): self.key = key self.start_id = start_id class VerificationOptions: """Store pairs of key / id to use for each type of data used in the graph. Does nothing unless verified transfers have been enabled by calling `set_transfer_options(opts, use_verified_transfers=True)` and an instance of this class has been set by calling `set_verification_options`: .. code-block:: python o = VerificationOptions() o.inputs.key = 1 o.infeeds["infeed"].key = 3 set_verification_options(opts, o) """ def __init__(self): self.inputs = KeyId() self.input_parameters = KeyId() self.outputs = KeyId() self.output_parameters = KeyId() self.infeeds = collections.defaultdict(KeyId) self.outfeeds = collections.defaultdict(KeyId) self.checkpoint_in = KeyId(0, 0) self.checkpoint_out = KeyId(0, 0) def set_verification_options(opts, verification_options): """Set the pairs or key / id to use for each type of data used in the graph when verified transfers are enabled. .. code-block:: python # Create a device which will use verified transfers with different keys. opts = create_ipu_config() opts = set_transfer_options(opts, use_verified_transfers=True) o = VerificationOptions() o.input_parameters = KeyId(1) o.infeeds["training_feed"] = KeyId(2) opts = set_verification_options(opts, o) ipu.utils.configure_ipu_system(opts) with tf.Session() as s: ... Args: opts: An IpuOptions session control protobuf. verification_options: a VerificationOptions object that contains the keys / ids to use. """ if not isinstance(verification_options, VerificationOptions): raise Exception( "`verification_options` must be of type VerificationOptions") def _cp_key_and_id(src, dst): dst.key = src.key dst.start_id = src.start_id for attr in [ "inputs", "input_parameters", "outputs", "output_parameters", "checkpoint_in", "checkpoint_out" ]: _cp_key_and_id(getattr(verification_options, attr), getattr(opts.verified_transfers, attr)) for name, options in verification_options.infeeds.items(): _cp_key_and_id(options, opts.verified_transfers.infeeds[name]) for name, options in verification_options.outfeeds.items(): _cp_key_and_id(options, opts.verified_transfers.outfeeds[name]) return opts def set_compilation_options(opts, compilation_options=None): """Set the IPU compilation options for the session. .. code-block:: python # Create a device with debug execution profile flag set to "compute_sets" opts = create_ipu_config() opts = set_compilation_options(opts, compilation_options={"debug.instrument": "true", "debug.allowOutOfMemory": "true"}) ipu.utils.configure_ipu_system(opts) with tf.Session() as s: ... Args: opts: An IpuOptions session control protobuf. compilation_options: A dictionary of poplar compilation option flags to be sent to the executor. Returns: The IpuOptions configuration protobuf, with engine compilation options set. """ if compilation_options: if not isinstance(compilation_options, dict): raise Exception("`compilation_options` must be a dictionary") for (option_name, value) in compilation_options.items(): compilation_option = opts.compilation_options.add() compilation_option.option = option_name compilation_option.value = value return opts def set_convolution_options(opts, convolution_options=None): """Set the IPU convolution options for the session. .. code-block:: python # Set "availableMemoryProportion" flag to "0.1" opts = create_ipu_config() opts = set_convolution_options(opts, convolution_options={"availableMemoryProportion": "0.1"}) ipu.utils.configure_ipu_system(opts) with tf.Session() as s: ... Args: opts: An IpuOptions session control protobuf. convolution_options: A dictionary of poplar option flags for convolutions. The "availableMemoryProportion" flag indicates the proportion of tile memory to be made available as temporary memory for convolutions (float between 0 and 1.0). Less temporary memory will generally result in a convolution that takes more cycles to complete. However, because always live memory (such as control code and vertex state) is not tracked when planning it, a convolution using less temporary memory may use more memory overall, due to an increase of always live memory. Returns: The IpuOptions configuration protobuf, with convolution options set. """ if convolution_options: if not isinstance(convolution_options, dict): raise Exception("`convolution_options` must be a dictionary") for (option_name, value) in convolution_options.items(): opt = opts.convolution_options.add() opt.option = option_name opt.value = value return opts def set_matmul_options(opts, matmul_options=None, clear_pass_type=False): """Set the IPU matrix multiplication options for the session. .. code-block:: python # Set "availableMemoryProportion" flag to "0.5" opts = create_ipu_config() opts = set_matmul_options(opts, matmul_options={"availableMemoryProportion": "0.5"}) ipu.utils.configure_ipu_system(opts) with tf.Session() as s: ... Args: opts: An IpuOptions session control protobuf. matmul_options: A dictionary containing the poplar option flag "availableMemoryProportion" for the matrix multiplication operations. It indicates the proportion of tile memory to be made available as temporary memory for the matrix multiplications (float between 0 and 1.0). Less temporary memory will generally result in a multiplication that takes more cycles to complete. However, because always live memory (like code and vertex state) is not tracked when planning it, a multiplication using less temporary memory may use more memory overall, due to an increase of always live memory. clear_pass_type: When set to True, the Pass type will not be set in the options passed to the poplar operation. Returns: The IpuOptions configuration protobuf, with matmul options set. """ if matmul_options: if not isinstance(matmul_options, dict): raise Exception("`matmul_options` must be a dictionary") for (option_name, value) in matmul_options.items(): opt = opts.matmul_options.add() opt.option = option_name opt.value = value opts.clear_matmul_pass_type = clear_pass_type return opts def set_pooling_options(opts, pooling_options=None): """Set the IPU pooling compilation options for the session. .. code-block:: python # Set "poolUseIntrospectiveMapping" flag to "false" opts = create_ipu_config() opts = set_pooling_options(opts, pooling_options={"poolUseIntrospectiveMapping": "false"}) ipu.utils.configure_ipu_system(opts) with tf.Session() as s: ... Args: opts: An IpuOptions session control protobuf. pooling_options: A dictionary of poplar option flags for the pooling operation. Returns: The IpuOptions configuration protobuf, with pooling options set. """ if pooling_options: if not isinstance(pooling_options, dict): raise Exception("`pooling_options` must be a dictionary") for (option_name, value) in pooling_options.items(): opt = opts.pooling_options.add() opt.option = option_name opt.value = value return opts @deprecation.deprecated_args( None, "report_options is deprecated, use graph_options and" " execution_options instead", "report_options") def set_report_options(opts, report_options=None, graph_options=None, execution_options=None): """Set the options used to influence Poplar graph and execution reports generation. .. code-block:: python opts = create_ipu_config() opts = set_report_options(opts, report_options={"reportOption1": "false"}, graph_options={"graphOptions": "false"}, execution_options={"executionOptions": "false"}) ipu.utils.configure_ipu_system(opts) with tf.Session() as s: ... Args: opts: An IpuOptions session control protobuf. report_options: (Deprecated) A dictionary of poplar option flags for the report generation. graph_options: A dictionary of poplar option flags for the graph report generation. execution_options: A dictionary of poplar option flags for the execution report generation. Returns: The IpuOptions configuration protobuf, with convolution options set. """ def use_report_options(): if report_options: if not isinstance(report_options, dict): raise Exception("`report_options` must be a dictionary") return report_options if not graph_options: graph_options = use_report_options() if graph_options: if not isinstance(graph_options, dict): raise Exception("`graph_options` must be a dictionary") for (option_name, value) in graph_options.items(): opt = opts.profiling.graph_options.add() opt.option = option_name opt.value = value if not execution_options: execution_options = use_report_options() if execution_options: if not isinstance(execution_options, dict): raise Exception("`execution_options` must be a dictionary") for (option_name, value) in execution_options.items(): opt = opts.profiling.execution_options.add() opt.option = option_name opt.value = value return opts def set_ipu_model_options(opts, compile_ipu_code=True): """Set the IPU Model options. Args: compile_ipu_code: Whether or not to actually compile real IPU code for modelling. Returns: The IpuOptions configuration protobuf, with IPU model options set. """ opts.ipu_model_config.compile_ipu_code = compile_ipu_code return opts @deprecation.deprecated_args( None, "Pipelining recomputation will recompute all the non-stateful operations " "when recomputation is enabled.", "allow_stateful_recompute", ) def set_recomputation_options(opts, allow_recompute=True, allow_stateful_recompute=None): # pylint: disable=unused-argument """Set re-computation options. Args: allow_recompute: Whether or not to re-compute instructions during training. If this is enabled then we will attempt to pattern match instructions/pipeline stages in the forward pass and recompute them in the backward pass to avoid having to preserve activations which increase the maximum memory liveness. Enabling this option can reduce memory usage at the expense of extra computation. Any stateful operations cannot be recomputed. allow_stateful_recompute: Deprecated. Returns: The IpuOptions configuration protobuf. """ opts.speed_size_config.allow_recompute = allow_recompute return opts def set_floating_point_behaviour_options(opts, inv=True, div0=True, oflo=True, esr=True, nanoo=True): """Set the IPU floating point control behaviour bits See the Poplar API documentation for poplar::FloatingPointBehaviour. Args: inv: If true a floating point invalid operation (defined by IEEE 754) will cause an exception. div0: If true a floating point divide by zero operation will cause an exception. oflo: If true a floating point overflow will cause an exception. esr: Enable stochastic rounding. nanoo: Enable Not-a-Number on overflow mode. """ opts.floating_point_behaviour.flags_set = True opts.floating_point_behaviour.inv = inv opts.floating_point_behaviour.div0 = div0 opts.floating_point_behaviour.oflo = oflo opts.floating_point_behaviour.esr = esr opts.floating_point_behaviour.nanoo = nanoo return opts def set_gcl_options(opts, num_io_tiles=0, gcl_options=None): """Set the IPU options for the Graphcore Communication Library. Args: num_io_tiles: Number of tiles to reserve per IPU for the GCL collective operations. gcl_options: A dictionary with options for configuring the GCL collective operations. Returns: The IpuOptions configuration protobuf. """ opts.gcl_num_io_tiles = num_io_tiles if gcl_options: if not isinstance(gcl_options, dict): raise TypeError("`gcl_options` must be a dictionary") for (option_name, value) in gcl_options.items(): opt = opts.gcl_options.add() opt.option = option_name opt.value = value return opts def auto_select_ipus(opts, num_ipus): """Configure the IPUs to be used by the session. The configuration describes a system consisting of multiple Tensorflow devices, each with control of one of more IPUs. The devices will be labeled ``/device:IPU:0``, ``/device:IPU:1`` and so on. Each device can control a specific number of IPUs, given by the ``num_ipus`` parameter. The system will automatically select IPU configurations from the available IPUs, where they match the desired number of IPUs. Examples: .. code-block:: python # Create a single device, with one IPU opts = create_ipu_config() opts = auto_select_ipus(opts, num_ipus=1) ipu.utils.configure_ipu_system(opts) with tf.Session() as s: ... .. code-block:: python # Create two devices, with 2 IPUs per device. opts = create_ipu_config() opts = auto_select_ipus(opts, num_ipus=[2,2]) ipu.utils.configure_ipu_system(opts) with tf.Session() as s: ... .. code-block:: python # Create two devices, with 1 IPU in the first device and 2 IPUs # in the second device. opts = create_ipu_config() opts = auto_select_ipus(opts, num_ipus=[1,2]) ipu.utils.configure_ipu_system(opts) with tf.Session() as s: ... Args: opts: An IpuOptions session control protobuf. num_ipus: List of IPUs per Tensorflow device Returns: The IpuOptions configuration protobuf, configured for auto-selecting a set of IPU devices. """ if opts.device_config: raise Exception("IPU devices have already been configured.") if not isinstance(num_ipus, (int, list, tuple)): raise Exception("`num_ipus` must be an integer, list or tuple.") if isinstance(num_ipus, int): dev = opts.device_config.add() dev.auto_count = num_ipus else: for n in num_ipus: dev = opts.device_config.add() dev.auto_count = n return opts def select_ipus(opts, indices): """Configure the IPUs to be used by the session. The configuration describes a system consisting of multiple Tensorflow devices, each with control of one of more IPUs. The Tensorflow devices will be labeled ``/device:IPU:0``, ``/device:IPU:1`` and so on. Each Tensorflow device uses a specific configuration consisting of one or more IPUs from the list of devices. These can be found by running the Graphcore utility ``gc-info -l``. For instance, the following listing shows the device configurations available on a system with 16 IPUs. .. code-block:: shell user@host:~$ gc-info -l Graphcore device listing: -+- Id: [0], type: [PCIe], PCI Domain: [0000:1a:00.0] -+- Id: [1], type: [PCIe], PCI Domain: [0000:1b:00.0] -+- Id: [2], type: [PCIe], PCI Domain: [0000:23:00.0] -+- Id: [3], type: [PCIe], PCI Domain: [0000:24:00.0] -+- Id: [4], type: [PCIe], PCI Domain: [0000:3d:00.0] -+- Id: [5], type: [PCIe], PCI Domain: [0000:3e:00.0] -+- Id: [6], type: [PCIe], PCI Domain: [0000:43:00.0] -+- Id: [7], type: [PCIe], PCI Domain: [0000:44:00.0] -+- Id: [8], type: [PCIe], PCI Domain: [0000:8b:00.0] -+- Id: [9], type: [PCIe], PCI Domain: [0000:8c:00.0] -+- Id: [10], type: [PCIe], PCI Domain: [0000:8e:00.0] -+- Id: [11], type: [PCIe], PCI Domain: [0000:8f:00.0] -+- Id: [12], type: [PCIe], PCI Domain: [0000:b8:00.0] -+- Id: [13], type: [PCIe], PCI Domain: [0000:b9:00.0] -+- Id: [14], type: [PCIe], PCI Domain: [0000:ba:00.0] -+- Id: [15], type: [PCIe], PCI Domain: [0000:bb:00.0] -+- Id: [16], type: [Multi IPU] |--- PCIe Id: [5], DNC Id: [0], PCI Domain: [0000:3e:00.0] |--- PCIe Id: [7], DNC Id: [1], PCI Domain: [0000:44:00.0] -+- Id: [17], type: [Multi IPU] |--- PCIe Id: [4], DNC Id: [0], PCI Domain: [0000:3d:00.0] |--- PCIe Id: [6], DNC Id: [1], PCI Domain: [0000:43:00.0] -+- Id: [18], type: [Multi IPU] |--- PCIe Id: [3], DNC Id: [0], PCI Domain: [0000:24:00.0] |--- PCIe Id: [1], DNC Id: [1], PCI Domain: [0000:1b:00.0] -+- Id: [19], type: [Multi IPU] |--- PCIe Id: [2], DNC Id: [0], PCI Domain: [0000:23:00.0] |--- PCIe Id: [0], DNC Id: [1], PCI Domain: [0000:1a:00.0] -+- Id: [20], type: [Multi IPU] |--- PCIe Id: [13], DNC Id: [0], PCI Domain: [0000:b9:00.0] |--- PCIe Id: [15], DNC Id: [1], PCI Domain: [0000:bb:00.0] -+- Id: [21], type: [Multi IPU] |--- PCIe Id: [12], DNC Id: [0], PCI Domain: [0000:b8:00.0] |--- PCIe Id: [14], DNC Id: [1], PCI Domain: [0000:ba:00.0] -+- Id: [22], type: [Multi IPU] |--- PCIe Id: [9], DNC Id: [0], PCI Domain: [0000:8c:00.0] |--- PCIe Id: [11], DNC Id: [1], PCI Domain: [0000:8f:00.0] -+- Id: [23], type: [Multi IPU] |--- PCIe Id: [10], DNC Id: [0], PCI Domain: [0000:8e:00.0] |--- PCIe Id: [8], DNC Id: [1], PCI Domain: [0000:8b:00.0] -+- Id: [24], type: [Multi IPU] |--- PCIe Id: [5], DNC Id: [0], PCI Domain: [0000:3e:00.0] |--- PCIe Id: [7], DNC Id: [1], PCI Domain: [0000:44:00.0] |--- PCIe Id: [4], DNC Id: [2], PCI Domain: [0000:3d:00.0] |--- PCIe Id: [6], DNC Id: [3], PCI Domain: [0000:43:00.0] -+- Id: [25], type: [Multi IPU] |--- PCIe Id: [3], DNC Id: [0], PCI Domain: [0000:24:00.0] |--- PCIe Id: [1], DNC Id: [1], PCI Domain: [0000:1b:00.0] |--- PCIe Id: [2], DNC Id: [2], PCI Domain: [0000:23:00.0] |--- PCIe Id: [0], DNC Id: [3], PCI Domain: [0000:1a:00.0] -+- Id: [26], type: [Multi IPU] |--- PCIe Id: [13], DNC Id: [0], PCI Domain: [0000:b9:00.0] |--- PCIe Id: [15], DNC Id: [1], PCI Domain: [0000:bb:00.0] |--- PCIe Id: [12], DNC Id: [2], PCI Domain: [0000:b8:00.0] |--- PCIe Id: [14], DNC Id: [3], PCI Domain: [0000:ba:00.0] -+- Id: [27], type: [Multi IPU] |--- PCIe Id: [9], DNC Id: [0], PCI Domain: [0000:8c:00.0] |--- PCIe Id: [11], DNC Id: [1], PCI Domain: [0000:8f:00.0] |--- PCIe Id: [10], DNC Id: [2], PCI Domain: [0000:8e:00.0] |--- PCIe Id: [8], DNC Id: [3], PCI Domain: [0000:8b:00.0] -+- Id: [28], type: [Multi IPU] |--- PCIe Id: [5], DNC Id: [0], PCI Domain: [0000:3e:00.0] |--- PCIe Id: [7], DNC Id: [1], PCI Domain: [0000:44:00.0] |--- PCIe Id: [4], DNC Id: [2], PCI Domain: [0000:3d:00.0] |--- PCIe Id: [6], DNC Id: [3], PCI Domain: [0000:43:00.0] |--- PCIe Id: [3], DNC Id: [4], PCI Domain: [0000:24:00.0] |--- PCIe Id: [1], DNC Id: [5], PCI Domain: [0000:1b:00.0] |--- PCIe Id: [2], DNC Id: [6], PCI Domain: [0000:23:00.0] |--- PCIe Id: [0], DNC Id: [7], PCI Domain: [0000:1a:00.0] -+- Id: [29], type: [Multi IPU] |--- PCIe Id: [13], DNC Id: [0], PCI Domain: [0000:b9:00.0] |--- PCIe Id: [15], DNC Id: [1], PCI Domain: [0000:bb:00.0] |--- PCIe Id: [12], DNC Id: [2], PCI Domain: [0000:b8:00.0] |--- PCIe Id: [14], DNC Id: [3], PCI Domain: [0000:ba:00.0] |--- PCIe Id: [9], DNC Id: [4], PCI Domain: [0000:8c:00.0] |--- PCIe Id: [11], DNC Id: [5], PCI Domain: [0000:8f:00.0] |--- PCIe Id: [10], DNC Id: [6], PCI Domain: [0000:8e:00.0] |--- PCIe Id: [8], DNC Id: [7], PCI Domain: [0000:8b:00.0] -+- Id: [30], type: [Multi IPU] |--- PCIe Id: [5], DNC Id: [0], PCI Domain: [0000:3e:00.0] |--- PCIe Id: [7], DNC Id: [1], PCI Domain: [0000:44:00.0] |--- PCIe Id: [4], DNC Id: [2], PCI Domain: [0000:3d:00.0] |--- PCIe Id: [6], DNC Id: [3], PCI Domain: [0000:43:00.0] |--- PCIe Id: [3], DNC Id: [4], PCI Domain: [0000:24:00.0] |--- PCIe Id: [1], DNC Id: [5], PCI Domain: [0000:1b:00.0] |--- PCIe Id: [2], DNC Id: [6], PCI Domain: [0000:23:00.0] |--- PCIe Id: [0], DNC Id: [7], PCI Domain: [0000:1a:00.0] |--- PCIe Id: [13], DNC Id: [8], PCI Domain: [0000:b9:00.0] |--- PCIe Id: [15], DNC Id: [9], PCI Domain: [0000:bb:00.0] |--- PCIe Id: [12], DNC Id: [10], PCI Domain: [0000:b8:00.0] |--- PCIe Id: [14], DNC Id: [11], PCI Domain: [0000:ba:00.0] |--- PCIe Id: [9], DNC Id: [12], PCI Domain: [0000:8c:00.0] |--- PCIe Id: [11], DNC Id: [13], PCI Domain: [0000:8f:00.0] |--- PCIe Id: [10], DNC Id: [14], PCI Domain: [0000:8e:00.0] |--- PCIe Id: [8], DNC Id: [15], PCI Domain: [0000:8b:00.0] Examples based on the listing above: .. code-block:: python # Create a single device with 1 IPU at PCI address 0000:1a:00.0 by using # IPU configuration index 0 opts = create_ipu_config() opts = select_ipus(opts, indices=[0]) ipu.utils.configure_ipu_system(opts) with tf.Session() as s: ... .. code-block:: python # Create a single device with 1 IPU at PCI address 0000:8b:00.0 by using # IPU configuration index 8 opts = create_ipu_config() opts = select_ipus(opts, indices=[8]) ipu.utils.configure_ipu_system(opts) with tf.Session() as s: ... .. code-block:: python # Create two TensorFlow devices, with one IPU each, being devices at # indices 0 and 1 opts = create_ipu_config() opts = select_ipus(opts, indices=[0, 1]) ipu.utils.configure_ipu_system(opts) with tf.Session() as s: ... .. code-block:: python # Create two TensorFlow devices, with four IPUs each. The device # configurations at indices 24 (0000:3e:00.0, 0000:44:00.0, 0000:3d:00.0, # 000:43:00.0) and 25 (0000:24:00.0, 0000:1b:00.0, 0000:23:00.0, # 00:1a:00.0) opts = create_ipu_config() opts = select_ipus(opts, indices=[24, 25]) ipu.utils.configure_ipu_system(opts) with tf.Session() as s: ... .. code-block:: python # Create four TensorFlow devices each with one IPU, at addresses # 0000:1a:00.0, 0000:1b:00.0, 0000:23:00.0, 0000:24:00.0. opts = create_ipu_config() opts = select_ipus(opts, indices=[0, 1, 2, 3]) ipu.utils.configure_ipu_system(opts) with tf.Session() as s: ... Args: opts: An IpuOptions session control protobuf. indices: List of IPU configuration indices. Returns: The IpuOptions configuration protobuf, with a number of devices selected by IPU configuration index. """ if opts.device_config: raise Exception("IPU devices have already been configured.") if not isinstance(indices, (list, tuple)): raise Exception("`indices` must be a list or tuple.") if len(set(indices)) != len(indices): raise Exception("All device indeicies in `indices` must be unique.") for i in indices: dev = opts.device_config.add() dev.cfg_index = i return opts def set_ipu_connection_type(opts, connection_type=None, ipu_version=None): """ Configure when to attach to the device. .. code-block:: python # Compile without attaching to the device. opts = create_ipu_config() opts = set_ipu_connection_type(opts, DeviceConnectionType.ON_DEMAND)) ipu.utils.configure_ipu_system(opts) with tf.Session() as s: ... Args: opts: An IpuOptions session control protobuf. connection_type: One of `DeviceConnectionType`. Defaults to `DeviceConnectionType.ALWAYS` if None. ipu_version: Version of the IPU hardware used. Required if the `connection_type` provided is `DeviceConnectionType.NEVER`. Returns: The IpuOptions configuration protobuf. """ connection_type = connection_type if connection_type \ else DeviceConnectionType.ALWAYS if connection_type == DeviceConnectionType.NEVER and ipu_version is None: raise Exception("`ipu_version` must be set when `connection_type` is set " "to `DeviceConnectionType.NEVER`") opts.device_connection_type = connection_type.value if ipu_version is not None: opts.ipu_version = ipu_version opts.has_ipu_version = True return opts def reset_ipu_seed(seed, device="/device:IPU:0", cpu_device="cpu"): """Reset the seed used to generate stateful random numbers and perform stochastic rounding. Args: seed: The new random number generator seed. device: The device to which the seed will be applied. cpu_device: The CPU device which is on the same hardware to the IPU device. Returns: None """ g = ops.Graph() with g.as_default(): with ops.device(cpu_device): cfg_op = gen_ipu_ops.ipu_reset_seed(device, seed) with session_lib.Session(graph=g) as sess: sess.run(cfg_op) def extract_all_strings_from_event_trace(events): """Extract a concatenation of all data strings from an IPU event trace. Args: events: An array of IPU events as returned from the ``ipu_compile_summary`` operation. Returns: A string containing the concatenation of all of the data fields of the events. """ result = "" for e in events: evt = IpuTraceEvent.FromString(e) result = result + ("-" * 70) + "\n=> @ " + \ time.strftime('%F %T %z', time.localtime(evt.timestamp)) + ": " if evt.type == IpuTraceEvent.COMPILE_BEGIN: evt_str = "Compile begin: " + \ evt.compile_begin.module_name.decode('utf-8') + "\n" elif evt.type == IpuTraceEvent.COMPILE_END: evt_str = "Compile end: " + \ evt.compile_end.module_name.decode('utf-8') + "\n" + \ "Duration: " + str(evt.compile_end.duration) + " us\n" + \ evt.compile_end.compilation_report.decode('utf-8') elif evt.type == IpuTraceEvent.HOST_TO_DEVICE_TRANSFER: evt_str = "Host->Device\n" + \ evt.data_transfer.data_transfer.decode('utf-8') + "\n" elif evt.type == IpuTraceEvent.DEVICE_TO_HOST_TRANSFER: evt_str = "Device->Host\n" + \ evt.data_transfer.data_transfer.decode('utf-8') + "\n" elif evt.type == IpuTraceEvent.LOAD_ENGINE: evt_str = "Load engine: " + \ evt.load_engine.module_name.decode('utf-8') + "\n" elif evt.type == IpuTraceEvent.EXECUTE: evt_str = "Execute: " + \ evt.execute.module_name.decode('utf-8') + "\n" + \ evt.execute.execution_report.decode('utf-8') else: evt_str = "Unknown event" result = result + evt_str + '\n' return result def extract_all_types_from_event_trace(events): """Return a list of the types of each event in an event trace tensor Args: events: A tensor containing a list of IPU events as protobuf strings Returns: A list containing the type of each event """ result = [] for e in events: evt = IpuTraceEvent.FromString(e) result += [evt.type] return result def extract_all_events(events): """Extract a list containing each event as an event object Args: events: A tensor containing a list of IPU events as protobuf strings Returns: A list containing IpuTraceEvent objects """ result = [] for e in events: evt = IpuTraceEvent.FromString(e) result += [evt] return result def extract_compile_reports(events): """Get a list of all compiler reports in the event list. Args: events: A list of trace event serialized protobufs. Returns: A list of tuples containing the module name and report.""" result = [] for e in events: evt = IpuTraceEvent.FromString(e) if evt.type == IpuTraceEvent.COMPILE_END: try: module = evt.compile_end.module_name.decode('utf-8') rep = evt.compile_end.compilation_report.decode('utf-8') if rep: result += [(module, rep)] except UnicodeDecodeError: pass return result def extract_poplar_serialized_graphs(events): """Get a list of all poplar serialized graphs in the event list. Args: events: A list of trace event serialized protobufs. Returns: A list of tuples containing the module name and report.""" result = [] for e in events: evt = IpuTraceEvent.FromString(e) if evt.type == IpuTraceEvent.COMPILE_END: try: rep = evt.compile_end.poplar_graph.decode('utf-8') except UnicodeDecodeError: rep = evt.compile_end.poplar_graph module = evt.compile_end.module_name.decode('utf-8') if rep: result += [(module, rep)] return result def extract_execute_reports(events): """Get a list of all compiler reports in the event list. Args: events: A list of trace event serialized protobufs. Returns: A list of tuples containing the module name and report.""" result = [] for e in events: evt = IpuTraceEvent.FromString(e) if evt.type == IpuTraceEvent.EXECUTE: try: module = evt.execute.module_name.decode('utf-8') rep = evt.execute.execution_report.decode('utf-8') if rep: result += [(module, rep)] except UnicodeDecodeError: pass return result def move_variable_initialization_to_cpu(graph=None): """For all variables in the VARIABLES collection, move any initialization ops onto the CPU. Args: graph: Operations are moved around on this graph. The default graph will be used if not specified. Returns: None """ if not graph: graph = ops.get_default_graph() with ops.device("/device:CPU:0"): control_flow_ops.no_op(name="cpu") variables = [] for v in graph.get_collection('variables'): # We assume a distribution strategy knows better how to # initialize its own variables, so skip those. if not isinstance(v, values.DistributedVariable): variables.append(v) def _uses_resource(op): """ Helper to determine if an op uses a resource """ return any(input_tensor.dtype == 'resource' for input_tensor in op.inputs) init_ops = [] dep_ops = [v.initializer.inputs[1].op for v in variables] visited = set() # Depth-first search up the graph starting from all variables in VARIABLES # Place all touched ops on the CPU, but do not touch or search ops that use # resource tensors, otherwise device colocation could be violated. while dep_ops: op = dep_ops.pop() if op not in visited and not _uses_resource(op): visited.add(op) init_ops += [op] dep_ops += [x.op for x in op.inputs] # pylint: disable=protected-access for op in init_ops: op._set_device('/device:CPU:0') op._set_attr( '_class', attr_value_pb2.AttrValue(list=attr_value_pb2.AttrValue.ListValue( s=[b'loc:@cpu']))) op._set_attr('_XlaCompile', attr_value_pb2.AttrValue(b=False)) op._set_attr('_XlaScope', attr_value_pb2.AttrValue(s=b'')) # pylint: enable=protected-access return def export_dataset_to_file(dataset_or_infeed, output_filename, num_elements, feed_name="", apply_options=True): """Export as binary `num_elements` from the given `infeed` to the specified `output_filename`. If the infeed elements are tuples then one file per tuple element will be created. For example, if `dataset` looks like .. code-block:: python [{ "a": A_0, "b": B_0}, { "a": A_1, "b": B_1}, ...] then `export_dataset_to_file(dataset, "my_dataset.bin", 100)` will generate: .. code-block:: python my_dataset.0.bin # Contains tensors [ A_0, A_1, ..., A_99] my_dataset.1.bin # Contains tensors [ B_0, B_1, ..., B_99] Args: dataset_or_infeed: An unary dataset with the same input and output structure or an `IPUInfeedQueue`. output_filename: Where to export the tensors to. num_elements: Number of elements to export from the dataset. feed_name: Specify the feed name. apply_options: Whether to apply optimization options which can improve the dataset performance. """ assert isinstance(dataset_or_infeed, (dataset_ops.Dataset, ipu_infeed_queue.IPUInfeedQueue)) if isinstance(dataset_or_infeed, ipu_infeed_queue.IPUInfeedQueue): dataset = dataset_or_infeed._dataset # pylint: disable=protected-access feed_name = feed_name or dataset_or_infeed._id # pylint: disable=protected-access else: dataset = dataset_or_infeed if apply_options: dataset = dataset._apply_options() # pylint: disable=protected-access extractor = dataset_extractor.dataset_extractor(dataset, num_elements, output_filename, feed_name) with ops.device("cpu"), session_lib.Session() as sess: sess.run(extractor) def export_inputs_to_file(inputs, output_filename, feed_dict): """Export as binary the list of `inputs` provided to the specified `output_filename`. Args: inputs: List of graph inputs to export. output_filename: Where to export the tensors to. feed_dict: Feed dictionary containing the inputs' values. """ with ops.device("cpu"), session_lib.Session() as sess: sess.run(dataset_extractor.export_variables(inputs, output_filename), feed_dict)
37.296926
96
0.668806
import collections from enum import Enum import os import time import numpy as np from tensorflow.compiler.plugin.poplar.driver.config_pb2 import IpuOptions from tensorflow.compiler.plugin.poplar.driver.trace_pb2 import IpuTraceEvent from tensorflow.compiler.plugin.poplar.driver import config_pb2 from tensorflow.compiler.plugin.poplar.ops import gen_ipu_ops from tensorflow.compiler.plugin.poplar.tools.tensorflow_weights_extractor import ( export_variables_from_live_session, export_variables_from_live_model, import_data_in_live_session, import_data_in_live_model) from tensorflow.compat.v1 import executing_eagerly from tensorflow.core.framework import attr_value_pb2 from tensorflow.python.client import session as session_lib from tensorflow.python.distribute import values from tensorflow.python.framework import ops from tensorflow.python.ops import control_flow_ops from tensorflow.python.util import deprecation from tensorflow.python.data.ops import dataset_ops from tensorflow.python.ipu import ipu_infeed_queue from tensorflow.python.ipu import dataset_extractor class SelectionOrder(Enum): AUTO = config_pb2.IpuSelectionOrder.Value("AUTO") ZIGZAG = config_pb2.IpuSelectionOrder.Value("ZIGZAG") SNAKE = config_pb2.IpuSelectionOrder.Value("SNAKE") HOOF = config_pb2.IpuSelectionOrder.Value("HOOF") class ExecutionProfileType(Enum): NO_PROFILE = config_pb2.IpuExecutionProfileType.Value("NO_PROFILE") DEVICE_PROFILE = config_pb2.IpuExecutionProfileType.Value("DEVICE_PROFILE") IPU_PROFILE = config_pb2.IpuExecutionProfileType.Value("IPU_PROFILE") TILE_PROFILE = config_pb2.IpuExecutionProfileType.Value("TILE_PROFILE") class DeviceConnectionType(Enum): ALWAYS = config_pb2.IpuDeviceConnectionType.Value("ALWAYS") ON_DEMAND = config_pb2.IpuDeviceConnectionType.Value("ON_DEMAND") NEVER = config_pb2.IpuDeviceConnectionType.Value("NEVER") def configure_ipu_system(config, device="cpu"): if not isinstance(config, config_pb2.IpuOptions): raise Exception("`config` must be an IpuOptions instance") g = ops.Graph() with g.as_default(): with ops.device(device): cfg_op = gen_ipu_ops.ipu_configure_hardware(config.SerializeToString()) with session_lib.Session(graph=g) as sess: sess.run(cfg_op) def get_ipu_config(session=None): configurations = None if executing_eagerly(): assert not session, "No session is required for eager execution." configurations = gen_ipu_ops.ipu_get_configuration().numpy() else: s = session if session else session_lib.Session() configurations = s.run(gen_ipu_ops.ipu_get_configuration()) deserialized = [] valid = False for conf in configurations: opt = IpuOptions() opt.ParseFromString(conf) deserialized.append(opt) valid |= len(opt.device_config) > 0 if not valid: raise RuntimeError("No IPU devices configured.") return deserialized def get_num_of_ipus_in_device(ipu_device, device="cpu"): g = ops.Graph() with g.as_default(): with ops.device(device): cfg_op = gen_ipu_ops.ipu_get_num_devices(ipu_device) with session_lib.Session(graph=g) as sess: return sess.run(cfg_op) def running_on_ipu_model(): return "--use_ipu_model" in os.environ.get("TF_POPLAR_FLAGS", "") @deprecation.deprecated_args(None, "Use set_optimization_options() instead.", "max_cross_replica_sum_buffer_size", "max_inter_ipu_copies_buffer_size") def create_ipu_config(profiling=False, enable_ipu_events=False, use_poplar_text_report=False, use_poplar_cbor_report=False, profile_execution=None, enable_poplar_serialized_graph=False, report_every_nth_execution=0, max_report_size=0x10000000, report_directory="", scheduler_selection="", always_rearrange_copies_on_the_host=False, merge_infeed_io_copies=False, disable_graph_convolution_caching=False, disable_graph_outlining=False, retain_control_dependencies=False, max_cross_replica_sum_buffer_size=0, max_inter_ipu_copies_buffer_size=0, max_scheduler_lookahead_depth=5, max_scheduler_search_space_size=64, prefetch_data_streams=True, selection_order=None, enable_experimental_remote_buffer_embedding=False): if profiling and enable_ipu_events: raise Exception( "`profiling` and `enable_ipu_events` are mutually exclusive") if retain_control_dependencies: raise Exception("`retain_control_dependencies` is deprecated") selection_order = selection_order if selection_order else SelectionOrder.AUTO profile_execution = profile_execution if profile_execution \ else ExecutionProfileType.NO_PROFILE if isinstance(profile_execution, (np.bool_, bool)): if profile_execution: profile_execution = ExecutionProfileType.DEVICE_PROFILE else: profile_execution = ExecutionProfileType.NO_PROFILE if (profile_execution != ExecutionProfileType.NO_PROFILE and not profiling): raise Exception("`profiling` is required when `profile_execution` is set") if not isinstance(profile_execution, ExecutionProfileType): raise Exception("`profile_execution` must be True, False, or an " "ExecutionProfileType instance") opts = config_pb2.IpuOptions() opts.creator_id = config_pb2.IpuOptionsCreator.IPU_UTILS opts.ipu_model_config.compile_ipu_code = True opts.enable_multi_slice_combiner = False opts.enable_matmul_combiner = False opts.enable_gather_simplifier = False opts.device_connection_type = DeviceConnectionType.ALWAYS.value opts.speed_size_config.allow_recompute = False opts.profiling.enable_ipu_trace_events = profiling or enable_ipu_events opts.profiling.enable_compilation_trace = profiling opts.profiling.enable_io_trace = profiling opts.profiling.execution_trace_type = profile_execution.value opts.profiling.enable_poplar_reports_text = use_poplar_text_report opts.profiling.enable_poplar_reports_cbor = use_poplar_cbor_report opts.profiling.enable_poplar_graph = enable_poplar_serialized_graph opts.profiling.report_every_nth_execution = report_every_nth_execution opts.profiling.max_report_size = max_report_size opts.profiling.report_directory = report_directory opts.speed_size_config.always_rearrange_copies_on_the_host = \ always_rearrange_copies_on_the_host opts.speed_size_config.merge_infeed_io_copies = merge_infeed_io_copies opts.speed_size_config.disable_graph_convolution_caching = \ disable_graph_convolution_caching opts.speed_size_config.disable_graph_outlining = \ disable_graph_outlining opts.speed_size_config.scheduler_selection = scheduler_selection opts.max_cross_replica_sum_buffer_size = max_cross_replica_sum_buffer_size opts.max_inter_ipu_copies_buffer_size = max_inter_ipu_copies_buffer_size opts.max_scheduler_lookahead_depth = max_scheduler_lookahead_depth opts.max_scheduler_search_space_size = max_scheduler_search_space_size opts.prefetch_data_streams = prefetch_data_streams opts.selection_order = selection_order.value opts.verified_transfers.enabled = False opts = set_verification_options(opts, VerificationOptions()) opts.enable_experimental_remote_buffer_embedding = \ enable_experimental_remote_buffer_embedding return opts def set_serialization_options(opts, output_folder=""): opts.serialization_folder = output_folder return opts def set_optimization_options(opts, combine_embedding_lookups=False, combine_matmuls=False, max_cross_replica_sum_buffer_size=0, max_reduce_scatter_buffer_size=0, max_inter_ipu_copies_buffer_size=0, max_send_recv_cluster_size=0, gather_simplifier=False, triangular_solve_expander_block_size=0): opts.enable_multi_slice_combiner = combine_embedding_lookups opts.enable_matmul_combiner = combine_matmuls opts.max_cross_replica_sum_buffer_size = max_cross_replica_sum_buffer_size opts.max_reduce_scatter_buffer_size = max_reduce_scatter_buffer_size opts.max_inter_ipu_copies_buffer_size = max_inter_ipu_copies_buffer_size opts.max_send_recv_cluster_size = max_send_recv_cluster_size opts.enable_gather_simplifier = gather_simplifier opts.triangular_solve_expander_block_size = \ triangular_solve_expander_block_size return opts def set_norm_options(opts, use_stable_statistics=False): opts.use_stable_norm_statistics = use_stable_statistics return opts def set_transfer_options(opts, use_verified_transfers=False): opts.verified_transfers.enabled = use_verified_transfers return opts class KeyId: def __init__(self, key=0, start_id=-1): self.key = key self.start_id = start_id class VerificationOptions: def __init__(self): self.inputs = KeyId() self.input_parameters = KeyId() self.outputs = KeyId() self.output_parameters = KeyId() self.infeeds = collections.defaultdict(KeyId) self.outfeeds = collections.defaultdict(KeyId) self.checkpoint_in = KeyId(0, 0) self.checkpoint_out = KeyId(0, 0) def set_verification_options(opts, verification_options): if not isinstance(verification_options, VerificationOptions): raise Exception( "`verification_options` must be of type VerificationOptions") def _cp_key_and_id(src, dst): dst.key = src.key dst.start_id = src.start_id for attr in [ "inputs", "input_parameters", "outputs", "output_parameters", "checkpoint_in", "checkpoint_out" ]: _cp_key_and_id(getattr(verification_options, attr), getattr(opts.verified_transfers, attr)) for name, options in verification_options.infeeds.items(): _cp_key_and_id(options, opts.verified_transfers.infeeds[name]) for name, options in verification_options.outfeeds.items(): _cp_key_and_id(options, opts.verified_transfers.outfeeds[name]) return opts def set_compilation_options(opts, compilation_options=None): if compilation_options: if not isinstance(compilation_options, dict): raise Exception("`compilation_options` must be a dictionary") for (option_name, value) in compilation_options.items(): compilation_option = opts.compilation_options.add() compilation_option.option = option_name compilation_option.value = value return opts def set_convolution_options(opts, convolution_options=None): if convolution_options: if not isinstance(convolution_options, dict): raise Exception("`convolution_options` must be a dictionary") for (option_name, value) in convolution_options.items(): opt = opts.convolution_options.add() opt.option = option_name opt.value = value return opts def set_matmul_options(opts, matmul_options=None, clear_pass_type=False): if matmul_options: if not isinstance(matmul_options, dict): raise Exception("`matmul_options` must be a dictionary") for (option_name, value) in matmul_options.items(): opt = opts.matmul_options.add() opt.option = option_name opt.value = value opts.clear_matmul_pass_type = clear_pass_type return opts def set_pooling_options(opts, pooling_options=None): if pooling_options: if not isinstance(pooling_options, dict): raise Exception("`pooling_options` must be a dictionary") for (option_name, value) in pooling_options.items(): opt = opts.pooling_options.add() opt.option = option_name opt.value = value return opts @deprecation.deprecated_args( None, "report_options is deprecated, use graph_options and" " execution_options instead", "report_options") def set_report_options(opts, report_options=None, graph_options=None, execution_options=None): def use_report_options(): if report_options: if not isinstance(report_options, dict): raise Exception("`report_options` must be a dictionary") return report_options if not graph_options: graph_options = use_report_options() if graph_options: if not isinstance(graph_options, dict): raise Exception("`graph_options` must be a dictionary") for (option_name, value) in graph_options.items(): opt = opts.profiling.graph_options.add() opt.option = option_name opt.value = value if not execution_options: execution_options = use_report_options() if execution_options: if not isinstance(execution_options, dict): raise Exception("`execution_options` must be a dictionary") for (option_name, value) in execution_options.items(): opt = opts.profiling.execution_options.add() opt.option = option_name opt.value = value return opts def set_ipu_model_options(opts, compile_ipu_code=True): opts.ipu_model_config.compile_ipu_code = compile_ipu_code return opts @deprecation.deprecated_args( None, "Pipelining recomputation will recompute all the non-stateful operations " "when recomputation is enabled.", "allow_stateful_recompute", ) def set_recomputation_options(opts, allow_recompute=True, allow_stateful_recompute=None): opts.speed_size_config.allow_recompute = allow_recompute return opts def set_floating_point_behaviour_options(opts, inv=True, div0=True, oflo=True, esr=True, nanoo=True): opts.floating_point_behaviour.flags_set = True opts.floating_point_behaviour.inv = inv opts.floating_point_behaviour.div0 = div0 opts.floating_point_behaviour.oflo = oflo opts.floating_point_behaviour.esr = esr opts.floating_point_behaviour.nanoo = nanoo return opts def set_gcl_options(opts, num_io_tiles=0, gcl_options=None): opts.gcl_num_io_tiles = num_io_tiles if gcl_options: if not isinstance(gcl_options, dict): raise TypeError("`gcl_options` must be a dictionary") for (option_name, value) in gcl_options.items(): opt = opts.gcl_options.add() opt.option = option_name opt.value = value return opts def auto_select_ipus(opts, num_ipus): if opts.device_config: raise Exception("IPU devices have already been configured.") if not isinstance(num_ipus, (int, list, tuple)): raise Exception("`num_ipus` must be an integer, list or tuple.") if isinstance(num_ipus, int): dev = opts.device_config.add() dev.auto_count = num_ipus else: for n in num_ipus: dev = opts.device_config.add() dev.auto_count = n return opts def select_ipus(opts, indices): if opts.device_config: raise Exception("IPU devices have already been configured.") if not isinstance(indices, (list, tuple)): raise Exception("`indices` must be a list or tuple.") if len(set(indices)) != len(indices): raise Exception("All device indeicies in `indices` must be unique.") for i in indices: dev = opts.device_config.add() dev.cfg_index = i return opts def set_ipu_connection_type(opts, connection_type=None, ipu_version=None): connection_type = connection_type if connection_type \ else DeviceConnectionType.ALWAYS if connection_type == DeviceConnectionType.NEVER and ipu_version is None: raise Exception("`ipu_version` must be set when `connection_type` is set " "to `DeviceConnectionType.NEVER`") opts.device_connection_type = connection_type.value if ipu_version is not None: opts.ipu_version = ipu_version opts.has_ipu_version = True return opts def reset_ipu_seed(seed, device="/device:IPU:0", cpu_device="cpu"): g = ops.Graph() with g.as_default(): with ops.device(cpu_device): cfg_op = gen_ipu_ops.ipu_reset_seed(device, seed) with session_lib.Session(graph=g) as sess: sess.run(cfg_op) def extract_all_strings_from_event_trace(events): result = "" for e in events: evt = IpuTraceEvent.FromString(e) result = result + ("-" * 70) + "\n=> @ " + \ time.strftime('%F %T %z', time.localtime(evt.timestamp)) + ": " if evt.type == IpuTraceEvent.COMPILE_BEGIN: evt_str = "Compile begin: " + \ evt.compile_begin.module_name.decode('utf-8') + "\n" elif evt.type == IpuTraceEvent.COMPILE_END: evt_str = "Compile end: " + \ evt.compile_end.module_name.decode('utf-8') + "\n" + \ "Duration: " + str(evt.compile_end.duration) + " us\n" + \ evt.compile_end.compilation_report.decode('utf-8') elif evt.type == IpuTraceEvent.HOST_TO_DEVICE_TRANSFER: evt_str = "Host->Device\n" + \ evt.data_transfer.data_transfer.decode('utf-8') + "\n" elif evt.type == IpuTraceEvent.DEVICE_TO_HOST_TRANSFER: evt_str = "Device->Host\n" + \ evt.data_transfer.data_transfer.decode('utf-8') + "\n" elif evt.type == IpuTraceEvent.LOAD_ENGINE: evt_str = "Load engine: " + \ evt.load_engine.module_name.decode('utf-8') + "\n" elif evt.type == IpuTraceEvent.EXECUTE: evt_str = "Execute: " + \ evt.execute.module_name.decode('utf-8') + "\n" + \ evt.execute.execution_report.decode('utf-8') else: evt_str = "Unknown event" result = result + evt_str + '\n' return result def extract_all_types_from_event_trace(events): result = [] for e in events: evt = IpuTraceEvent.FromString(e) result += [evt.type] return result def extract_all_events(events): result = [] for e in events: evt = IpuTraceEvent.FromString(e) result += [evt] return result def extract_compile_reports(events): result = [] for e in events: evt = IpuTraceEvent.FromString(e) if evt.type == IpuTraceEvent.COMPILE_END: try: module = evt.compile_end.module_name.decode('utf-8') rep = evt.compile_end.compilation_report.decode('utf-8') if rep: result += [(module, rep)] except UnicodeDecodeError: pass return result def extract_poplar_serialized_graphs(events): result = [] for e in events: evt = IpuTraceEvent.FromString(e) if evt.type == IpuTraceEvent.COMPILE_END: try: rep = evt.compile_end.poplar_graph.decode('utf-8') except UnicodeDecodeError: rep = evt.compile_end.poplar_graph module = evt.compile_end.module_name.decode('utf-8') if rep: result += [(module, rep)] return result def extract_execute_reports(events): result = [] for e in events: evt = IpuTraceEvent.FromString(e) if evt.type == IpuTraceEvent.EXECUTE: try: module = evt.execute.module_name.decode('utf-8') rep = evt.execute.execution_report.decode('utf-8') if rep: result += [(module, rep)] except UnicodeDecodeError: pass return result def move_variable_initialization_to_cpu(graph=None): if not graph: graph = ops.get_default_graph() with ops.device("/device:CPU:0"): control_flow_ops.no_op(name="cpu") variables = [] for v in graph.get_collection('variables'): if not isinstance(v, values.DistributedVariable): variables.append(v) def _uses_resource(op): return any(input_tensor.dtype == 'resource' for input_tensor in op.inputs) init_ops = [] dep_ops = [v.initializer.inputs[1].op for v in variables] visited = set() while dep_ops: op = dep_ops.pop() if op not in visited and not _uses_resource(op): visited.add(op) init_ops += [op] dep_ops += [x.op for x in op.inputs] for op in init_ops: op._set_device('/device:CPU:0') op._set_attr( '_class', attr_value_pb2.AttrValue(list=attr_value_pb2.AttrValue.ListValue( s=[b'loc:@cpu']))) op._set_attr('_XlaCompile', attr_value_pb2.AttrValue(b=False)) op._set_attr('_XlaScope', attr_value_pb2.AttrValue(s=b'')) return def export_dataset_to_file(dataset_or_infeed, output_filename, num_elements, feed_name="", apply_options=True): assert isinstance(dataset_or_infeed, (dataset_ops.Dataset, ipu_infeed_queue.IPUInfeedQueue)) if isinstance(dataset_or_infeed, ipu_infeed_queue.IPUInfeedQueue): dataset = dataset_or_infeed._dataset feed_name = feed_name or dataset_or_infeed._id else: dataset = dataset_or_infeed if apply_options: dataset = dataset._apply_options() extractor = dataset_extractor.dataset_extractor(dataset, num_elements, output_filename, feed_name) with ops.device("cpu"), session_lib.Session() as sess: sess.run(extractor) def export_inputs_to_file(inputs, output_filename, feed_dict): with ops.device("cpu"), session_lib.Session() as sess: sess.run(dataset_extractor.export_variables(inputs, output_filename), feed_dict)
true
true
f72ca776ebc6d065e702f3c8cb4da790bde5d2ce
3,892
py
Python
tests/data/residues/GLN.py
uw-ipd/privileged_residues
78078c22ba537651a1b6bd1404c05246ab73a3e3
[ "Apache-2.0" ]
null
null
null
tests/data/residues/GLN.py
uw-ipd/privileged_residues
78078c22ba537651a1b6bd1404c05246ab73a3e3
[ "Apache-2.0" ]
20
2018-08-13T22:50:46.000Z
2018-11-03T22:29:03.000Z
tests/data/residues/GLN.py
uw-ipd/privileged_residues
78078c22ba537651a1b6bd1404c05246ab73a3e3
[ "Apache-2.0" ]
1
2018-08-25T06:03:43.000Z
2018-08-25T06:03:43.000Z
from tests.util import pick_ray from pyrosetta import Pose from pyrosetta.rosetta.core.import_pose import pose_from_pdbstring name = "GLN" contents = """ ATOM 1 N ALA A 1 0.000 0.000 0.000 1.00 0.00 N ATOM 2 CA ALA A 1 1.458 0.000 0.000 1.00 0.00 C ATOM 3 C ALA A 1 2.009 1.420 0.000 1.00 0.00 C ATOM 4 O ALA A 1 1.251 2.390 0.000 1.00 0.00 O ATOM 5 CB ALA A 1 1.988 -0.773 -1.199 1.00 0.00 C ATOM 6 1H ALA A 1 -0.334 -0.943 -0.000 1.00 0.00 H ATOM 7 2H ALA A 1 -0.334 0.471 0.816 1.00 0.00 H ATOM 8 3H ALA A 1 -0.334 0.471 -0.816 1.00 0.00 H ATOM 9 HA ALA A 1 1.797 -0.490 0.913 1.00 0.00 H ATOM 10 1HB ALA A 1 3.078 -0.764 -1.185 1.00 0.00 H ATOM 11 2HB ALA A 1 1.633 -1.802 -1.154 1.00 0.00 H ATOM 12 3HB ALA A 1 1.633 -0.307 -2.117 1.00 0.00 H ATOM 13 N GLN A 2 3.332 1.536 0.000 1.00 0.00 N ATOM 14 CA GLN A 2 3.988 2.839 0.000 1.00 0.00 C ATOM 15 C GLN A 2 5.504 2.693 0.000 1.00 0.00 C ATOM 16 O GLN A 2 6.030 1.580 0.000 1.00 0.00 O ATOM 17 CB GLN A 2 3.542 3.663 1.211 1.00 0.00 C ATOM 18 CG GLN A 2 2.545 2.955 2.113 1.00 0.00 C ATOM 19 CD GLN A 2 2.200 1.564 1.615 1.00 0.00 C ATOM 20 OE1 GLN A 2 2.707 1.116 0.583 1.00 0.00 O ATOM 21 NE2 GLN A 2 1.333 0.873 2.346 1.00 0.00 N ATOM 22 H GLN A 2 3.899 0.700 0.000 1.00 0.00 H ATOM 23 HA GLN A 2 3.702 3.361 -0.913 1.00 0.00 H ATOM 24 1HB GLN A 2 4.412 3.926 1.812 1.00 0.00 H ATOM 25 2HB GLN A 2 3.086 4.592 0.870 1.00 0.00 H ATOM 26 1HG GLN A 2 2.975 2.864 3.111 1.00 0.00 H ATOM 27 2HG GLN A 2 1.627 3.541 2.153 1.00 0.00 H ATOM 28 1HE2 GLN A 2 1.066 -0.050 2.067 1.00 0.00 H ATOM 29 2HE2 GLN A 2 0.945 1.275 3.176 1.00 0.00 H ATOM 30 N ALA A 3 6.202 3.823 0.000 1.00 0.00 N ATOM 31 CA ALA A 3 7.660 3.823 0.000 1.00 0.00 C ATOM 32 C ALA A 3 8.211 5.243 0.000 1.00 0.00 C ATOM 33 O ALA A 3 8.260 5.868 1.023 1.00 0.00 O ATOM 34 OXT ALA A 3 8.596 5.737 -1.023 1.00 0.00 O ATOM 35 CB ALA A 3 8.190 3.050 -1.199 1.00 0.00 C ATOM 36 H ALA A 3 5.710 4.705 -0.000 1.00 0.00 H ATOM 37 HA ALA A 3 7.999 3.333 0.913 1.00 0.00 H ATOM 38 1HB ALA A 3 9.280 3.059 -1.185 1.00 0.00 H ATOM 39 2HB ALA A 3 7.835 2.021 -1.154 1.00 0.00 H ATOM 40 3HB ALA A 3 7.835 3.516 -2.117 1.00 0.00 H TER """ pose = Pose() pose_from_pdbstring(pose, contents) n_rays = { 1: pick_ray(pose.residue(1), "1H", "N"), 2: pick_ray(pose.residue(2), "H", "N"), 3: pick_ray(pose.residue(3), "H", "N") } c_rays = { 1: pick_ray(pose.residue(1), "O", "C"), 2: pick_ray(pose.residue(2), "O", "C"), 3: pick_ray(pose.residue(3), "O", "C") } sc_donor = { 2: [ pick_ray(pose.residue(2), "1HE2", "NE2"), pick_ray(pose.residue(2), "2HE2", "NE2") ] } sc_acceptor = { 2: [ pick_ray(pose.residue(2), "OE1", "CD") ] } cat_pi = [ ]
48.049383
78
0.43705
from tests.util import pick_ray from pyrosetta import Pose from pyrosetta.rosetta.core.import_pose import pose_from_pdbstring name = "GLN" contents = """ ATOM 1 N ALA A 1 0.000 0.000 0.000 1.00 0.00 N ATOM 2 CA ALA A 1 1.458 0.000 0.000 1.00 0.00 C ATOM 3 C ALA A 1 2.009 1.420 0.000 1.00 0.00 C ATOM 4 O ALA A 1 1.251 2.390 0.000 1.00 0.00 O ATOM 5 CB ALA A 1 1.988 -0.773 -1.199 1.00 0.00 C ATOM 6 1H ALA A 1 -0.334 -0.943 -0.000 1.00 0.00 H ATOM 7 2H ALA A 1 -0.334 0.471 0.816 1.00 0.00 H ATOM 8 3H ALA A 1 -0.334 0.471 -0.816 1.00 0.00 H ATOM 9 HA ALA A 1 1.797 -0.490 0.913 1.00 0.00 H ATOM 10 1HB ALA A 1 3.078 -0.764 -1.185 1.00 0.00 H ATOM 11 2HB ALA A 1 1.633 -1.802 -1.154 1.00 0.00 H ATOM 12 3HB ALA A 1 1.633 -0.307 -2.117 1.00 0.00 H ATOM 13 N GLN A 2 3.332 1.536 0.000 1.00 0.00 N ATOM 14 CA GLN A 2 3.988 2.839 0.000 1.00 0.00 C ATOM 15 C GLN A 2 5.504 2.693 0.000 1.00 0.00 C ATOM 16 O GLN A 2 6.030 1.580 0.000 1.00 0.00 O ATOM 17 CB GLN A 2 3.542 3.663 1.211 1.00 0.00 C ATOM 18 CG GLN A 2 2.545 2.955 2.113 1.00 0.00 C ATOM 19 CD GLN A 2 2.200 1.564 1.615 1.00 0.00 C ATOM 20 OE1 GLN A 2 2.707 1.116 0.583 1.00 0.00 O ATOM 21 NE2 GLN A 2 1.333 0.873 2.346 1.00 0.00 N ATOM 22 H GLN A 2 3.899 0.700 0.000 1.00 0.00 H ATOM 23 HA GLN A 2 3.702 3.361 -0.913 1.00 0.00 H ATOM 24 1HB GLN A 2 4.412 3.926 1.812 1.00 0.00 H ATOM 25 2HB GLN A 2 3.086 4.592 0.870 1.00 0.00 H ATOM 26 1HG GLN A 2 2.975 2.864 3.111 1.00 0.00 H ATOM 27 2HG GLN A 2 1.627 3.541 2.153 1.00 0.00 H ATOM 28 1HE2 GLN A 2 1.066 -0.050 2.067 1.00 0.00 H ATOM 29 2HE2 GLN A 2 0.945 1.275 3.176 1.00 0.00 H ATOM 30 N ALA A 3 6.202 3.823 0.000 1.00 0.00 N ATOM 31 CA ALA A 3 7.660 3.823 0.000 1.00 0.00 C ATOM 32 C ALA A 3 8.211 5.243 0.000 1.00 0.00 C ATOM 33 O ALA A 3 8.260 5.868 1.023 1.00 0.00 O ATOM 34 OXT ALA A 3 8.596 5.737 -1.023 1.00 0.00 O ATOM 35 CB ALA A 3 8.190 3.050 -1.199 1.00 0.00 C ATOM 36 H ALA A 3 5.710 4.705 -0.000 1.00 0.00 H ATOM 37 HA ALA A 3 7.999 3.333 0.913 1.00 0.00 H ATOM 38 1HB ALA A 3 9.280 3.059 -1.185 1.00 0.00 H ATOM 39 2HB ALA A 3 7.835 2.021 -1.154 1.00 0.00 H ATOM 40 3HB ALA A 3 7.835 3.516 -2.117 1.00 0.00 H TER """ pose = Pose() pose_from_pdbstring(pose, contents) n_rays = { 1: pick_ray(pose.residue(1), "1H", "N"), 2: pick_ray(pose.residue(2), "H", "N"), 3: pick_ray(pose.residue(3), "H", "N") } c_rays = { 1: pick_ray(pose.residue(1), "O", "C"), 2: pick_ray(pose.residue(2), "O", "C"), 3: pick_ray(pose.residue(3), "O", "C") } sc_donor = { 2: [ pick_ray(pose.residue(2), "1HE2", "NE2"), pick_ray(pose.residue(2), "2HE2", "NE2") ] } sc_acceptor = { 2: [ pick_ray(pose.residue(2), "OE1", "CD") ] } cat_pi = [ ]
true
true
f72ca7d3d97e12ab7b405dcff314bdb6c0a78755
3,337
py
Python
examples/pointer_generator/preprocess.py
fairseq-FT/fairseq
18725499144c1bba7c151b796ba774e59d36eaa9
[ "MIT" ]
16,259
2018-05-02T02:31:30.000Z
2022-03-31T21:50:23.000Z
examples/pointer_generator/preprocess.py
fairseq-FT/fairseq
18725499144c1bba7c151b796ba774e59d36eaa9
[ "MIT" ]
3,863
2018-05-02T13:42:39.000Z
2022-03-31T19:03:32.000Z
examples/pointer_generator/preprocess.py
fairseq-FT/fairseq
18725499144c1bba7c151b796ba774e59d36eaa9
[ "MIT" ]
4,796
2018-05-02T07:55:51.000Z
2022-03-31T14:46:45.000Z
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import argparse from itertools import zip_longest def replace_oovs(source_in, target_in, vocabulary, source_out, target_out): """Replaces out-of-vocabulary words in source and target text with <unk-N>, where N in is the position of the word in the source sequence. """ def format_unk(pos): return "<unk-{}>".format(pos) if target_in is None: target_in = [] for seq_num, (source_seq, target_seq) in enumerate( zip_longest(source_in, target_in) ): source_seq_out = [] target_seq_out = [] word_to_pos = dict() for position, token in enumerate(source_seq.strip().split()): if token in vocabulary: token_out = token else: if token in word_to_pos: oov_pos = word_to_pos[token] else: word_to_pos[token] = position oov_pos = position token_out = format_unk(oov_pos) source_seq_out.append(token_out) source_out.write(" ".join(source_seq_out) + "\n") if target_seq is not None: for token in target_seq.strip().split(): if token in word_to_pos: token_out = format_unk(word_to_pos[token]) else: token_out = token target_seq_out.append(token_out) if target_out is not None: target_out.write(" ".join(target_seq_out) + "\n") def main(): parser = argparse.ArgumentParser( description="Replaces out-of-vocabulary words in both source and target " "sequences with tokens that indicate the position of the word " "in the source sequence." ) parser.add_argument( "--source", type=str, help="text file with source sequences", required=True ) parser.add_argument( "--target", type=str, help="text file with target sequences", default=None ) parser.add_argument("--vocab", type=str, help="vocabulary file", required=True) parser.add_argument( "--source-out", type=str, help="where to write source sequences with <unk-N> entries", required=True, ) parser.add_argument( "--target-out", type=str, help="where to write target sequences with <unk-N> entries", default=None, ) args = parser.parse_args() with open(args.vocab, encoding="utf-8") as vocab: vocabulary = vocab.read().splitlines() target_in = ( open(args.target, "r", encoding="utf-8") if args.target is not None else None ) target_out = ( open(args.target_out, "w", encoding="utf-8") if args.target_out is not None else None ) with open(args.source, "r", encoding="utf-8") as source_in, open( args.source_out, "w", encoding="utf-8" ) as source_out: replace_oovs(source_in, target_in, vocabulary, source_out, target_out) if target_in is not None: target_in.close() if target_out is not None: target_out.close() if __name__ == "__main__": main()
32.398058
85
0.605034
import argparse from itertools import zip_longest def replace_oovs(source_in, target_in, vocabulary, source_out, target_out): def format_unk(pos): return "<unk-{}>".format(pos) if target_in is None: target_in = [] for seq_num, (source_seq, target_seq) in enumerate( zip_longest(source_in, target_in) ): source_seq_out = [] target_seq_out = [] word_to_pos = dict() for position, token in enumerate(source_seq.strip().split()): if token in vocabulary: token_out = token else: if token in word_to_pos: oov_pos = word_to_pos[token] else: word_to_pos[token] = position oov_pos = position token_out = format_unk(oov_pos) source_seq_out.append(token_out) source_out.write(" ".join(source_seq_out) + "\n") if target_seq is not None: for token in target_seq.strip().split(): if token in word_to_pos: token_out = format_unk(word_to_pos[token]) else: token_out = token target_seq_out.append(token_out) if target_out is not None: target_out.write(" ".join(target_seq_out) + "\n") def main(): parser = argparse.ArgumentParser( description="Replaces out-of-vocabulary words in both source and target " "sequences with tokens that indicate the position of the word " "in the source sequence." ) parser.add_argument( "--source", type=str, help="text file with source sequences", required=True ) parser.add_argument( "--target", type=str, help="text file with target sequences", default=None ) parser.add_argument("--vocab", type=str, help="vocabulary file", required=True) parser.add_argument( "--source-out", type=str, help="where to write source sequences with <unk-N> entries", required=True, ) parser.add_argument( "--target-out", type=str, help="where to write target sequences with <unk-N> entries", default=None, ) args = parser.parse_args() with open(args.vocab, encoding="utf-8") as vocab: vocabulary = vocab.read().splitlines() target_in = ( open(args.target, "r", encoding="utf-8") if args.target is not None else None ) target_out = ( open(args.target_out, "w", encoding="utf-8") if args.target_out is not None else None ) with open(args.source, "r", encoding="utf-8") as source_in, open( args.source_out, "w", encoding="utf-8" ) as source_out: replace_oovs(source_in, target_in, vocabulary, source_out, target_out) if target_in is not None: target_in.close() if target_out is not None: target_out.close() if __name__ == "__main__": main()
true
true
f72ca9ee9ae4957b92084a00b5624be329e8478f
349
py
Python
Capitulo_02/exercise2_4.py
thiagosouzalink/my_codes-exercices-book-curso_intensivo_de_python
841aa855a7450ad3d0ba65393ba0b6debcd6a770
[ "MIT" ]
null
null
null
Capitulo_02/exercise2_4.py
thiagosouzalink/my_codes-exercices-book-curso_intensivo_de_python
841aa855a7450ad3d0ba65393ba0b6debcd6a770
[ "MIT" ]
null
null
null
Capitulo_02/exercise2_4.py
thiagosouzalink/my_codes-exercices-book-curso_intensivo_de_python
841aa855a7450ad3d0ba65393ba0b6debcd6a770
[ "MIT" ]
null
null
null
""" 2.4 – Letras maiúsculas e minúsculas em nomes: Armazene o nome de uma pessoa em uma variável e então apresente o nome dessa pessoa em letras minúsculas, em letras maiúsculas e somente com a primeira letra maiúscula. """ nome = "José" # Minúsculas print(nome.lower()) # Maiúsculas print(nome.upper()) # Somente a primeira letra print(nome[0])
24.928571
215
0.747851
nome = "José" print(nome.lower()) print(nome.upper()) print(nome[0])
true
true
f72caa1cc50710b6f6793c4a96821b65b2e32acb
2,025
py
Python
src/routes/users.py
tombrereton/flask-api-starter-kit
2e244bfc4f5659e91fd7cd27388c37bf32baeaec
[ "MIT" ]
null
null
null
src/routes/users.py
tombrereton/flask-api-starter-kit
2e244bfc4f5659e91fd7cd27388c37bf32baeaec
[ "MIT" ]
null
null
null
src/routes/users.py
tombrereton/flask-api-starter-kit
2e244bfc4f5659e91fd7cd27388c37bf32baeaec
[ "MIT" ]
null
null
null
from http import HTTPStatus from typing import List from apifairy import body, other_responses, response from flask import Blueprint, jsonify from flask import request from src.config import DefaultConfig from src.dtos.user import UserDto from src.requests.user import CreateUserRequestSchema, CreateUserRequest, CreateManyUsersRequestSchema, \ CreateManyUsersRequest from src.responses.user import UserResponseSchema from src.services import queue_client from src.services.pascal_to_snake_serializer import JSONSerializer as ToSnakeJson from src.services.snake_to_pascal_serializer import JSONSerializer as ToPascalJson users_api = Blueprint('users', __name__) @users_api.route('users', methods=['POST']) @other_responses({ 200: 'User Created', 400: 'Request Body is Invalid' }) @body(CreateUserRequestSchema()) def post(user_request: CreateUserRequest): """Create a User.""" if request.method == 'POST': user_snake_case = ToSnakeJson.deserialize(UserDto, ToSnakeJson.serialize(user_request)) add_msg = queue_client.add_create_user_job(user_snake_case) return jsonify(add_msg), 200 @users_api.route('users/many', methods=['POST']) @other_responses({ 200: 'Users Created', 400: 'Request Body is Invalid' }) @body(CreateManyUsersRequestSchema()) def post_many(user_request: CreateManyUsersRequest): """Create a User.""" if request.method == 'POST': users_snake_case = ToSnakeJson.deserialize(List[UserDto], ToSnakeJson.serialize(user_request.Users)) users_added = [] for user in users_snake_case: add_msg = queue_client.add_create_user_job(user) users_added.append(add_msg) return jsonify(users_added), 200 @users_api.route('users/<int:id>', methods=['GET']) @response(UserResponseSchema, HTTPStatus.OK.value, "Get Users") def get_all_users(id: int): if request.method == 'GET': user = UserDto(user_name=DefaultConfig.DEFAULT_USERNAME) return ToPascalJson.serialize(user), 200
33.196721
108
0.74963
from http import HTTPStatus from typing import List from apifairy import body, other_responses, response from flask import Blueprint, jsonify from flask import request from src.config import DefaultConfig from src.dtos.user import UserDto from src.requests.user import CreateUserRequestSchema, CreateUserRequest, CreateManyUsersRequestSchema, \ CreateManyUsersRequest from src.responses.user import UserResponseSchema from src.services import queue_client from src.services.pascal_to_snake_serializer import JSONSerializer as ToSnakeJson from src.services.snake_to_pascal_serializer import JSONSerializer as ToPascalJson users_api = Blueprint('users', __name__) @users_api.route('users', methods=['POST']) @other_responses({ 200: 'User Created', 400: 'Request Body is Invalid' }) @body(CreateUserRequestSchema()) def post(user_request: CreateUserRequest): if request.method == 'POST': user_snake_case = ToSnakeJson.deserialize(UserDto, ToSnakeJson.serialize(user_request)) add_msg = queue_client.add_create_user_job(user_snake_case) return jsonify(add_msg), 200 @users_api.route('users/many', methods=['POST']) @other_responses({ 200: 'Users Created', 400: 'Request Body is Invalid' }) @body(CreateManyUsersRequestSchema()) def post_many(user_request: CreateManyUsersRequest): if request.method == 'POST': users_snake_case = ToSnakeJson.deserialize(List[UserDto], ToSnakeJson.serialize(user_request.Users)) users_added = [] for user in users_snake_case: add_msg = queue_client.add_create_user_job(user) users_added.append(add_msg) return jsonify(users_added), 200 @users_api.route('users/<int:id>', methods=['GET']) @response(UserResponseSchema, HTTPStatus.OK.value, "Get Users") def get_all_users(id: int): if request.method == 'GET': user = UserDto(user_name=DefaultConfig.DEFAULT_USERNAME) return ToPascalJson.serialize(user), 200
true
true
f72caa4b74837bd62d61442cc130cfd18f4a2cb9
602
py
Python
src/command_modules/azure-cli-find/azure/cli/command_modules/find/_help.py
v-Ajnava/azure-cli
febec631d79bfca151e84267b5b409594bad598e
[ "MIT" ]
null
null
null
src/command_modules/azure-cli-find/azure/cli/command_modules/find/_help.py
v-Ajnava/azure-cli
febec631d79bfca151e84267b5b409594bad598e
[ "MIT" ]
3
2021-03-26T00:48:20.000Z
2022-03-29T22:05:39.000Z
src/command_modules/azure-cli-find/azure/cli/command_modules/find/_help.py
v-Ajnava/azure-cli
febec631d79bfca151e84267b5b409594bad598e
[ "MIT" ]
1
2017-12-28T04:51:44.000Z
2017-12-28T04:51:44.000Z
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------------------------------- from azure.cli.core.help_files import helps helps['find'] = """ type: command short-summary: Find Azure CLI commands. examples: - name: Search for commands containing 'vm' or 'secret' text: > az find -q vm secret """
37.625
94
0.465116
from azure.cli.core.help_files import helps helps['find'] = """ type: command short-summary: Find Azure CLI commands. examples: - name: Search for commands containing 'vm' or 'secret' text: > az find -q vm secret """
true
true
f72caa944d2ed0ef2d12c5b7459dddcc53fc9b34
12,347
py
Python
EPro-PnP-Det/epropnp_det/core/bbox_3d/misc.py
Lakonik/EPro-PnP
931df847190ce10eddd1dc3e3168ce1a2f295ffa
[ "Apache-2.0" ]
19
2022-03-21T10:22:24.000Z
2022-03-30T15:43:46.000Z
EPro-PnP-Det/epropnp_det/core/bbox_3d/misc.py
Lakonik/EPro-PnP
931df847190ce10eddd1dc3e3168ce1a2f295ffa
[ "Apache-2.0" ]
null
null
null
EPro-PnP-Det/epropnp_det/core/bbox_3d/misc.py
Lakonik/EPro-PnP
931df847190ce10eddd1dc3e3168ce1a2f295ffa
[ "Apache-2.0" ]
3
2022-03-26T08:08:24.000Z
2022-03-30T11:17:11.000Z
""" Copyright (C) 2010-2022 Alibaba Group Holding Limited. This file is modified from https://github.com/tjiiv-cprg/MonoRUn """ import math import numpy as np import torch from pytorch3d.structures.meshes import Meshes from epropnp_det.ops.iou3d.iou3d_utils import nms_gpu def gen_unit_noc(num_pts, device=None): indices = torch.arange(0, num_pts, dtype=torch.float32, device=device) + 0.5 phi = torch.arccos(1 - 2 * indices / num_pts) theta = math.pi * (1 + 5**0.5) * indices xyz = torch.stack( (torch.cos(theta) * torch.sin(phi), torch.sin(theta) * torch.sin(phi), torch.cos(phi)), dim=-1) return xyz def project_to_image_r_mat( x3d, r_mat, t_vec, cam_intrinsic, img_shapes, z_min=0.5, allowed_border=200, return_z=False, return_clip_mask=False): """ Args: x3d (torch.Tensor): shape (*, num_points, 3) r_mat (torch.Tensor): shape (*, 3, 3) t_vec (torch.Tensor): shape (*, 3) in format [x, y, z] cam_intrinsic (torch.Tensor): shape (*, 3, 3) img_shapes (torch.Tensor): shape (*, 2) Returns: Tensor: x2d_proj, shape (*, num_points, 2) """ proj_r_mats = cam_intrinsic @ r_mat # (*, 3, 3) proj_t_vecs = cam_intrinsic @ t_vec.unsqueeze(-1) # (*, 3, 1) # (*, num_points, 3) = ((*, 3, 3) @ (*, 3, num_points) + (*, 3, 1)).T xyz_proj = (proj_r_mats @ x3d.transpose(-1, -2) + proj_t_vecs).transpose(-1, -2) z_proj = xyz_proj[..., 2:] # (*, num_points, 1) if return_clip_mask: z_clip_mask = z_proj < z_min z_proj = z_proj.clamp(min=z_min) x2d_proj = xyz_proj[..., :2] / z_proj # (*, num_points, 2) # clip to border x2d_min = -allowed_border - 0.5 # Number x2d_max = img_shapes[..., None, [1, 0]] + (allowed_border - 0.5) # (*, 1, 2) if return_clip_mask: x2d_clip_mask = (x2d_proj < x2d_min) | (x2d_proj > x2d_max) clip_mask = z_clip_mask.squeeze(-1) | x2d_clip_mask.any(-1) # (*, num_points) x2d_proj = torch.min(x2d_proj.clamp(min=x2d_min), x2d_max) if not return_z: if not return_clip_mask: return x2d_proj else: return x2d_proj, clip_mask else: if not return_clip_mask: return x2d_proj, z_proj else: return x2d_proj, z_proj, clip_mask def project_to_image( x3d, pose, cam_intrinsic, img_shapes, z_min=0.5, allowed_border=200, return_z=False, return_clip_mask=False): """ Args: x3d (torch.Tensor): shape (*, num_points, 3) pose (torch.Tensor): shape (*, 4) in format [x, y, z, yaw] cam_intrinsic (torch.Tensor): shape (*, 3, 3) img_shapes (torch.Tensor): shape (*, 2) Returns: Tensor: x2d_proj, shape (*, num_points, 2) """ r_mat = yaw_to_rot_mat(pose[..., 3]) t_vec = pose[..., :3] return project_to_image_r_mat(x3d, r_mat, t_vec, cam_intrinsic, img_shapes, z_min, allowed_border, return_z, return_clip_mask) def yaw_to_rot_mat(yaw): """ Args: yaw: (*) Returns: rot_mats: (*, 3, 3) """ if isinstance(yaw, torch.Tensor): pkg = torch device_kwarg = dict(device=yaw.device) else: pkg = np device_kwarg = dict() sin_yaw = pkg.sin(yaw) cos_yaw = pkg.cos(yaw) # [[ cos_yaw, 0, sin_yaw], # [ 0, 1, 0], # [-sin_yaw, 0, cos_yaw]] rot_mats = pkg.zeros(yaw.shape + (3, 3), dtype=pkg.float32, **device_kwarg) rot_mats[..., 0, 0] = cos_yaw rot_mats[..., 2, 2] = cos_yaw rot_mats[..., 0, 2] = sin_yaw rot_mats[..., 2, 0] = -sin_yaw rot_mats[..., 1, 1] = 1 return rot_mats def rot_mat_to_yaw(rot_mat): """ Args: rot_mat: (*, 3, 3) Returns: yaw: (*) """ if isinstance(rot_mat, torch.Tensor): atan2 = torch.atan2 else: atan2 = np.arctan2 yaw = atan2(rot_mat[..., 0, 2] - rot_mat[..., 2, 0], rot_mat[..., 0, 0] + rot_mat[..., 2, 2]) return yaw def box_mesh(): return Meshes( verts=[torch.tensor([[-1, -1, 1], [ 1, -1, 1], [-1, 1, 1], [ 1, 1, 1], [-1, -1, -1], [ 1, -1, -1], [-1, 1, -1], [ 1, 1, -1]], dtype=torch.float32)], faces=[torch.tensor([[0, 1, 2], [1, 3, 2], [2, 3, 7], [2, 7, 6], [1, 7, 3], [1, 5, 7], [6, 7, 4], [7, 5, 4], [0, 4, 1], [1, 4, 5], [2, 6, 4], [0, 2, 4]], dtype=torch.int)]) def compute_box_3d(bbox_3d): """ Args: bbox_3d: (*, 7) Returns: corners: (*, 8, 3) edge_corner_idx: (12, 2) """ bs = bbox_3d.shape[:-1] rotation_matrix = yaw_to_rot_mat(bbox_3d[..., 6]) # (*bs, 3, 3) edge_corner_idx = np.array([[0, 1], [1, 2], [2, 3], [3, 0], [4, 5], [5, 6], [6, 7], [7, 4], [0, 4], [1, 5], [2, 6], [3, 7]]) corners = np.array([[ 0.5, 0.5, 0.5], [ 0.5, 0.5, -0.5], [-0.5, 0.5, -0.5], [-0.5, 0.5, 0.5], [ 0.5, -0.5, 0.5], [ 0.5, -0.5, -0.5], [-0.5, -0.5, -0.5], [-0.5, -0.5, 0.5]], dtype=np.float32) if isinstance(bbox_3d, torch.Tensor): edge_corner_idx = torch.from_numpy(edge_corner_idx).to(device=bbox_3d.device) corners = torch.from_numpy(corners).to(device=bbox_3d.device) corners = corners * bbox_3d[..., None, :3] # (*bs, 8, 3) corners = (rotation_matrix[..., None, :, :] @ corners[..., None]).reshape(*bs, 8, 3) \ + bbox_3d[..., None, 3:6] return corners, edge_corner_idx def edge_intersection(corners, edge_corner_idx, clip_axis, clip_val, op, edge_valid_mask=None): """ Args: corners: (bs, 8, 3/2) edge_corner_idx: (12, 2) clip_val: (bs, ) edge_valid_mask: (bs, 12) """ if op == 'greater': op = torch.greater elif op == 'less': op = torch.less if edge_valid_mask is None: edge_valid_mask = corners.new_ones( (corners.size(0), edge_corner_idx.size(0)), dtype=torch.bool) corners_inside = op(corners[..., clip_axis], clip_val[:, None]) # (bs, 8) # compute z intersection edges_0_inside = corners_inside[:, edge_corner_idx[:, 0]] # (bs, 12) edges_1_inside = corners_inside[:, edge_corner_idx[:, 1]] # (bs, 12) edges_clipped = (edges_0_inside ^ edges_1_inside) & edge_valid_mask # (bs, 12) edges_clipped_idx = edges_clipped.nonzero() # (num_nonzero, 2) in [bs_ind, edge_ind] if edges_clipped_idx.shape[0] > 0: edge_corner_idx_to_clip = edge_corner_idx[edges_clipped_idx[:, 1], :] # (num_nonzero, 2) edges_0 = corners[edges_clipped_idx[:, 0], edge_corner_idx_to_clip[:, 0], :] # (num_nonzero, 3) edges_1 = corners[edges_clipped_idx[:, 0], edge_corner_idx_to_clip[:, 1], :] # (num_nonzero, 3) axval0 = edges_0[:, clip_axis] # (num_nonzero, ) axval1 = edges_1[:, clip_axis] clip_val_ = clip_val[edges_clipped_idx[:, 0]] weight_0 = axval1 - clip_val_ # (num_nonzero, ) weight_1 = clip_val_ - axval0 intersection = (edges_0 * weight_0[:, None] + edges_1 * weight_1[:, None] ) * (1 / (axval1 - axval0)).clamp(min=-1e6, max=1e6)[:, None] # (num_nonzero, 3) clip_idx = torch.where(op(axval0, clip_val_), edge_corner_idx_to_clip[:, 1], edge_corner_idx_to_clip[:, 0]) # (num_nonzero, ) corners[edges_clipped_idx[:, 0], clip_idx, :] = intersection # replace clipped corners with intersection corners_inside[edges_clipped_idx[:, 0], clip_idx] = True edge_valid_mask &= corners_inside[:, edge_corner_idx[:, 0]] & corners_inside[:, edge_corner_idx[:, 1]] else: edge_valid_mask &= edges_0_inside & edges_1_inside return corners, corners_inside, edge_valid_mask def bboxes_3d_to_2d(bbox_3d, cam_intrinsic, imsize, z_clip=0.1, min_size=4.0, clip=False): """ Args: bbox_3d: (bs, 7) cam_intrinsic: (bs, 3, 3) imsize: (bs, 2) in [h, w] """ assert bbox_3d.dim() == 2 bs = bbox_3d.size(0) if bs > 0: # (bs, 8, 3), (12, 2) corners, edge_corner_idx = compute_box_3d(bbox_3d) corners, in_front, edge_valid_mask = edge_intersection( corners, edge_corner_idx, 2, corners.new_tensor([z_clip]).expand(bs), 'greater') pts_2d = corners @ cam_intrinsic.transpose(-1, -2) pts_2d = pts_2d[..., :2] / pts_2d[..., 2:].clamp(min=z_clip) + 0.5 # (bs, 8, 2) in_canvas = in_front if clip: pts_2d, in_canvas_x0, edge_valid_mask = edge_intersection( pts_2d, edge_corner_idx, 0, corners.new_tensor([0]).expand(bs), 'greater', edge_valid_mask) pts_2d, in_canvas_y0, edge_valid_mask = edge_intersection( pts_2d, edge_corner_idx, 1, corners.new_tensor([0]).expand(bs), 'greater', edge_valid_mask) pts_2d, in_canvas_x1, edge_valid_mask = edge_intersection( pts_2d, edge_corner_idx, 0, imsize[:, 1], 'less', edge_valid_mask) pts_2d, in_canvas_y1, edge_valid_mask = edge_intersection( pts_2d, edge_corner_idx, 1, imsize[:, 0], 'less', edge_valid_mask) in_canvas = in_canvas & in_canvas_x0 & in_canvas_x1 & in_canvas_y0 & in_canvas_y1 # (bs, 8) not_in_canvas = ~in_canvas pts_2d[not_in_canvas] = imsize[:, None, [1, 0]].expand(-1, 8, -1)[not_in_canvas] x0y0 = pts_2d.min(dim=1)[0].clamp(min=0) # (bs, 2) pts_2d[not_in_canvas] = 0 x1y1 = torch.minimum(pts_2d.max(dim=1)[0], imsize[:, [1, 0]]) bbox = torch.cat((x0y0, x1y1), dim=1) # (bs, 4) bbox_valid_mask = (x1y1 - x0y0).min(dim=1)[0] >= min_size # (bs, ) else: bbox = bbox_3d.new_empty((0, 4)) bbox_valid_mask = bbox_3d.new_empty((0, ), dtype=torch.bool) return bbox, bbox_valid_mask def xywhr2xyxyr(boxes_xywhr): """Convert a rotated boxes in XYWHR format to XYXYR format. Args: boxes_xywhr (torch.Tensor): Rotated boxes in XYWHR format. Returns: torch.Tensor: Converted boxes in XYXYR format. """ boxes = torch.zeros_like(boxes_xywhr) half_w = boxes_xywhr[:, 2] / 2 # l in bbox_3d half_h = boxes_xywhr[:, 3] / 2 # w in bbox_3d # x in cam coord boxes[:, 0] = boxes_xywhr[:, 0] - half_w # z in cam coord, mirrored_direction boxes[:, 1] = boxes_xywhr[:, 1] - half_h boxes[:, 2] = boxes_xywhr[:, 0] + half_w boxes[:, 3] = boxes_xywhr[:, 1] + half_h boxes[:, 4] = boxes_xywhr[:, 4] return boxes def batched_bev_nms(bbox_3d, batch_inds, nms_thr=0.25): """ Args: bbox_3d (Tensor): tensor shape (N, 8+), in format [l, h, w, x, y, z, ry, score, ind, *] batch_inds (Tensor): tensor shape (N, ) nms_thr (float) Returns: Tuple: bbox_3d_out (Tensor) keep_inds (Tensor) """ n = bbox_3d.size(0) if n > 1: boxes_for_nms = xywhr2xyxyr( bbox_3d[:, [3, 5, 0, 2, 6]]) offset_unit = (boxes_for_nms[:, :4].max() - boxes_for_nms[:, :4].min()) * 2 boxes_for_nms[:, :4] = boxes_for_nms[:, :4] + (offset_unit * batch_inds)[:, None] keep_inds = nms_gpu( boxes_for_nms, bbox_3d[:, 7], nms_thr) else: keep_inds = bbox_3d.new_zeros(0, dtype=torch.int64) bbox_3d_out = bbox_3d[keep_inds] return bbox_3d_out, keep_inds
37.990769
113
0.53268
import math import numpy as np import torch from pytorch3d.structures.meshes import Meshes from epropnp_det.ops.iou3d.iou3d_utils import nms_gpu def gen_unit_noc(num_pts, device=None): indices = torch.arange(0, num_pts, dtype=torch.float32, device=device) + 0.5 phi = torch.arccos(1 - 2 * indices / num_pts) theta = math.pi * (1 + 5**0.5) * indices xyz = torch.stack( (torch.cos(theta) * torch.sin(phi), torch.sin(theta) * torch.sin(phi), torch.cos(phi)), dim=-1) return xyz def project_to_image_r_mat( x3d, r_mat, t_vec, cam_intrinsic, img_shapes, z_min=0.5, allowed_border=200, return_z=False, return_clip_mask=False): proj_r_mats = cam_intrinsic @ r_mat proj_t_vecs = cam_intrinsic @ t_vec.unsqueeze(-1) xyz_proj = (proj_r_mats @ x3d.transpose(-1, -2) + proj_t_vecs).transpose(-1, -2) z_proj = xyz_proj[..., 2:] if return_clip_mask: z_clip_mask = z_proj < z_min z_proj = z_proj.clamp(min=z_min) x2d_proj = xyz_proj[..., :2] / z_proj x2d_min = -allowed_border - 0.5 x2d_max = img_shapes[..., None, [1, 0]] + (allowed_border - 0.5) if return_clip_mask: x2d_clip_mask = (x2d_proj < x2d_min) | (x2d_proj > x2d_max) clip_mask = z_clip_mask.squeeze(-1) | x2d_clip_mask.any(-1) x2d_proj = torch.min(x2d_proj.clamp(min=x2d_min), x2d_max) if not return_z: if not return_clip_mask: return x2d_proj else: return x2d_proj, clip_mask else: if not return_clip_mask: return x2d_proj, z_proj else: return x2d_proj, z_proj, clip_mask def project_to_image( x3d, pose, cam_intrinsic, img_shapes, z_min=0.5, allowed_border=200, return_z=False, return_clip_mask=False): r_mat = yaw_to_rot_mat(pose[..., 3]) t_vec = pose[..., :3] return project_to_image_r_mat(x3d, r_mat, t_vec, cam_intrinsic, img_shapes, z_min, allowed_border, return_z, return_clip_mask) def yaw_to_rot_mat(yaw): if isinstance(yaw, torch.Tensor): pkg = torch device_kwarg = dict(device=yaw.device) else: pkg = np device_kwarg = dict() sin_yaw = pkg.sin(yaw) cos_yaw = pkg.cos(yaw) rot_mats = pkg.zeros(yaw.shape + (3, 3), dtype=pkg.float32, **device_kwarg) rot_mats[..., 0, 0] = cos_yaw rot_mats[..., 2, 2] = cos_yaw rot_mats[..., 0, 2] = sin_yaw rot_mats[..., 2, 0] = -sin_yaw rot_mats[..., 1, 1] = 1 return rot_mats def rot_mat_to_yaw(rot_mat): if isinstance(rot_mat, torch.Tensor): atan2 = torch.atan2 else: atan2 = np.arctan2 yaw = atan2(rot_mat[..., 0, 2] - rot_mat[..., 2, 0], rot_mat[..., 0, 0] + rot_mat[..., 2, 2]) return yaw def box_mesh(): return Meshes( verts=[torch.tensor([[-1, -1, 1], [ 1, -1, 1], [-1, 1, 1], [ 1, 1, 1], [-1, -1, -1], [ 1, -1, -1], [-1, 1, -1], [ 1, 1, -1]], dtype=torch.float32)], faces=[torch.tensor([[0, 1, 2], [1, 3, 2], [2, 3, 7], [2, 7, 6], [1, 7, 3], [1, 5, 7], [6, 7, 4], [7, 5, 4], [0, 4, 1], [1, 4, 5], [2, 6, 4], [0, 2, 4]], dtype=torch.int)]) def compute_box_3d(bbox_3d): bs = bbox_3d.shape[:-1] rotation_matrix = yaw_to_rot_mat(bbox_3d[..., 6]) edge_corner_idx = np.array([[0, 1], [1, 2], [2, 3], [3, 0], [4, 5], [5, 6], [6, 7], [7, 4], [0, 4], [1, 5], [2, 6], [3, 7]]) corners = np.array([[ 0.5, 0.5, 0.5], [ 0.5, 0.5, -0.5], [-0.5, 0.5, -0.5], [-0.5, 0.5, 0.5], [ 0.5, -0.5, 0.5], [ 0.5, -0.5, -0.5], [-0.5, -0.5, -0.5], [-0.5, -0.5, 0.5]], dtype=np.float32) if isinstance(bbox_3d, torch.Tensor): edge_corner_idx = torch.from_numpy(edge_corner_idx).to(device=bbox_3d.device) corners = torch.from_numpy(corners).to(device=bbox_3d.device) corners = corners * bbox_3d[..., None, :3] corners = (rotation_matrix[..., None, :, :] @ corners[..., None]).reshape(*bs, 8, 3) \ + bbox_3d[..., None, 3:6] return corners, edge_corner_idx def edge_intersection(corners, edge_corner_idx, clip_axis, clip_val, op, edge_valid_mask=None): if op == 'greater': op = torch.greater elif op == 'less': op = torch.less if edge_valid_mask is None: edge_valid_mask = corners.new_ones( (corners.size(0), edge_corner_idx.size(0)), dtype=torch.bool) corners_inside = op(corners[..., clip_axis], clip_val[:, None]) edges_0_inside = corners_inside[:, edge_corner_idx[:, 0]] edges_1_inside = corners_inside[:, edge_corner_idx[:, 1]] edges_clipped = (edges_0_inside ^ edges_1_inside) & edge_valid_mask edges_clipped_idx = edges_clipped.nonzero() if edges_clipped_idx.shape[0] > 0: edge_corner_idx_to_clip = edge_corner_idx[edges_clipped_idx[:, 1], :] edges_0 = corners[edges_clipped_idx[:, 0], edge_corner_idx_to_clip[:, 0], :] edges_1 = corners[edges_clipped_idx[:, 0], edge_corner_idx_to_clip[:, 1], :] axval0 = edges_0[:, clip_axis] axval1 = edges_1[:, clip_axis] clip_val_ = clip_val[edges_clipped_idx[:, 0]] weight_0 = axval1 - clip_val_ weight_1 = clip_val_ - axval0 intersection = (edges_0 * weight_0[:, None] + edges_1 * weight_1[:, None] ) * (1 / (axval1 - axval0)).clamp(min=-1e6, max=1e6)[:, None] clip_idx = torch.where(op(axval0, clip_val_), edge_corner_idx_to_clip[:, 1], edge_corner_idx_to_clip[:, 0]) corners[edges_clipped_idx[:, 0], clip_idx, :] = intersection corners_inside[edges_clipped_idx[:, 0], clip_idx] = True edge_valid_mask &= corners_inside[:, edge_corner_idx[:, 0]] & corners_inside[:, edge_corner_idx[:, 1]] else: edge_valid_mask &= edges_0_inside & edges_1_inside return corners, corners_inside, edge_valid_mask def bboxes_3d_to_2d(bbox_3d, cam_intrinsic, imsize, z_clip=0.1, min_size=4.0, clip=False): assert bbox_3d.dim() == 2 bs = bbox_3d.size(0) if bs > 0: corners, edge_corner_idx = compute_box_3d(bbox_3d) corners, in_front, edge_valid_mask = edge_intersection( corners, edge_corner_idx, 2, corners.new_tensor([z_clip]).expand(bs), 'greater') pts_2d = corners @ cam_intrinsic.transpose(-1, -2) pts_2d = pts_2d[..., :2] / pts_2d[..., 2:].clamp(min=z_clip) + 0.5 in_canvas = in_front if clip: pts_2d, in_canvas_x0, edge_valid_mask = edge_intersection( pts_2d, edge_corner_idx, 0, corners.new_tensor([0]).expand(bs), 'greater', edge_valid_mask) pts_2d, in_canvas_y0, edge_valid_mask = edge_intersection( pts_2d, edge_corner_idx, 1, corners.new_tensor([0]).expand(bs), 'greater', edge_valid_mask) pts_2d, in_canvas_x1, edge_valid_mask = edge_intersection( pts_2d, edge_corner_idx, 0, imsize[:, 1], 'less', edge_valid_mask) pts_2d, in_canvas_y1, edge_valid_mask = edge_intersection( pts_2d, edge_corner_idx, 1, imsize[:, 0], 'less', edge_valid_mask) in_canvas = in_canvas & in_canvas_x0 & in_canvas_x1 & in_canvas_y0 & in_canvas_y1 not_in_canvas = ~in_canvas pts_2d[not_in_canvas] = imsize[:, None, [1, 0]].expand(-1, 8, -1)[not_in_canvas] x0y0 = pts_2d.min(dim=1)[0].clamp(min=0) pts_2d[not_in_canvas] = 0 x1y1 = torch.minimum(pts_2d.max(dim=1)[0], imsize[:, [1, 0]]) bbox = torch.cat((x0y0, x1y1), dim=1) bbox_valid_mask = (x1y1 - x0y0).min(dim=1)[0] >= min_size else: bbox = bbox_3d.new_empty((0, 4)) bbox_valid_mask = bbox_3d.new_empty((0, ), dtype=torch.bool) return bbox, bbox_valid_mask def xywhr2xyxyr(boxes_xywhr): boxes = torch.zeros_like(boxes_xywhr) half_w = boxes_xywhr[:, 2] / 2 half_h = boxes_xywhr[:, 3] / 2 boxes[:, 0] = boxes_xywhr[:, 0] - half_w boxes[:, 1] = boxes_xywhr[:, 1] - half_h boxes[:, 2] = boxes_xywhr[:, 0] + half_w boxes[:, 3] = boxes_xywhr[:, 1] + half_h boxes[:, 4] = boxes_xywhr[:, 4] return boxes def batched_bev_nms(bbox_3d, batch_inds, nms_thr=0.25): n = bbox_3d.size(0) if n > 1: boxes_for_nms = xywhr2xyxyr( bbox_3d[:, [3, 5, 0, 2, 6]]) offset_unit = (boxes_for_nms[:, :4].max() - boxes_for_nms[:, :4].min()) * 2 boxes_for_nms[:, :4] = boxes_for_nms[:, :4] + (offset_unit * batch_inds)[:, None] keep_inds = nms_gpu( boxes_for_nms, bbox_3d[:, 7], nms_thr) else: keep_inds = bbox_3d.new_zeros(0, dtype=torch.int64) bbox_3d_out = bbox_3d[keep_inds] return bbox_3d_out, keep_inds
true
true
f72cab0568521a363e71061115573b79f5eea8ff
22,874
py
Python
sdk/python/pulumi_azure_nextgen/compute/v20191201/virtual_machine.py
pulumi/pulumi-azure-nextgen
452736b0a1cf584c2d4c04666e017af6e9b2c15c
[ "Apache-2.0" ]
31
2020-09-21T09:41:01.000Z
2021-02-26T13:21:59.000Z
sdk/python/pulumi_azure_nextgen/compute/v20191201/virtual_machine.py
pulumi/pulumi-azure-nextgen
452736b0a1cf584c2d4c04666e017af6e9b2c15c
[ "Apache-2.0" ]
231
2020-09-21T09:38:45.000Z
2021-03-01T11:16:03.000Z
sdk/python/pulumi_azure_nextgen/compute/v20191201/virtual_machine.py
pulumi/pulumi-azure-nextgen
452736b0a1cf584c2d4c04666e017af6e9b2c15c
[ "Apache-2.0" ]
4
2020-09-29T14:14:59.000Z
2021-02-10T20:38:16.000Z
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union from ... import _utilities, _tables from . import outputs from ._enums import * from ._inputs import * __all__ = ['VirtualMachine'] class VirtualMachine(pulumi.CustomResource): def __init__(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions] = None, additional_capabilities: Optional[pulumi.Input[pulumi.InputType['AdditionalCapabilitiesArgs']]] = None, availability_set: Optional[pulumi.Input[pulumi.InputType['SubResourceArgs']]] = None, billing_profile: Optional[pulumi.Input[pulumi.InputType['BillingProfileArgs']]] = None, diagnostics_profile: Optional[pulumi.Input[pulumi.InputType['DiagnosticsProfileArgs']]] = None, eviction_policy: Optional[pulumi.Input[Union[str, 'VirtualMachineEvictionPolicyTypes']]] = None, hardware_profile: Optional[pulumi.Input[pulumi.InputType['HardwareProfileArgs']]] = None, host: Optional[pulumi.Input[pulumi.InputType['SubResourceArgs']]] = None, identity: Optional[pulumi.Input[pulumi.InputType['VirtualMachineIdentityArgs']]] = None, license_type: Optional[pulumi.Input[str]] = None, location: Optional[pulumi.Input[str]] = None, network_profile: Optional[pulumi.Input[pulumi.InputType['NetworkProfileArgs']]] = None, os_profile: Optional[pulumi.Input[pulumi.InputType['OSProfileArgs']]] = None, plan: Optional[pulumi.Input[pulumi.InputType['PlanArgs']]] = None, priority: Optional[pulumi.Input[Union[str, 'VirtualMachinePriorityTypes']]] = None, proximity_placement_group: Optional[pulumi.Input[pulumi.InputType['SubResourceArgs']]] = None, resource_group_name: Optional[pulumi.Input[str]] = None, storage_profile: Optional[pulumi.Input[pulumi.InputType['StorageProfileArgs']]] = None, tags: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None, virtual_machine_scale_set: Optional[pulumi.Input[pulumi.InputType['SubResourceArgs']]] = None, vm_name: Optional[pulumi.Input[str]] = None, zones: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None, __props__=None, __name__=None, __opts__=None): """ Describes a Virtual Machine. :param str resource_name: The name of the resource. :param pulumi.ResourceOptions opts: Options for the resource. :param pulumi.Input[pulumi.InputType['AdditionalCapabilitiesArgs']] additional_capabilities: Specifies additional capabilities enabled or disabled on the virtual machine. :param pulumi.Input[pulumi.InputType['SubResourceArgs']] availability_set: Specifies information about the availability set that the virtual machine should be assigned to. Virtual machines specified in the same availability set are allocated to different nodes to maximize availability. For more information about availability sets, see [Manage the availability of virtual machines](https://docs.microsoft.com/azure/virtual-machines/virtual-machines-windows-manage-availability?toc=%2fazure%2fvirtual-machines%2fwindows%2ftoc.json). <br><br> For more information on Azure planned maintenance, see [Planned maintenance for virtual machines in Azure](https://docs.microsoft.com/azure/virtual-machines/virtual-machines-windows-planned-maintenance?toc=%2fazure%2fvirtual-machines%2fwindows%2ftoc.json) <br><br> Currently, a VM can only be added to availability set at creation time. The availability set to which the VM is being added should be under the same resource group as the availability set resource. An existing VM cannot be added to an availability set. <br><br>This property cannot exist along with a non-null properties.virtualMachineScaleSet reference. :param pulumi.Input[pulumi.InputType['BillingProfileArgs']] billing_profile: Specifies the billing related details of a Azure Spot virtual machine. <br><br>Minimum api-version: 2019-03-01. :param pulumi.Input[pulumi.InputType['DiagnosticsProfileArgs']] diagnostics_profile: Specifies the boot diagnostic settings state. <br><br>Minimum api-version: 2015-06-15. :param pulumi.Input[Union[str, 'VirtualMachineEvictionPolicyTypes']] eviction_policy: Specifies the eviction policy for the Azure Spot virtual machine and Azure Spot scale set. <br><br>For Azure Spot virtual machines, both 'Deallocate' and 'Delete' are supported and the minimum api-version is 2019-03-01. <br><br>For Azure Spot scale sets, both 'Deallocate' and 'Delete' are supported and the minimum api-version is 2017-10-30-preview. :param pulumi.Input[pulumi.InputType['HardwareProfileArgs']] hardware_profile: Specifies the hardware settings for the virtual machine. :param pulumi.Input[pulumi.InputType['SubResourceArgs']] host: Specifies information about the dedicated host that the virtual machine resides in. <br><br>Minimum api-version: 2018-10-01. :param pulumi.Input[pulumi.InputType['VirtualMachineIdentityArgs']] identity: The identity of the virtual machine, if configured. :param pulumi.Input[str] license_type: Specifies that the image or disk that is being used was licensed on-premises. This element is only used for images that contain the Windows Server operating system. <br><br> Possible values are: <br><br> Windows_Client <br><br> Windows_Server <br><br> If this element is included in a request for an update, the value must match the initial value. This value cannot be updated. <br><br> For more information, see [Azure Hybrid Use Benefit for Windows Server](https://docs.microsoft.com/azure/virtual-machines/virtual-machines-windows-hybrid-use-benefit-licensing?toc=%2fazure%2fvirtual-machines%2fwindows%2ftoc.json) <br><br> Minimum api-version: 2015-06-15 :param pulumi.Input[str] location: Resource location :param pulumi.Input[pulumi.InputType['NetworkProfileArgs']] network_profile: Specifies the network interfaces of the virtual machine. :param pulumi.Input[pulumi.InputType['OSProfileArgs']] os_profile: Specifies the operating system settings used while creating the virtual machine. Some of the settings cannot be changed once VM is provisioned. :param pulumi.Input[pulumi.InputType['PlanArgs']] plan: Specifies information about the marketplace image used to create the virtual machine. This element is only used for marketplace images. Before you can use a marketplace image from an API, you must enable the image for programmatic use. In the Azure portal, find the marketplace image that you want to use and then click **Want to deploy programmatically, Get Started ->**. Enter any required information and then click **Save**. :param pulumi.Input[Union[str, 'VirtualMachinePriorityTypes']] priority: Specifies the priority for the virtual machine. <br><br>Minimum api-version: 2019-03-01 :param pulumi.Input[pulumi.InputType['SubResourceArgs']] proximity_placement_group: Specifies information about the proximity placement group that the virtual machine should be assigned to. <br><br>Minimum api-version: 2018-04-01. :param pulumi.Input[str] resource_group_name: The name of the resource group. :param pulumi.Input[pulumi.InputType['StorageProfileArgs']] storage_profile: Specifies the storage settings for the virtual machine disks. :param pulumi.Input[Mapping[str, pulumi.Input[str]]] tags: Resource tags :param pulumi.Input[pulumi.InputType['SubResourceArgs']] virtual_machine_scale_set: Specifies information about the virtual machine scale set that the virtual machine should be assigned to. Virtual machines specified in the same virtual machine scale set are allocated to different nodes to maximize availability. Currently, a VM can only be added to virtual machine scale set at creation time. An existing VM cannot be added to a virtual machine scale set. <br><br>This property cannot exist along with a non-null properties.availabilitySet reference. <br><br>Minimum api‐version: 2019‐03‐01 :param pulumi.Input[str] vm_name: The name of the virtual machine. :param pulumi.Input[Sequence[pulumi.Input[str]]] zones: The virtual machine zones. """ if __name__ is not None: warnings.warn("explicit use of __name__ is deprecated", DeprecationWarning) resource_name = __name__ if __opts__ is not None: warnings.warn("explicit use of __opts__ is deprecated, use 'opts' instead", DeprecationWarning) opts = __opts__ if opts is None: opts = pulumi.ResourceOptions() if not isinstance(opts, pulumi.ResourceOptions): raise TypeError('Expected resource options to be a ResourceOptions instance') if opts.version is None: opts.version = _utilities.get_version() if opts.id is None: if __props__ is not None: raise TypeError('__props__ is only valid when passed in combination with a valid opts.id to get an existing resource') __props__ = dict() __props__['additional_capabilities'] = additional_capabilities __props__['availability_set'] = availability_set __props__['billing_profile'] = billing_profile __props__['diagnostics_profile'] = diagnostics_profile __props__['eviction_policy'] = eviction_policy __props__['hardware_profile'] = hardware_profile __props__['host'] = host __props__['identity'] = identity __props__['license_type'] = license_type __props__['location'] = location __props__['network_profile'] = network_profile __props__['os_profile'] = os_profile __props__['plan'] = plan __props__['priority'] = priority __props__['proximity_placement_group'] = proximity_placement_group if resource_group_name is None and not opts.urn: raise TypeError("Missing required property 'resource_group_name'") __props__['resource_group_name'] = resource_group_name __props__['storage_profile'] = storage_profile __props__['tags'] = tags __props__['virtual_machine_scale_set'] = virtual_machine_scale_set __props__['vm_name'] = vm_name __props__['zones'] = zones __props__['instance_view'] = None __props__['name'] = None __props__['provisioning_state'] = None __props__['resources'] = None __props__['type'] = None __props__['vm_id'] = None alias_opts = pulumi.ResourceOptions(aliases=[pulumi.Alias(type_="azure-nextgen:compute:VirtualMachine"), pulumi.Alias(type_="azure-nextgen:compute/latest:VirtualMachine"), pulumi.Alias(type_="azure-nextgen:compute/v20150615:VirtualMachine"), pulumi.Alias(type_="azure-nextgen:compute/v20160330:VirtualMachine"), pulumi.Alias(type_="azure-nextgen:compute/v20160430preview:VirtualMachine"), pulumi.Alias(type_="azure-nextgen:compute/v20170330:VirtualMachine"), pulumi.Alias(type_="azure-nextgen:compute/v20171201:VirtualMachine"), pulumi.Alias(type_="azure-nextgen:compute/v20180401:VirtualMachine"), pulumi.Alias(type_="azure-nextgen:compute/v20180601:VirtualMachine"), pulumi.Alias(type_="azure-nextgen:compute/v20181001:VirtualMachine"), pulumi.Alias(type_="azure-nextgen:compute/v20190301:VirtualMachine"), pulumi.Alias(type_="azure-nextgen:compute/v20190701:VirtualMachine"), pulumi.Alias(type_="azure-nextgen:compute/v20200601:VirtualMachine"), pulumi.Alias(type_="azure-nextgen:compute/v20201201:VirtualMachine")]) opts = pulumi.ResourceOptions.merge(opts, alias_opts) super(VirtualMachine, __self__).__init__( 'azure-nextgen:compute/v20191201:VirtualMachine', resource_name, __props__, opts) @staticmethod def get(resource_name: str, id: pulumi.Input[str], opts: Optional[pulumi.ResourceOptions] = None) -> 'VirtualMachine': """ Get an existing VirtualMachine resource's state with the given name, id, and optional extra properties used to qualify the lookup. :param str resource_name: The unique name of the resulting resource. :param pulumi.Input[str] id: The unique provider ID of the resource to lookup. :param pulumi.ResourceOptions opts: Options for the resource. """ opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id)) __props__ = dict() return VirtualMachine(resource_name, opts=opts, __props__=__props__) @property @pulumi.getter(name="additionalCapabilities") def additional_capabilities(self) -> pulumi.Output[Optional['outputs.AdditionalCapabilitiesResponse']]: """ Specifies additional capabilities enabled or disabled on the virtual machine. """ return pulumi.get(self, "additional_capabilities") @property @pulumi.getter(name="availabilitySet") def availability_set(self) -> pulumi.Output[Optional['outputs.SubResourceResponse']]: """ Specifies information about the availability set that the virtual machine should be assigned to. Virtual machines specified in the same availability set are allocated to different nodes to maximize availability. For more information about availability sets, see [Manage the availability of virtual machines](https://docs.microsoft.com/azure/virtual-machines/virtual-machines-windows-manage-availability?toc=%2fazure%2fvirtual-machines%2fwindows%2ftoc.json). <br><br> For more information on Azure planned maintenance, see [Planned maintenance for virtual machines in Azure](https://docs.microsoft.com/azure/virtual-machines/virtual-machines-windows-planned-maintenance?toc=%2fazure%2fvirtual-machines%2fwindows%2ftoc.json) <br><br> Currently, a VM can only be added to availability set at creation time. The availability set to which the VM is being added should be under the same resource group as the availability set resource. An existing VM cannot be added to an availability set. <br><br>This property cannot exist along with a non-null properties.virtualMachineScaleSet reference. """ return pulumi.get(self, "availability_set") @property @pulumi.getter(name="billingProfile") def billing_profile(self) -> pulumi.Output[Optional['outputs.BillingProfileResponse']]: """ Specifies the billing related details of a Azure Spot virtual machine. <br><br>Minimum api-version: 2019-03-01. """ return pulumi.get(self, "billing_profile") @property @pulumi.getter(name="diagnosticsProfile") def diagnostics_profile(self) -> pulumi.Output[Optional['outputs.DiagnosticsProfileResponse']]: """ Specifies the boot diagnostic settings state. <br><br>Minimum api-version: 2015-06-15. """ return pulumi.get(self, "diagnostics_profile") @property @pulumi.getter(name="evictionPolicy") def eviction_policy(self) -> pulumi.Output[Optional[str]]: """ Specifies the eviction policy for the Azure Spot virtual machine and Azure Spot scale set. <br><br>For Azure Spot virtual machines, both 'Deallocate' and 'Delete' are supported and the minimum api-version is 2019-03-01. <br><br>For Azure Spot scale sets, both 'Deallocate' and 'Delete' are supported and the minimum api-version is 2017-10-30-preview. """ return pulumi.get(self, "eviction_policy") @property @pulumi.getter(name="hardwareProfile") def hardware_profile(self) -> pulumi.Output[Optional['outputs.HardwareProfileResponse']]: """ Specifies the hardware settings for the virtual machine. """ return pulumi.get(self, "hardware_profile") @property @pulumi.getter def host(self) -> pulumi.Output[Optional['outputs.SubResourceResponse']]: """ Specifies information about the dedicated host that the virtual machine resides in. <br><br>Minimum api-version: 2018-10-01. """ return pulumi.get(self, "host") @property @pulumi.getter def identity(self) -> pulumi.Output[Optional['outputs.VirtualMachineIdentityResponse']]: """ The identity of the virtual machine, if configured. """ return pulumi.get(self, "identity") @property @pulumi.getter(name="instanceView") def instance_view(self) -> pulumi.Output['outputs.VirtualMachineInstanceViewResponse']: """ The virtual machine instance view. """ return pulumi.get(self, "instance_view") @property @pulumi.getter(name="licenseType") def license_type(self) -> pulumi.Output[Optional[str]]: """ Specifies that the image or disk that is being used was licensed on-premises. This element is only used for images that contain the Windows Server operating system. <br><br> Possible values are: <br><br> Windows_Client <br><br> Windows_Server <br><br> If this element is included in a request for an update, the value must match the initial value. This value cannot be updated. <br><br> For more information, see [Azure Hybrid Use Benefit for Windows Server](https://docs.microsoft.com/azure/virtual-machines/virtual-machines-windows-hybrid-use-benefit-licensing?toc=%2fazure%2fvirtual-machines%2fwindows%2ftoc.json) <br><br> Minimum api-version: 2015-06-15 """ return pulumi.get(self, "license_type") @property @pulumi.getter def location(self) -> pulumi.Output[str]: """ Resource location """ return pulumi.get(self, "location") @property @pulumi.getter def name(self) -> pulumi.Output[str]: """ Resource name """ return pulumi.get(self, "name") @property @pulumi.getter(name="networkProfile") def network_profile(self) -> pulumi.Output[Optional['outputs.NetworkProfileResponse']]: """ Specifies the network interfaces of the virtual machine. """ return pulumi.get(self, "network_profile") @property @pulumi.getter(name="osProfile") def os_profile(self) -> pulumi.Output[Optional['outputs.OSProfileResponse']]: """ Specifies the operating system settings used while creating the virtual machine. Some of the settings cannot be changed once VM is provisioned. """ return pulumi.get(self, "os_profile") @property @pulumi.getter def plan(self) -> pulumi.Output[Optional['outputs.PlanResponse']]: """ Specifies information about the marketplace image used to create the virtual machine. This element is only used for marketplace images. Before you can use a marketplace image from an API, you must enable the image for programmatic use. In the Azure portal, find the marketplace image that you want to use and then click **Want to deploy programmatically, Get Started ->**. Enter any required information and then click **Save**. """ return pulumi.get(self, "plan") @property @pulumi.getter def priority(self) -> pulumi.Output[Optional[str]]: """ Specifies the priority for the virtual machine. <br><br>Minimum api-version: 2019-03-01 """ return pulumi.get(self, "priority") @property @pulumi.getter(name="provisioningState") def provisioning_state(self) -> pulumi.Output[str]: """ The provisioning state, which only appears in the response. """ return pulumi.get(self, "provisioning_state") @property @pulumi.getter(name="proximityPlacementGroup") def proximity_placement_group(self) -> pulumi.Output[Optional['outputs.SubResourceResponse']]: """ Specifies information about the proximity placement group that the virtual machine should be assigned to. <br><br>Minimum api-version: 2018-04-01. """ return pulumi.get(self, "proximity_placement_group") @property @pulumi.getter def resources(self) -> pulumi.Output[Sequence['outputs.VirtualMachineExtensionResponse']]: """ The virtual machine child extension resources. """ return pulumi.get(self, "resources") @property @pulumi.getter(name="storageProfile") def storage_profile(self) -> pulumi.Output[Optional['outputs.StorageProfileResponse']]: """ Specifies the storage settings for the virtual machine disks. """ return pulumi.get(self, "storage_profile") @property @pulumi.getter def tags(self) -> pulumi.Output[Optional[Mapping[str, str]]]: """ Resource tags """ return pulumi.get(self, "tags") @property @pulumi.getter def type(self) -> pulumi.Output[str]: """ Resource type """ return pulumi.get(self, "type") @property @pulumi.getter(name="virtualMachineScaleSet") def virtual_machine_scale_set(self) -> pulumi.Output[Optional['outputs.SubResourceResponse']]: """ Specifies information about the virtual machine scale set that the virtual machine should be assigned to. Virtual machines specified in the same virtual machine scale set are allocated to different nodes to maximize availability. Currently, a VM can only be added to virtual machine scale set at creation time. An existing VM cannot be added to a virtual machine scale set. <br><br>This property cannot exist along with a non-null properties.availabilitySet reference. <br><br>Minimum api‐version: 2019‐03‐01 """ return pulumi.get(self, "virtual_machine_scale_set") @property @pulumi.getter(name="vmId") def vm_id(self) -> pulumi.Output[str]: """ Specifies the VM unique ID which is a 128-bits identifier that is encoded and stored in all Azure IaaS VMs SMBIOS and can be read using platform BIOS commands. """ return pulumi.get(self, "vm_id") @property @pulumi.getter def zones(self) -> pulumi.Output[Optional[Sequence[str]]]: """ The virtual machine zones. """ return pulumi.get(self, "zones") def translate_output_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop def translate_input_property(self, prop): return _tables.SNAKE_TO_CAMEL_CASE_TABLE.get(prop) or prop
65.354286
1,169
0.707135
import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union from ... import _utilities, _tables from . import outputs from ._enums import * from ._inputs import * __all__ = ['VirtualMachine'] class VirtualMachine(pulumi.CustomResource): def __init__(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions] = None, additional_capabilities: Optional[pulumi.Input[pulumi.InputType['AdditionalCapabilitiesArgs']]] = None, availability_set: Optional[pulumi.Input[pulumi.InputType['SubResourceArgs']]] = None, billing_profile: Optional[pulumi.Input[pulumi.InputType['BillingProfileArgs']]] = None, diagnostics_profile: Optional[pulumi.Input[pulumi.InputType['DiagnosticsProfileArgs']]] = None, eviction_policy: Optional[pulumi.Input[Union[str, 'VirtualMachineEvictionPolicyTypes']]] = None, hardware_profile: Optional[pulumi.Input[pulumi.InputType['HardwareProfileArgs']]] = None, host: Optional[pulumi.Input[pulumi.InputType['SubResourceArgs']]] = None, identity: Optional[pulumi.Input[pulumi.InputType['VirtualMachineIdentityArgs']]] = None, license_type: Optional[pulumi.Input[str]] = None, location: Optional[pulumi.Input[str]] = None, network_profile: Optional[pulumi.Input[pulumi.InputType['NetworkProfileArgs']]] = None, os_profile: Optional[pulumi.Input[pulumi.InputType['OSProfileArgs']]] = None, plan: Optional[pulumi.Input[pulumi.InputType['PlanArgs']]] = None, priority: Optional[pulumi.Input[Union[str, 'VirtualMachinePriorityTypes']]] = None, proximity_placement_group: Optional[pulumi.Input[pulumi.InputType['SubResourceArgs']]] = None, resource_group_name: Optional[pulumi.Input[str]] = None, storage_profile: Optional[pulumi.Input[pulumi.InputType['StorageProfileArgs']]] = None, tags: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None, virtual_machine_scale_set: Optional[pulumi.Input[pulumi.InputType['SubResourceArgs']]] = None, vm_name: Optional[pulumi.Input[str]] = None, zones: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None, __props__=None, __name__=None, __opts__=None): if __name__ is not None: warnings.warn("explicit use of __name__ is deprecated", DeprecationWarning) resource_name = __name__ if __opts__ is not None: warnings.warn("explicit use of __opts__ is deprecated, use 'opts' instead", DeprecationWarning) opts = __opts__ if opts is None: opts = pulumi.ResourceOptions() if not isinstance(opts, pulumi.ResourceOptions): raise TypeError('Expected resource options to be a ResourceOptions instance') if opts.version is None: opts.version = _utilities.get_version() if opts.id is None: if __props__ is not None: raise TypeError('__props__ is only valid when passed in combination with a valid opts.id to get an existing resource') __props__ = dict() __props__['additional_capabilities'] = additional_capabilities __props__['availability_set'] = availability_set __props__['billing_profile'] = billing_profile __props__['diagnostics_profile'] = diagnostics_profile __props__['eviction_policy'] = eviction_policy __props__['hardware_profile'] = hardware_profile __props__['host'] = host __props__['identity'] = identity __props__['license_type'] = license_type __props__['location'] = location __props__['network_profile'] = network_profile __props__['os_profile'] = os_profile __props__['plan'] = plan __props__['priority'] = priority __props__['proximity_placement_group'] = proximity_placement_group if resource_group_name is None and not opts.urn: raise TypeError("Missing required property 'resource_group_name'") __props__['resource_group_name'] = resource_group_name __props__['storage_profile'] = storage_profile __props__['tags'] = tags __props__['virtual_machine_scale_set'] = virtual_machine_scale_set __props__['vm_name'] = vm_name __props__['zones'] = zones __props__['instance_view'] = None __props__['name'] = None __props__['provisioning_state'] = None __props__['resources'] = None __props__['type'] = None __props__['vm_id'] = None alias_opts = pulumi.ResourceOptions(aliases=[pulumi.Alias(type_="azure-nextgen:compute:VirtualMachine"), pulumi.Alias(type_="azure-nextgen:compute/latest:VirtualMachine"), pulumi.Alias(type_="azure-nextgen:compute/v20150615:VirtualMachine"), pulumi.Alias(type_="azure-nextgen:compute/v20160330:VirtualMachine"), pulumi.Alias(type_="azure-nextgen:compute/v20160430preview:VirtualMachine"), pulumi.Alias(type_="azure-nextgen:compute/v20170330:VirtualMachine"), pulumi.Alias(type_="azure-nextgen:compute/v20171201:VirtualMachine"), pulumi.Alias(type_="azure-nextgen:compute/v20180401:VirtualMachine"), pulumi.Alias(type_="azure-nextgen:compute/v20180601:VirtualMachine"), pulumi.Alias(type_="azure-nextgen:compute/v20181001:VirtualMachine"), pulumi.Alias(type_="azure-nextgen:compute/v20190301:VirtualMachine"), pulumi.Alias(type_="azure-nextgen:compute/v20190701:VirtualMachine"), pulumi.Alias(type_="azure-nextgen:compute/v20200601:VirtualMachine"), pulumi.Alias(type_="azure-nextgen:compute/v20201201:VirtualMachine")]) opts = pulumi.ResourceOptions.merge(opts, alias_opts) super(VirtualMachine, __self__).__init__( 'azure-nextgen:compute/v20191201:VirtualMachine', resource_name, __props__, opts) @staticmethod def get(resource_name: str, id: pulumi.Input[str], opts: Optional[pulumi.ResourceOptions] = None) -> 'VirtualMachine': opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id)) __props__ = dict() return VirtualMachine(resource_name, opts=opts, __props__=__props__) @property @pulumi.getter(name="additionalCapabilities") def additional_capabilities(self) -> pulumi.Output[Optional['outputs.AdditionalCapabilitiesResponse']]: return pulumi.get(self, "additional_capabilities") @property @pulumi.getter(name="availabilitySet") def availability_set(self) -> pulumi.Output[Optional['outputs.SubResourceResponse']]: return pulumi.get(self, "availability_set") @property @pulumi.getter(name="billingProfile") def billing_profile(self) -> pulumi.Output[Optional['outputs.BillingProfileResponse']]: return pulumi.get(self, "billing_profile") @property @pulumi.getter(name="diagnosticsProfile") def diagnostics_profile(self) -> pulumi.Output[Optional['outputs.DiagnosticsProfileResponse']]: return pulumi.get(self, "diagnostics_profile") @property @pulumi.getter(name="evictionPolicy") def eviction_policy(self) -> pulumi.Output[Optional[str]]: return pulumi.get(self, "eviction_policy") @property @pulumi.getter(name="hardwareProfile") def hardware_profile(self) -> pulumi.Output[Optional['outputs.HardwareProfileResponse']]: return pulumi.get(self, "hardware_profile") @property @pulumi.getter def host(self) -> pulumi.Output[Optional['outputs.SubResourceResponse']]: return pulumi.get(self, "host") @property @pulumi.getter def identity(self) -> pulumi.Output[Optional['outputs.VirtualMachineIdentityResponse']]: return pulumi.get(self, "identity") @property @pulumi.getter(name="instanceView") def instance_view(self) -> pulumi.Output['outputs.VirtualMachineInstanceViewResponse']: return pulumi.get(self, "instance_view") @property @pulumi.getter(name="licenseType") def license_type(self) -> pulumi.Output[Optional[str]]: return pulumi.get(self, "license_type") @property @pulumi.getter def location(self) -> pulumi.Output[str]: return pulumi.get(self, "location") @property @pulumi.getter def name(self) -> pulumi.Output[str]: return pulumi.get(self, "name") @property @pulumi.getter(name="networkProfile") def network_profile(self) -> pulumi.Output[Optional['outputs.NetworkProfileResponse']]: return pulumi.get(self, "network_profile") @property @pulumi.getter(name="osProfile") def os_profile(self) -> pulumi.Output[Optional['outputs.OSProfileResponse']]: return pulumi.get(self, "os_profile") @property @pulumi.getter def plan(self) -> pulumi.Output[Optional['outputs.PlanResponse']]: return pulumi.get(self, "plan") @property @pulumi.getter def priority(self) -> pulumi.Output[Optional[str]]: return pulumi.get(self, "priority") @property @pulumi.getter(name="provisioningState") def provisioning_state(self) -> pulumi.Output[str]: return pulumi.get(self, "provisioning_state") @property @pulumi.getter(name="proximityPlacementGroup") def proximity_placement_group(self) -> pulumi.Output[Optional['outputs.SubResourceResponse']]: return pulumi.get(self, "proximity_placement_group") @property @pulumi.getter def resources(self) -> pulumi.Output[Sequence['outputs.VirtualMachineExtensionResponse']]: return pulumi.get(self, "resources") @property @pulumi.getter(name="storageProfile") def storage_profile(self) -> pulumi.Output[Optional['outputs.StorageProfileResponse']]: return pulumi.get(self, "storage_profile") @property @pulumi.getter def tags(self) -> pulumi.Output[Optional[Mapping[str, str]]]: return pulumi.get(self, "tags") @property @pulumi.getter def type(self) -> pulumi.Output[str]: return pulumi.get(self, "type") @property @pulumi.getter(name="virtualMachineScaleSet") def virtual_machine_scale_set(self) -> pulumi.Output[Optional['outputs.SubResourceResponse']]: return pulumi.get(self, "virtual_machine_scale_set") @property @pulumi.getter(name="vmId") def vm_id(self) -> pulumi.Output[str]: return pulumi.get(self, "vm_id") @property @pulumi.getter def zones(self) -> pulumi.Output[Optional[Sequence[str]]]: return pulumi.get(self, "zones") def translate_output_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop def translate_input_property(self, prop): return _tables.SNAKE_TO_CAMEL_CASE_TABLE.get(prop) or prop
true
true
f72cab35e960fe08f1ad7e2c27dda165a8cea5a9
352
py
Python
qualysapi/__init__.py
trolldbois/qualysapi
33de3cda1e1073e5c960740e38864d1f551bfd3d
[ "Apache-2.0" ]
4
2019-03-20T14:49:01.000Z
2020-06-19T19:03:54.000Z
qualysapi/__init__.py
trolldbois/qualysapi
33de3cda1e1073e5c960740e38864d1f551bfd3d
[ "Apache-2.0" ]
2
2019-02-05T16:20:44.000Z
2019-02-06T09:50:27.000Z
qualysapi/__init__.py
trolldbois/qualysapi
33de3cda1e1073e5c960740e38864d1f551bfd3d
[ "Apache-2.0" ]
1
2020-06-01T18:57:41.000Z
2020-06-01T18:57:41.000Z
# -*- coding: future_fstrings -*- # This is the version string assigned to the entire egg post # setup.py install # Ownership and Copyright Information. from __future__ import absolute_import __author__ = "Parag Baxi <parag.baxi@gmail.com>" __copyright__ = "Copyright 2011-2013, Parag Baxi" __license__ = "BSD-new" from qualysapi.util import connect
29.333333
60
0.772727
from __future__ import absolute_import __author__ = "Parag Baxi <parag.baxi@gmail.com>" __copyright__ = "Copyright 2011-2013, Parag Baxi" __license__ = "BSD-new" from qualysapi.util import connect
true
true
f72cab98f8c6d40b4cfe232aace0f320986b5a88
607
py
Python
biosimulators_utils/sedml/exceptions.py
biosimulators/Biosimulators_utils
c1363467263120bf1166da2b75e38fc7f56dc94f
[ "MIT" ]
2
2021-06-02T13:26:34.000Z
2021-12-27T23:12:47.000Z
biosimulators_utils/sedml/exceptions.py
biosimulators/Biosimulators_utils
c1363467263120bf1166da2b75e38fc7f56dc94f
[ "MIT" ]
102
2020-12-06T19:47:43.000Z
2022-03-31T12:56:17.000Z
biosimulators_utils/sedml/exceptions.py
biosimulators/Biosimulators_utils
c1363467263120bf1166da2b75e38fc7f56dc94f
[ "MIT" ]
4
2021-01-27T19:56:34.000Z
2022-02-03T21:08:20.000Z
""" Exceptions for SED-ML :Author: Jonathan Karr <karr@mssm.edu> :Date: 2021-01-12 :Copyright: 2021, Center for Reproducible Biomedical Modeling :License: MIT """ from ..exceptions import BioSimulatorsException __all__ = [ 'SedmlExecutionError', 'UnsupportedModelLanguageError', ] class SedmlExecutionError(BioSimulatorsException): """ Error that a SED document could not be executed """ pass # pragma: no cover class UnsupportedModelLanguageError(BioSimulatorsException, NotImplementedError): """ Error that a SED document could not be executed """ pass # pragma: no cover
24.28
81
0.742998
from ..exceptions import BioSimulatorsException __all__ = [ 'SedmlExecutionError', 'UnsupportedModelLanguageError', ] class SedmlExecutionError(BioSimulatorsException): pass class UnsupportedModelLanguageError(BioSimulatorsException, NotImplementedError): pass
true
true
f72cabca4a5200b7b635654d553d20ae2f30155f
3,356
py
Python
tests/bindings/test_python.py
mfkiwl/hgdb
6279b2d671b09094b7e69c592fa8f2eca3f6bacd
[ "BSD-2-Clause" ]
34
2021-01-19T21:14:06.000Z
2022-03-31T18:42:58.000Z
tests/bindings/test_python.py
mfkiwl/hgdb
6279b2d671b09094b7e69c592fa8f2eca3f6bacd
[ "BSD-2-Clause" ]
33
2021-01-12T18:50:16.000Z
2022-03-23T04:49:20.000Z
tests/bindings/test_python.py
mfkiwl/hgdb
6279b2d671b09094b7e69c592fa8f2eca3f6bacd
[ "BSD-2-Clause" ]
2
2021-03-28T06:58:46.000Z
2022-03-31T02:55:53.000Z
import sqlite3 import tempfile import hgdb import os import pytest def get_conn_cursor(db_name): conn = sqlite3.connect(db_name) c = conn.cursor() return conn, c def test_store_instance(): with tempfile.TemporaryDirectory() as temp: db_name = os.path.join(temp, "debug.db") db = hgdb.DebugSymbolTable(db_name) db.store_instance(42, "test") conn, c = get_conn_cursor(db_name) c.execute("SELECT COUNT(*) FROM instance WHERE id=?", (42,)) r = c.fetchone()[0] assert r == 1 conn.close() def test_store_breakpoint(): with tempfile.TemporaryDirectory() as temp: db_name = os.path.join(temp, "debug.db") db = hgdb.DebugSymbolTable(db_name) # no instance matching yet with pytest.raises(hgdb.db.DebugSymbolTableException) as ex: db.store_breakpoint(1, 42, "/tmp/test.py", 1) assert ex.value.args[0] db.store_instance(42, "test") db.store_breakpoint(1, 42, "/tmp/test.py", 1) conn, c = get_conn_cursor(db_name) c.execute("SELECT COUNT(*) FROM breakpoint WHERE filename=? AND line_num=?", ("/tmp/test.py", 1)) r = c.fetchone()[0] assert r == 1 conn.close() def test_store_context_variable(): with tempfile.TemporaryDirectory() as temp: db_name = os.path.join(temp, "debug.db") db = hgdb.DebugSymbolTable(db_name) # no variable matching yet with pytest.raises(hgdb.db.DebugSymbolTableException) as ex: db.store_context_variable("a", 1, 43) assert ex.value.args[0] db.store_instance(42, "test") db.store_breakpoint(1, 42, "/tmp/test.py", 1) db.store_variable(43, "value") db.store_context_variable("a", 1, 43) conn, c = get_conn_cursor(db_name) c.execute("SELECT COUNT(*) FROM context_variable WHERE breakpoint_id=?", (1, )) r = c.fetchone()[0] assert r == 1 conn.close() def test_store_generator_variable(): with tempfile.TemporaryDirectory() as temp: db_name = os.path.join(temp, "debug.db") db = hgdb.DebugSymbolTable(db_name) # no instance matching yet with pytest.raises(hgdb.db.DebugSymbolTableException) as ex: db.store_generator_variable("a", 42, 43) assert ex.value.args[0] db.store_instance(42, "test") db.store_breakpoint(1, 42, "/tmp/test.py", 1) db.store_variable(43, "value") db.store_generator_variable("a", 42, 43) conn, c = get_conn_cursor(db_name) c.execute("SELECT COUNT(*) FROM generator_variable WHERE instance_id=?", (42, )) r = c.fetchone()[0] assert r == 1 conn.close() def test_store_scope(): with tempfile.TemporaryDirectory() as temp: db_name = os.path.join(temp, "debug.db") db = hgdb.DebugSymbolTable(db_name) db.store_instance(42, "test") for i in range(4): db.store_breakpoint(i, 42, "/tmp/test.py", i + 1) db.store_scope(0, *[0, 1, 2, 3]) conn, c = get_conn_cursor(db_name) c.execute("SELECT breakpoints FROM scope WHERE scope=?", (0, )) r = c.fetchone()[0] assert r == " ".join([str(i) for i in range(4)]) conn.close() if __name__ == "__main__": test_store_scope()
31.660377
105
0.61025
import sqlite3 import tempfile import hgdb import os import pytest def get_conn_cursor(db_name): conn = sqlite3.connect(db_name) c = conn.cursor() return conn, c def test_store_instance(): with tempfile.TemporaryDirectory() as temp: db_name = os.path.join(temp, "debug.db") db = hgdb.DebugSymbolTable(db_name) db.store_instance(42, "test") conn, c = get_conn_cursor(db_name) c.execute("SELECT COUNT(*) FROM instance WHERE id=?", (42,)) r = c.fetchone()[0] assert r == 1 conn.close() def test_store_breakpoint(): with tempfile.TemporaryDirectory() as temp: db_name = os.path.join(temp, "debug.db") db = hgdb.DebugSymbolTable(db_name) with pytest.raises(hgdb.db.DebugSymbolTableException) as ex: db.store_breakpoint(1, 42, "/tmp/test.py", 1) assert ex.value.args[0] db.store_instance(42, "test") db.store_breakpoint(1, 42, "/tmp/test.py", 1) conn, c = get_conn_cursor(db_name) c.execute("SELECT COUNT(*) FROM breakpoint WHERE filename=? AND line_num=?", ("/tmp/test.py", 1)) r = c.fetchone()[0] assert r == 1 conn.close() def test_store_context_variable(): with tempfile.TemporaryDirectory() as temp: db_name = os.path.join(temp, "debug.db") db = hgdb.DebugSymbolTable(db_name) with pytest.raises(hgdb.db.DebugSymbolTableException) as ex: db.store_context_variable("a", 1, 43) assert ex.value.args[0] db.store_instance(42, "test") db.store_breakpoint(1, 42, "/tmp/test.py", 1) db.store_variable(43, "value") db.store_context_variable("a", 1, 43) conn, c = get_conn_cursor(db_name) c.execute("SELECT COUNT(*) FROM context_variable WHERE breakpoint_id=?", (1, )) r = c.fetchone()[0] assert r == 1 conn.close() def test_store_generator_variable(): with tempfile.TemporaryDirectory() as temp: db_name = os.path.join(temp, "debug.db") db = hgdb.DebugSymbolTable(db_name) with pytest.raises(hgdb.db.DebugSymbolTableException) as ex: db.store_generator_variable("a", 42, 43) assert ex.value.args[0] db.store_instance(42, "test") db.store_breakpoint(1, 42, "/tmp/test.py", 1) db.store_variable(43, "value") db.store_generator_variable("a", 42, 43) conn, c = get_conn_cursor(db_name) c.execute("SELECT COUNT(*) FROM generator_variable WHERE instance_id=?", (42, )) r = c.fetchone()[0] assert r == 1 conn.close() def test_store_scope(): with tempfile.TemporaryDirectory() as temp: db_name = os.path.join(temp, "debug.db") db = hgdb.DebugSymbolTable(db_name) db.store_instance(42, "test") for i in range(4): db.store_breakpoint(i, 42, "/tmp/test.py", i + 1) db.store_scope(0, *[0, 1, 2, 3]) conn, c = get_conn_cursor(db_name) c.execute("SELECT breakpoints FROM scope WHERE scope=?", (0, )) r = c.fetchone()[0] assert r == " ".join([str(i) for i in range(4)]) conn.close() if __name__ == "__main__": test_store_scope()
true
true
f72cac3af394de7e0476052b87a340105bd5386f
2,482
py
Python
bot.py
StarkGang/TagChecker
390191a03afc17c9003a046954586532947d10d4
[ "MIT" ]
1
2021-07-18T01:12:55.000Z
2021-07-18T01:12:55.000Z
bot.py
StarkGang/TagChecker
390191a03afc17c9003a046954586532947d10d4
[ "MIT" ]
null
null
null
bot.py
StarkGang/TagChecker
390191a03afc17c9003a046954586532947d10d4
[ "MIT" ]
null
null
null
from pyrogram import filters, Client import logging import os from pyrogram.types import ( ChatPermissions, InlineKeyboardButton, InlineKeyboardMarkup ) logging.basicConfig(level=logging.INFO) API_ID = int(os.environ.get("API_ID", 6)) API_HASH = os.environ.get("API_HASH", "eb06d4abfb49dc3eeb1aeb98ae0f581e") TOKEN = os.environ.get("TOKEN", None) TAG = os.environ.get("TAG", None) OWNER_ID = int(os.environ.get("OWNER_ID", 1704673514)) tagcheck = Client( "tagcheck", bot_token=TOKEN, api_id=API_ID, api_hash=API_HASH ) user_s = {} async def is_admin(message): user = await tagcheck.get_chat_member(message.chat.id, message.from_user.id) if user.status in ("administrator", "creator"): return True return False @tagcheck.on_message(filters.command("start") & filters.user(OWNER_ID)) async def start(_, message): await message.reply("I am Alive.") @tagcheck.on_message(filters.group) async def tag_check(_, message): if await is_admin(message): return user = message.from_user.id if TAG not in message.from_user.first_name: try: await tagcheck.restrict_chat_member( message.chat.id, user, ChatPermissions(), ) except BaseException as be: await message.reply(f"**Error:**\n`{be}`") return text = f""" **Heya {message.from_user.mention}** Please add our tag in your name to chat again in the group. **Tag:** `{TAG}` **Note:** __Click The Below Button For Unmuting YourSelf!__ """ await message.reply( text, reply_markup=InlineKeyboardMarkup([ [InlineKeyboardButton("Unmute Me", callback_data="unmute")] ] ) ) user_s.update({"user_id": user}) @tagcheck.on_callback_query(filters.regex("unmute")) async def unmute(client, cb): try: user = user_s["user_id"] except KeyError: await cb.answer( "Oops!\nIts looks like i lost your id from my server\nContact Admins For Unmiting", show_alert=True ) return if cb.from_user.id != user: await cb.answer("This Button is not for you!", show_alert=True) return if TAG in cb.from_user.first_name: await tagcheck.unban_chat_member(cb.message.chat.id, user) await cb.answer("Succesfully Unmuted!") await message.delete() return await cb.answer("Please add tag in your name!", show_alert=True) tagcheck.run()
26.404255
92
0.657937
from pyrogram import filters, Client import logging import os from pyrogram.types import ( ChatPermissions, InlineKeyboardButton, InlineKeyboardMarkup ) logging.basicConfig(level=logging.INFO) API_ID = int(os.environ.get("API_ID", 6)) API_HASH = os.environ.get("API_HASH", "eb06d4abfb49dc3eeb1aeb98ae0f581e") TOKEN = os.environ.get("TOKEN", None) TAG = os.environ.get("TAG", None) OWNER_ID = int(os.environ.get("OWNER_ID", 1704673514)) tagcheck = Client( "tagcheck", bot_token=TOKEN, api_id=API_ID, api_hash=API_HASH ) user_s = {} async def is_admin(message): user = await tagcheck.get_chat_member(message.chat.id, message.from_user.id) if user.status in ("administrator", "creator"): return True return False @tagcheck.on_message(filters.command("start") & filters.user(OWNER_ID)) async def start(_, message): await message.reply("I am Alive.") @tagcheck.on_message(filters.group) async def tag_check(_, message): if await is_admin(message): return user = message.from_user.id if TAG not in message.from_user.first_name: try: await tagcheck.restrict_chat_member( message.chat.id, user, ChatPermissions(), ) except BaseException as be: await message.reply(f"**Error:**\n`{be}`") return text = f""" **Heya {message.from_user.mention}** Please add our tag in your name to chat again in the group. **Tag:** `{TAG}` **Note:** __Click The Below Button For Unmuting YourSelf!__ """ await message.reply( text, reply_markup=InlineKeyboardMarkup([ [InlineKeyboardButton("Unmute Me", callback_data="unmute")] ] ) ) user_s.update({"user_id": user}) @tagcheck.on_callback_query(filters.regex("unmute")) async def unmute(client, cb): try: user = user_s["user_id"] except KeyError: await cb.answer( "Oops!\nIts looks like i lost your id from my server\nContact Admins For Unmiting", show_alert=True ) return if cb.from_user.id != user: await cb.answer("This Button is not for you!", show_alert=True) return if TAG in cb.from_user.first_name: await tagcheck.unban_chat_member(cb.message.chat.id, user) await cb.answer("Succesfully Unmuted!") await message.delete() return await cb.answer("Please add tag in your name!", show_alert=True) tagcheck.run()
true
true
f72cad1a00cbc3a4cfeedd1cef65f5d5f630641b
2,143
py
Python
oneflow/python/framework/watcher.py
666DZY666/oneflow
2062cb211dd1e0619d610659e6d41598d5f73e17
[ "Apache-2.0" ]
null
null
null
oneflow/python/framework/watcher.py
666DZY666/oneflow
2062cb211dd1e0619d610659e6d41598d5f73e17
[ "Apache-2.0" ]
null
null
null
oneflow/python/framework/watcher.py
666DZY666/oneflow
2062cb211dd1e0619d610659e6d41598d5f73e17
[ "Apache-2.0" ]
1
2021-11-10T07:57:01.000Z
2021-11-10T07:57:01.000Z
""" Copyright 2020 The OneFlow Authors. 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 __future__ import absolute_import import traceback import oneflow.core.record.record_pb2 as record_util import oneflow.python.framework.local_blob as local_blob_util import oneflow.python.framework.ofblob as ofblob import oneflow.python.framework.remote_blob as remote_blob_util import oneflow.python.framework.session_context as session_ctx import oneflow.python.framework.typing_util as oft_util import oneflow_api from google.protobuf import text_format def BindUuidAndHandler(uuid, blob_watched, handler): assert isinstance(blob_watched, oneflow_api.ConsistentBlob) session_ctx.GetDefaultSession().uuid2watch_handler[uuid] = (blob_watched, handler) class _Watcher(oneflow_api.ForeignWatcher): def __init__(self): oneflow_api.ForeignWatcher.__init__(self) def Call(self, handler_uuid, of_blob_ptr): try: _WatcherHandler(handler_uuid, of_blob_ptr) except Exception as e: print(traceback.format_exc()) raise e def _WatcherHandler(handler_uuid, of_blob_ptr): uuid2handler = session_ctx.GetDefaultSession().uuid2watch_handler assert handler_uuid in uuid2handler blob_watched, handler = uuid2handler[handler_uuid] assert callable(handler) ndarray_lists = ofblob.OfBlob(of_blob_ptr).CopyToNdarrayLists() local_blob = local_blob_util.MakeLocalBlob(ndarray_lists, blob_watched) handler(oft_util.TransformWatchedBlob(local_blob, handler)) # static lifetime _global_watcher = _Watcher() oneflow_api.RegisterWatcherOnlyOnce(_global_watcher)
35.716667
86
0.792814
from __future__ import absolute_import import traceback import oneflow.core.record.record_pb2 as record_util import oneflow.python.framework.local_blob as local_blob_util import oneflow.python.framework.ofblob as ofblob import oneflow.python.framework.remote_blob as remote_blob_util import oneflow.python.framework.session_context as session_ctx import oneflow.python.framework.typing_util as oft_util import oneflow_api from google.protobuf import text_format def BindUuidAndHandler(uuid, blob_watched, handler): assert isinstance(blob_watched, oneflow_api.ConsistentBlob) session_ctx.GetDefaultSession().uuid2watch_handler[uuid] = (blob_watched, handler) class _Watcher(oneflow_api.ForeignWatcher): def __init__(self): oneflow_api.ForeignWatcher.__init__(self) def Call(self, handler_uuid, of_blob_ptr): try: _WatcherHandler(handler_uuid, of_blob_ptr) except Exception as e: print(traceback.format_exc()) raise e def _WatcherHandler(handler_uuid, of_blob_ptr): uuid2handler = session_ctx.GetDefaultSession().uuid2watch_handler assert handler_uuid in uuid2handler blob_watched, handler = uuid2handler[handler_uuid] assert callable(handler) ndarray_lists = ofblob.OfBlob(of_blob_ptr).CopyToNdarrayLists() local_blob = local_blob_util.MakeLocalBlob(ndarray_lists, blob_watched) handler(oft_util.TransformWatchedBlob(local_blob, handler)) _global_watcher = _Watcher() oneflow_api.RegisterWatcherOnlyOnce(_global_watcher)
true
true
f72cad26cae4ebe6adabb39d7a5dfcd09cf17363
31,637
py
Python
sdk/python/pulumi_f5bigip/ltm/snat.py
pulumi/pulumi-f5bigip
4bce074f8bd7cb42f359ef4814ca5b437230fd1c
[ "ECL-2.0", "Apache-2.0" ]
4
2018-12-21T23:30:33.000Z
2021-10-12T16:38:27.000Z
sdk/python/pulumi_f5bigip/ltm/snat.py
pulumi/pulumi-f5bigip
4bce074f8bd7cb42f359ef4814ca5b437230fd1c
[ "ECL-2.0", "Apache-2.0" ]
61
2019-01-09T01:50:19.000Z
2022-03-31T15:27:17.000Z
sdk/python/pulumi_f5bigip/ltm/snat.py
pulumi/pulumi-f5bigip
4bce074f8bd7cb42f359ef4814ca5b437230fd1c
[ "ECL-2.0", "Apache-2.0" ]
1
2019-10-05T10:36:30.000Z
2019-10-05T10:36:30.000Z
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from .. import _utilities from . import outputs from ._inputs import * __all__ = ['SnatArgs', 'Snat'] @pulumi.input_type class SnatArgs: def __init__(__self__, *, name: pulumi.Input[str], origins: pulumi.Input[Sequence[pulumi.Input['SnatOriginArgs']]], autolasthop: Optional[pulumi.Input[str]] = None, full_path: Optional[pulumi.Input[str]] = None, mirror: Optional[pulumi.Input[str]] = None, partition: Optional[pulumi.Input[str]] = None, snatpool: Optional[pulumi.Input[str]] = None, sourceport: Optional[pulumi.Input[str]] = None, translation: Optional[pulumi.Input[str]] = None, vlans: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None, vlansdisabled: Optional[pulumi.Input[bool]] = None): """ The set of arguments for constructing a Snat resource. :param pulumi.Input[str] name: Name of the snat :param pulumi.Input[Sequence[pulumi.Input['SnatOriginArgs']]] origins: IP or hostname of the snat :param pulumi.Input[str] autolasthop: -(Optional) Specifies whether to automatically map last hop for pools or not. The default is to use next level's default. :param pulumi.Input[str] full_path: Fullpath :param pulumi.Input[str] mirror: Enables or disables mirroring of SNAT connections. :param pulumi.Input[str] partition: Displays the administrative partition within which this profile resides :param pulumi.Input[str] snatpool: Specifies the name of a SNAT pool. You can only use this option when automap and translation are not used. :param pulumi.Input[str] sourceport: Specifies whether the system preserves the source port of the connection. The default is preserve. Use of the preserve-strict setting should be restricted to UDP only under very special circumstances such as nPath or transparent (that is, no translation of any other L3/L4 field), where there is a 1:1 relationship between virtual IP addresses and node addresses, or when clustered multi-processing (CMP) is disabled. The change setting is useful for obfuscating internal network addresses. :param pulumi.Input[str] translation: Specifies the name of a translated IP address. Note that translated addresses are outside the traffic management system. You can only use this option when automap and snatpool are not used. :param pulumi.Input[Sequence[pulumi.Input[str]]] vlans: Specifies the name of the VLAN to which you want to assign the SNAT. The default is vlans-enabled. :param pulumi.Input[bool] vlansdisabled: Disables the SNAT on all VLANs. """ pulumi.set(__self__, "name", name) pulumi.set(__self__, "origins", origins) if autolasthop is not None: pulumi.set(__self__, "autolasthop", autolasthop) if full_path is not None: pulumi.set(__self__, "full_path", full_path) if mirror is not None: pulumi.set(__self__, "mirror", mirror) if partition is not None: pulumi.set(__self__, "partition", partition) if snatpool is not None: pulumi.set(__self__, "snatpool", snatpool) if sourceport is not None: pulumi.set(__self__, "sourceport", sourceport) if translation is not None: pulumi.set(__self__, "translation", translation) if vlans is not None: pulumi.set(__self__, "vlans", vlans) if vlansdisabled is not None: pulumi.set(__self__, "vlansdisabled", vlansdisabled) @property @pulumi.getter def name(self) -> pulumi.Input[str]: """ Name of the snat """ return pulumi.get(self, "name") @name.setter def name(self, value: pulumi.Input[str]): pulumi.set(self, "name", value) @property @pulumi.getter def origins(self) -> pulumi.Input[Sequence[pulumi.Input['SnatOriginArgs']]]: """ IP or hostname of the snat """ return pulumi.get(self, "origins") @origins.setter def origins(self, value: pulumi.Input[Sequence[pulumi.Input['SnatOriginArgs']]]): pulumi.set(self, "origins", value) @property @pulumi.getter def autolasthop(self) -> Optional[pulumi.Input[str]]: """ -(Optional) Specifies whether to automatically map last hop for pools or not. The default is to use next level's default. """ return pulumi.get(self, "autolasthop") @autolasthop.setter def autolasthop(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "autolasthop", value) @property @pulumi.getter(name="fullPath") def full_path(self) -> Optional[pulumi.Input[str]]: """ Fullpath """ return pulumi.get(self, "full_path") @full_path.setter def full_path(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "full_path", value) @property @pulumi.getter def mirror(self) -> Optional[pulumi.Input[str]]: """ Enables or disables mirroring of SNAT connections. """ return pulumi.get(self, "mirror") @mirror.setter def mirror(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "mirror", value) @property @pulumi.getter def partition(self) -> Optional[pulumi.Input[str]]: """ Displays the administrative partition within which this profile resides """ return pulumi.get(self, "partition") @partition.setter def partition(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "partition", value) @property @pulumi.getter def snatpool(self) -> Optional[pulumi.Input[str]]: """ Specifies the name of a SNAT pool. You can only use this option when automap and translation are not used. """ return pulumi.get(self, "snatpool") @snatpool.setter def snatpool(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "snatpool", value) @property @pulumi.getter def sourceport(self) -> Optional[pulumi.Input[str]]: """ Specifies whether the system preserves the source port of the connection. The default is preserve. Use of the preserve-strict setting should be restricted to UDP only under very special circumstances such as nPath or transparent (that is, no translation of any other L3/L4 field), where there is a 1:1 relationship between virtual IP addresses and node addresses, or when clustered multi-processing (CMP) is disabled. The change setting is useful for obfuscating internal network addresses. """ return pulumi.get(self, "sourceport") @sourceport.setter def sourceport(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "sourceport", value) @property @pulumi.getter def translation(self) -> Optional[pulumi.Input[str]]: """ Specifies the name of a translated IP address. Note that translated addresses are outside the traffic management system. You can only use this option when automap and snatpool are not used. """ return pulumi.get(self, "translation") @translation.setter def translation(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "translation", value) @property @pulumi.getter def vlans(self) -> Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]: """ Specifies the name of the VLAN to which you want to assign the SNAT. The default is vlans-enabled. """ return pulumi.get(self, "vlans") @vlans.setter def vlans(self, value: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]): pulumi.set(self, "vlans", value) @property @pulumi.getter def vlansdisabled(self) -> Optional[pulumi.Input[bool]]: """ Disables the SNAT on all VLANs. """ return pulumi.get(self, "vlansdisabled") @vlansdisabled.setter def vlansdisabled(self, value: Optional[pulumi.Input[bool]]): pulumi.set(self, "vlansdisabled", value) @pulumi.input_type class _SnatState: def __init__(__self__, *, autolasthop: Optional[pulumi.Input[str]] = None, full_path: Optional[pulumi.Input[str]] = None, mirror: Optional[pulumi.Input[str]] = None, name: Optional[pulumi.Input[str]] = None, origins: Optional[pulumi.Input[Sequence[pulumi.Input['SnatOriginArgs']]]] = None, partition: Optional[pulumi.Input[str]] = None, snatpool: Optional[pulumi.Input[str]] = None, sourceport: Optional[pulumi.Input[str]] = None, translation: Optional[pulumi.Input[str]] = None, vlans: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None, vlansdisabled: Optional[pulumi.Input[bool]] = None): """ Input properties used for looking up and filtering Snat resources. :param pulumi.Input[str] autolasthop: -(Optional) Specifies whether to automatically map last hop for pools or not. The default is to use next level's default. :param pulumi.Input[str] full_path: Fullpath :param pulumi.Input[str] mirror: Enables or disables mirroring of SNAT connections. :param pulumi.Input[str] name: Name of the snat :param pulumi.Input[Sequence[pulumi.Input['SnatOriginArgs']]] origins: IP or hostname of the snat :param pulumi.Input[str] partition: Displays the administrative partition within which this profile resides :param pulumi.Input[str] snatpool: Specifies the name of a SNAT pool. You can only use this option when automap and translation are not used. :param pulumi.Input[str] sourceport: Specifies whether the system preserves the source port of the connection. The default is preserve. Use of the preserve-strict setting should be restricted to UDP only under very special circumstances such as nPath or transparent (that is, no translation of any other L3/L4 field), where there is a 1:1 relationship between virtual IP addresses and node addresses, or when clustered multi-processing (CMP) is disabled. The change setting is useful for obfuscating internal network addresses. :param pulumi.Input[str] translation: Specifies the name of a translated IP address. Note that translated addresses are outside the traffic management system. You can only use this option when automap and snatpool are not used. :param pulumi.Input[Sequence[pulumi.Input[str]]] vlans: Specifies the name of the VLAN to which you want to assign the SNAT. The default is vlans-enabled. :param pulumi.Input[bool] vlansdisabled: Disables the SNAT on all VLANs. """ if autolasthop is not None: pulumi.set(__self__, "autolasthop", autolasthop) if full_path is not None: pulumi.set(__self__, "full_path", full_path) if mirror is not None: pulumi.set(__self__, "mirror", mirror) if name is not None: pulumi.set(__self__, "name", name) if origins is not None: pulumi.set(__self__, "origins", origins) if partition is not None: pulumi.set(__self__, "partition", partition) if snatpool is not None: pulumi.set(__self__, "snatpool", snatpool) if sourceport is not None: pulumi.set(__self__, "sourceport", sourceport) if translation is not None: pulumi.set(__self__, "translation", translation) if vlans is not None: pulumi.set(__self__, "vlans", vlans) if vlansdisabled is not None: pulumi.set(__self__, "vlansdisabled", vlansdisabled) @property @pulumi.getter def autolasthop(self) -> Optional[pulumi.Input[str]]: """ -(Optional) Specifies whether to automatically map last hop for pools or not. The default is to use next level's default. """ return pulumi.get(self, "autolasthop") @autolasthop.setter def autolasthop(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "autolasthop", value) @property @pulumi.getter(name="fullPath") def full_path(self) -> Optional[pulumi.Input[str]]: """ Fullpath """ return pulumi.get(self, "full_path") @full_path.setter def full_path(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "full_path", value) @property @pulumi.getter def mirror(self) -> Optional[pulumi.Input[str]]: """ Enables or disables mirroring of SNAT connections. """ return pulumi.get(self, "mirror") @mirror.setter def mirror(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "mirror", value) @property @pulumi.getter def name(self) -> Optional[pulumi.Input[str]]: """ Name of the snat """ return pulumi.get(self, "name") @name.setter def name(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "name", value) @property @pulumi.getter def origins(self) -> Optional[pulumi.Input[Sequence[pulumi.Input['SnatOriginArgs']]]]: """ IP or hostname of the snat """ return pulumi.get(self, "origins") @origins.setter def origins(self, value: Optional[pulumi.Input[Sequence[pulumi.Input['SnatOriginArgs']]]]): pulumi.set(self, "origins", value) @property @pulumi.getter def partition(self) -> Optional[pulumi.Input[str]]: """ Displays the administrative partition within which this profile resides """ return pulumi.get(self, "partition") @partition.setter def partition(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "partition", value) @property @pulumi.getter def snatpool(self) -> Optional[pulumi.Input[str]]: """ Specifies the name of a SNAT pool. You can only use this option when automap and translation are not used. """ return pulumi.get(self, "snatpool") @snatpool.setter def snatpool(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "snatpool", value) @property @pulumi.getter def sourceport(self) -> Optional[pulumi.Input[str]]: """ Specifies whether the system preserves the source port of the connection. The default is preserve. Use of the preserve-strict setting should be restricted to UDP only under very special circumstances such as nPath or transparent (that is, no translation of any other L3/L4 field), where there is a 1:1 relationship between virtual IP addresses and node addresses, or when clustered multi-processing (CMP) is disabled. The change setting is useful for obfuscating internal network addresses. """ return pulumi.get(self, "sourceport") @sourceport.setter def sourceport(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "sourceport", value) @property @pulumi.getter def translation(self) -> Optional[pulumi.Input[str]]: """ Specifies the name of a translated IP address. Note that translated addresses are outside the traffic management system. You can only use this option when automap and snatpool are not used. """ return pulumi.get(self, "translation") @translation.setter def translation(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "translation", value) @property @pulumi.getter def vlans(self) -> Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]: """ Specifies the name of the VLAN to which you want to assign the SNAT. The default is vlans-enabled. """ return pulumi.get(self, "vlans") @vlans.setter def vlans(self, value: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]): pulumi.set(self, "vlans", value) @property @pulumi.getter def vlansdisabled(self) -> Optional[pulumi.Input[bool]]: """ Disables the SNAT on all VLANs. """ return pulumi.get(self, "vlansdisabled") @vlansdisabled.setter def vlansdisabled(self, value: Optional[pulumi.Input[bool]]): pulumi.set(self, "vlansdisabled", value) class Snat(pulumi.CustomResource): @overload def __init__(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions] = None, autolasthop: Optional[pulumi.Input[str]] = None, full_path: Optional[pulumi.Input[str]] = None, mirror: Optional[pulumi.Input[str]] = None, name: Optional[pulumi.Input[str]] = None, origins: Optional[pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['SnatOriginArgs']]]]] = None, partition: Optional[pulumi.Input[str]] = None, snatpool: Optional[pulumi.Input[str]] = None, sourceport: Optional[pulumi.Input[str]] = None, translation: Optional[pulumi.Input[str]] = None, vlans: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None, vlansdisabled: Optional[pulumi.Input[bool]] = None, __props__=None): """ `ltm.Snat` Manages a snat configuration For resources should be named with their "full path". The full path is the combination of the partition + name of the resource. For example /Common/my-pool. ## Example Usage ```python import pulumi import pulumi_f5bigip as f5bigip test_snat = f5bigip.ltm.Snat("test-snat", autolasthop="default", full_path="/Common/test-snat", mirror="disabled", name="TEST_SNAT_NAME", origins=[ f5bigip.ltm.SnatOriginArgs( name="2.2.2.2", ), f5bigip.ltm.SnatOriginArgs( name="3.3.3.3", ), ], partition="Common", translation="/Common/136.1.1.1", vlansdisabled=True) ``` :param str resource_name: The name of the resource. :param pulumi.ResourceOptions opts: Options for the resource. :param pulumi.Input[str] autolasthop: -(Optional) Specifies whether to automatically map last hop for pools or not. The default is to use next level's default. :param pulumi.Input[str] full_path: Fullpath :param pulumi.Input[str] mirror: Enables or disables mirroring of SNAT connections. :param pulumi.Input[str] name: Name of the snat :param pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['SnatOriginArgs']]]] origins: IP or hostname of the snat :param pulumi.Input[str] partition: Displays the administrative partition within which this profile resides :param pulumi.Input[str] snatpool: Specifies the name of a SNAT pool. You can only use this option when automap and translation are not used. :param pulumi.Input[str] sourceport: Specifies whether the system preserves the source port of the connection. The default is preserve. Use of the preserve-strict setting should be restricted to UDP only under very special circumstances such as nPath or transparent (that is, no translation of any other L3/L4 field), where there is a 1:1 relationship between virtual IP addresses and node addresses, or when clustered multi-processing (CMP) is disabled. The change setting is useful for obfuscating internal network addresses. :param pulumi.Input[str] translation: Specifies the name of a translated IP address. Note that translated addresses are outside the traffic management system. You can only use this option when automap and snatpool are not used. :param pulumi.Input[Sequence[pulumi.Input[str]]] vlans: Specifies the name of the VLAN to which you want to assign the SNAT. The default is vlans-enabled. :param pulumi.Input[bool] vlansdisabled: Disables the SNAT on all VLANs. """ ... @overload def __init__(__self__, resource_name: str, args: SnatArgs, opts: Optional[pulumi.ResourceOptions] = None): """ `ltm.Snat` Manages a snat configuration For resources should be named with their "full path". The full path is the combination of the partition + name of the resource. For example /Common/my-pool. ## Example Usage ```python import pulumi import pulumi_f5bigip as f5bigip test_snat = f5bigip.ltm.Snat("test-snat", autolasthop="default", full_path="/Common/test-snat", mirror="disabled", name="TEST_SNAT_NAME", origins=[ f5bigip.ltm.SnatOriginArgs( name="2.2.2.2", ), f5bigip.ltm.SnatOriginArgs( name="3.3.3.3", ), ], partition="Common", translation="/Common/136.1.1.1", vlansdisabled=True) ``` :param str resource_name: The name of the resource. :param SnatArgs args: The arguments to use to populate this resource's properties. :param pulumi.ResourceOptions opts: Options for the resource. """ ... def __init__(__self__, resource_name: str, *args, **kwargs): resource_args, opts = _utilities.get_resource_args_opts(SnatArgs, pulumi.ResourceOptions, *args, **kwargs) if resource_args is not None: __self__._internal_init(resource_name, opts, **resource_args.__dict__) else: __self__._internal_init(resource_name, *args, **kwargs) def _internal_init(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions] = None, autolasthop: Optional[pulumi.Input[str]] = None, full_path: Optional[pulumi.Input[str]] = None, mirror: Optional[pulumi.Input[str]] = None, name: Optional[pulumi.Input[str]] = None, origins: Optional[pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['SnatOriginArgs']]]]] = None, partition: Optional[pulumi.Input[str]] = None, snatpool: Optional[pulumi.Input[str]] = None, sourceport: Optional[pulumi.Input[str]] = None, translation: Optional[pulumi.Input[str]] = None, vlans: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None, vlansdisabled: Optional[pulumi.Input[bool]] = None, __props__=None): if opts is None: opts = pulumi.ResourceOptions() if not isinstance(opts, pulumi.ResourceOptions): raise TypeError('Expected resource options to be a ResourceOptions instance') if opts.version is None: opts.version = _utilities.get_version() if opts.id is None: if __props__ is not None: raise TypeError('__props__ is only valid when passed in combination with a valid opts.id to get an existing resource') __props__ = SnatArgs.__new__(SnatArgs) __props__.__dict__["autolasthop"] = autolasthop __props__.__dict__["full_path"] = full_path __props__.__dict__["mirror"] = mirror if name is None and not opts.urn: raise TypeError("Missing required property 'name'") __props__.__dict__["name"] = name if origins is None and not opts.urn: raise TypeError("Missing required property 'origins'") __props__.__dict__["origins"] = origins __props__.__dict__["partition"] = partition __props__.__dict__["snatpool"] = snatpool __props__.__dict__["sourceport"] = sourceport __props__.__dict__["translation"] = translation __props__.__dict__["vlans"] = vlans __props__.__dict__["vlansdisabled"] = vlansdisabled super(Snat, __self__).__init__( 'f5bigip:ltm/snat:Snat', resource_name, __props__, opts) @staticmethod def get(resource_name: str, id: pulumi.Input[str], opts: Optional[pulumi.ResourceOptions] = None, autolasthop: Optional[pulumi.Input[str]] = None, full_path: Optional[pulumi.Input[str]] = None, mirror: Optional[pulumi.Input[str]] = None, name: Optional[pulumi.Input[str]] = None, origins: Optional[pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['SnatOriginArgs']]]]] = None, partition: Optional[pulumi.Input[str]] = None, snatpool: Optional[pulumi.Input[str]] = None, sourceport: Optional[pulumi.Input[str]] = None, translation: Optional[pulumi.Input[str]] = None, vlans: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None, vlansdisabled: Optional[pulumi.Input[bool]] = None) -> 'Snat': """ Get an existing Snat resource's state with the given name, id, and optional extra properties used to qualify the lookup. :param str resource_name: The unique name of the resulting resource. :param pulumi.Input[str] id: The unique provider ID of the resource to lookup. :param pulumi.ResourceOptions opts: Options for the resource. :param pulumi.Input[str] autolasthop: -(Optional) Specifies whether to automatically map last hop for pools or not. The default is to use next level's default. :param pulumi.Input[str] full_path: Fullpath :param pulumi.Input[str] mirror: Enables or disables mirroring of SNAT connections. :param pulumi.Input[str] name: Name of the snat :param pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['SnatOriginArgs']]]] origins: IP or hostname of the snat :param pulumi.Input[str] partition: Displays the administrative partition within which this profile resides :param pulumi.Input[str] snatpool: Specifies the name of a SNAT pool. You can only use this option when automap and translation are not used. :param pulumi.Input[str] sourceport: Specifies whether the system preserves the source port of the connection. The default is preserve. Use of the preserve-strict setting should be restricted to UDP only under very special circumstances such as nPath or transparent (that is, no translation of any other L3/L4 field), where there is a 1:1 relationship between virtual IP addresses and node addresses, or when clustered multi-processing (CMP) is disabled. The change setting is useful for obfuscating internal network addresses. :param pulumi.Input[str] translation: Specifies the name of a translated IP address. Note that translated addresses are outside the traffic management system. You can only use this option when automap and snatpool are not used. :param pulumi.Input[Sequence[pulumi.Input[str]]] vlans: Specifies the name of the VLAN to which you want to assign the SNAT. The default is vlans-enabled. :param pulumi.Input[bool] vlansdisabled: Disables the SNAT on all VLANs. """ opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id)) __props__ = _SnatState.__new__(_SnatState) __props__.__dict__["autolasthop"] = autolasthop __props__.__dict__["full_path"] = full_path __props__.__dict__["mirror"] = mirror __props__.__dict__["name"] = name __props__.__dict__["origins"] = origins __props__.__dict__["partition"] = partition __props__.__dict__["snatpool"] = snatpool __props__.__dict__["sourceport"] = sourceport __props__.__dict__["translation"] = translation __props__.__dict__["vlans"] = vlans __props__.__dict__["vlansdisabled"] = vlansdisabled return Snat(resource_name, opts=opts, __props__=__props__) @property @pulumi.getter def autolasthop(self) -> pulumi.Output[Optional[str]]: """ -(Optional) Specifies whether to automatically map last hop for pools or not. The default is to use next level's default. """ return pulumi.get(self, "autolasthop") @property @pulumi.getter(name="fullPath") def full_path(self) -> pulumi.Output[Optional[str]]: """ Fullpath """ return pulumi.get(self, "full_path") @property @pulumi.getter def mirror(self) -> pulumi.Output[Optional[str]]: """ Enables or disables mirroring of SNAT connections. """ return pulumi.get(self, "mirror") @property @pulumi.getter def name(self) -> pulumi.Output[str]: """ Name of the snat """ return pulumi.get(self, "name") @property @pulumi.getter def origins(self) -> pulumi.Output[Sequence['outputs.SnatOrigin']]: """ IP or hostname of the snat """ return pulumi.get(self, "origins") @property @pulumi.getter def partition(self) -> pulumi.Output[Optional[str]]: """ Displays the administrative partition within which this profile resides """ return pulumi.get(self, "partition") @property @pulumi.getter def snatpool(self) -> pulumi.Output[Optional[str]]: """ Specifies the name of a SNAT pool. You can only use this option when automap and translation are not used. """ return pulumi.get(self, "snatpool") @property @pulumi.getter def sourceport(self) -> pulumi.Output[Optional[str]]: """ Specifies whether the system preserves the source port of the connection. The default is preserve. Use of the preserve-strict setting should be restricted to UDP only under very special circumstances such as nPath or transparent (that is, no translation of any other L3/L4 field), where there is a 1:1 relationship between virtual IP addresses and node addresses, or when clustered multi-processing (CMP) is disabled. The change setting is useful for obfuscating internal network addresses. """ return pulumi.get(self, "sourceport") @property @pulumi.getter def translation(self) -> pulumi.Output[Optional[str]]: """ Specifies the name of a translated IP address. Note that translated addresses are outside the traffic management system. You can only use this option when automap and snatpool are not used. """ return pulumi.get(self, "translation") @property @pulumi.getter def vlans(self) -> pulumi.Output[Optional[Sequence[str]]]: """ Specifies the name of the VLAN to which you want to assign the SNAT. The default is vlans-enabled. """ return pulumi.get(self, "vlans") @property @pulumi.getter def vlansdisabled(self) -> pulumi.Output[Optional[bool]]: """ Disables the SNAT on all VLANs. """ return pulumi.get(self, "vlansdisabled")
46.939169
535
0.649746
import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from .. import _utilities from . import outputs from ._inputs import * __all__ = ['SnatArgs', 'Snat'] @pulumi.input_type class SnatArgs: def __init__(__self__, *, name: pulumi.Input[str], origins: pulumi.Input[Sequence[pulumi.Input['SnatOriginArgs']]], autolasthop: Optional[pulumi.Input[str]] = None, full_path: Optional[pulumi.Input[str]] = None, mirror: Optional[pulumi.Input[str]] = None, partition: Optional[pulumi.Input[str]] = None, snatpool: Optional[pulumi.Input[str]] = None, sourceport: Optional[pulumi.Input[str]] = None, translation: Optional[pulumi.Input[str]] = None, vlans: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None, vlansdisabled: Optional[pulumi.Input[bool]] = None): pulumi.set(__self__, "name", name) pulumi.set(__self__, "origins", origins) if autolasthop is not None: pulumi.set(__self__, "autolasthop", autolasthop) if full_path is not None: pulumi.set(__self__, "full_path", full_path) if mirror is not None: pulumi.set(__self__, "mirror", mirror) if partition is not None: pulumi.set(__self__, "partition", partition) if snatpool is not None: pulumi.set(__self__, "snatpool", snatpool) if sourceport is not None: pulumi.set(__self__, "sourceport", sourceport) if translation is not None: pulumi.set(__self__, "translation", translation) if vlans is not None: pulumi.set(__self__, "vlans", vlans) if vlansdisabled is not None: pulumi.set(__self__, "vlansdisabled", vlansdisabled) @property @pulumi.getter def name(self) -> pulumi.Input[str]: return pulumi.get(self, "name") @name.setter def name(self, value: pulumi.Input[str]): pulumi.set(self, "name", value) @property @pulumi.getter def origins(self) -> pulumi.Input[Sequence[pulumi.Input['SnatOriginArgs']]]: return pulumi.get(self, "origins") @origins.setter def origins(self, value: pulumi.Input[Sequence[pulumi.Input['SnatOriginArgs']]]): pulumi.set(self, "origins", value) @property @pulumi.getter def autolasthop(self) -> Optional[pulumi.Input[str]]: return pulumi.get(self, "autolasthop") @autolasthop.setter def autolasthop(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "autolasthop", value) @property @pulumi.getter(name="fullPath") def full_path(self) -> Optional[pulumi.Input[str]]: return pulumi.get(self, "full_path") @full_path.setter def full_path(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "full_path", value) @property @pulumi.getter def mirror(self) -> Optional[pulumi.Input[str]]: return pulumi.get(self, "mirror") @mirror.setter def mirror(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "mirror", value) @property @pulumi.getter def partition(self) -> Optional[pulumi.Input[str]]: return pulumi.get(self, "partition") @partition.setter def partition(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "partition", value) @property @pulumi.getter def snatpool(self) -> Optional[pulumi.Input[str]]: return pulumi.get(self, "snatpool") @snatpool.setter def snatpool(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "snatpool", value) @property @pulumi.getter def sourceport(self) -> Optional[pulumi.Input[str]]: return pulumi.get(self, "sourceport") @sourceport.setter def sourceport(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "sourceport", value) @property @pulumi.getter def translation(self) -> Optional[pulumi.Input[str]]: return pulumi.get(self, "translation") @translation.setter def translation(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "translation", value) @property @pulumi.getter def vlans(self) -> Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]: return pulumi.get(self, "vlans") @vlans.setter def vlans(self, value: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]): pulumi.set(self, "vlans", value) @property @pulumi.getter def vlansdisabled(self) -> Optional[pulumi.Input[bool]]: return pulumi.get(self, "vlansdisabled") @vlansdisabled.setter def vlansdisabled(self, value: Optional[pulumi.Input[bool]]): pulumi.set(self, "vlansdisabled", value) @pulumi.input_type class _SnatState: def __init__(__self__, *, autolasthop: Optional[pulumi.Input[str]] = None, full_path: Optional[pulumi.Input[str]] = None, mirror: Optional[pulumi.Input[str]] = None, name: Optional[pulumi.Input[str]] = None, origins: Optional[pulumi.Input[Sequence[pulumi.Input['SnatOriginArgs']]]] = None, partition: Optional[pulumi.Input[str]] = None, snatpool: Optional[pulumi.Input[str]] = None, sourceport: Optional[pulumi.Input[str]] = None, translation: Optional[pulumi.Input[str]] = None, vlans: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None, vlansdisabled: Optional[pulumi.Input[bool]] = None): if autolasthop is not None: pulumi.set(__self__, "autolasthop", autolasthop) if full_path is not None: pulumi.set(__self__, "full_path", full_path) if mirror is not None: pulumi.set(__self__, "mirror", mirror) if name is not None: pulumi.set(__self__, "name", name) if origins is not None: pulumi.set(__self__, "origins", origins) if partition is not None: pulumi.set(__self__, "partition", partition) if snatpool is not None: pulumi.set(__self__, "snatpool", snatpool) if sourceport is not None: pulumi.set(__self__, "sourceport", sourceport) if translation is not None: pulumi.set(__self__, "translation", translation) if vlans is not None: pulumi.set(__self__, "vlans", vlans) if vlansdisabled is not None: pulumi.set(__self__, "vlansdisabled", vlansdisabled) @property @pulumi.getter def autolasthop(self) -> Optional[pulumi.Input[str]]: return pulumi.get(self, "autolasthop") @autolasthop.setter def autolasthop(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "autolasthop", value) @property @pulumi.getter(name="fullPath") def full_path(self) -> Optional[pulumi.Input[str]]: return pulumi.get(self, "full_path") @full_path.setter def full_path(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "full_path", value) @property @pulumi.getter def mirror(self) -> Optional[pulumi.Input[str]]: return pulumi.get(self, "mirror") @mirror.setter def mirror(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "mirror", value) @property @pulumi.getter def name(self) -> Optional[pulumi.Input[str]]: return pulumi.get(self, "name") @name.setter def name(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "name", value) @property @pulumi.getter def origins(self) -> Optional[pulumi.Input[Sequence[pulumi.Input['SnatOriginArgs']]]]: return pulumi.get(self, "origins") @origins.setter def origins(self, value: Optional[pulumi.Input[Sequence[pulumi.Input['SnatOriginArgs']]]]): pulumi.set(self, "origins", value) @property @pulumi.getter def partition(self) -> Optional[pulumi.Input[str]]: return pulumi.get(self, "partition") @partition.setter def partition(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "partition", value) @property @pulumi.getter def snatpool(self) -> Optional[pulumi.Input[str]]: return pulumi.get(self, "snatpool") @snatpool.setter def snatpool(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "snatpool", value) @property @pulumi.getter def sourceport(self) -> Optional[pulumi.Input[str]]: return pulumi.get(self, "sourceport") @sourceport.setter def sourceport(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "sourceport", value) @property @pulumi.getter def translation(self) -> Optional[pulumi.Input[str]]: return pulumi.get(self, "translation") @translation.setter def translation(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "translation", value) @property @pulumi.getter def vlans(self) -> Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]: return pulumi.get(self, "vlans") @vlans.setter def vlans(self, value: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]): pulumi.set(self, "vlans", value) @property @pulumi.getter def vlansdisabled(self) -> Optional[pulumi.Input[bool]]: return pulumi.get(self, "vlansdisabled") @vlansdisabled.setter def vlansdisabled(self, value: Optional[pulumi.Input[bool]]): pulumi.set(self, "vlansdisabled", value) class Snat(pulumi.CustomResource): @overload def __init__(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions] = None, autolasthop: Optional[pulumi.Input[str]] = None, full_path: Optional[pulumi.Input[str]] = None, mirror: Optional[pulumi.Input[str]] = None, name: Optional[pulumi.Input[str]] = None, origins: Optional[pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['SnatOriginArgs']]]]] = None, partition: Optional[pulumi.Input[str]] = None, snatpool: Optional[pulumi.Input[str]] = None, sourceport: Optional[pulumi.Input[str]] = None, translation: Optional[pulumi.Input[str]] = None, vlans: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None, vlansdisabled: Optional[pulumi.Input[bool]] = None, __props__=None): ... @overload def __init__(__self__, resource_name: str, args: SnatArgs, opts: Optional[pulumi.ResourceOptions] = None): ... def __init__(__self__, resource_name: str, *args, **kwargs): resource_args, opts = _utilities.get_resource_args_opts(SnatArgs, pulumi.ResourceOptions, *args, **kwargs) if resource_args is not None: __self__._internal_init(resource_name, opts, **resource_args.__dict__) else: __self__._internal_init(resource_name, *args, **kwargs) def _internal_init(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions] = None, autolasthop: Optional[pulumi.Input[str]] = None, full_path: Optional[pulumi.Input[str]] = None, mirror: Optional[pulumi.Input[str]] = None, name: Optional[pulumi.Input[str]] = None, origins: Optional[pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['SnatOriginArgs']]]]] = None, partition: Optional[pulumi.Input[str]] = None, snatpool: Optional[pulumi.Input[str]] = None, sourceport: Optional[pulumi.Input[str]] = None, translation: Optional[pulumi.Input[str]] = None, vlans: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None, vlansdisabled: Optional[pulumi.Input[bool]] = None, __props__=None): if opts is None: opts = pulumi.ResourceOptions() if not isinstance(opts, pulumi.ResourceOptions): raise TypeError('Expected resource options to be a ResourceOptions instance') if opts.version is None: opts.version = _utilities.get_version() if opts.id is None: if __props__ is not None: raise TypeError('__props__ is only valid when passed in combination with a valid opts.id to get an existing resource') __props__ = SnatArgs.__new__(SnatArgs) __props__.__dict__["autolasthop"] = autolasthop __props__.__dict__["full_path"] = full_path __props__.__dict__["mirror"] = mirror if name is None and not opts.urn: raise TypeError("Missing required property 'name'") __props__.__dict__["name"] = name if origins is None and not opts.urn: raise TypeError("Missing required property 'origins'") __props__.__dict__["origins"] = origins __props__.__dict__["partition"] = partition __props__.__dict__["snatpool"] = snatpool __props__.__dict__["sourceport"] = sourceport __props__.__dict__["translation"] = translation __props__.__dict__["vlans"] = vlans __props__.__dict__["vlansdisabled"] = vlansdisabled super(Snat, __self__).__init__( 'f5bigip:ltm/snat:Snat', resource_name, __props__, opts) @staticmethod def get(resource_name: str, id: pulumi.Input[str], opts: Optional[pulumi.ResourceOptions] = None, autolasthop: Optional[pulumi.Input[str]] = None, full_path: Optional[pulumi.Input[str]] = None, mirror: Optional[pulumi.Input[str]] = None, name: Optional[pulumi.Input[str]] = None, origins: Optional[pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['SnatOriginArgs']]]]] = None, partition: Optional[pulumi.Input[str]] = None, snatpool: Optional[pulumi.Input[str]] = None, sourceport: Optional[pulumi.Input[str]] = None, translation: Optional[pulumi.Input[str]] = None, vlans: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None, vlansdisabled: Optional[pulumi.Input[bool]] = None) -> 'Snat': opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id)) __props__ = _SnatState.__new__(_SnatState) __props__.__dict__["autolasthop"] = autolasthop __props__.__dict__["full_path"] = full_path __props__.__dict__["mirror"] = mirror __props__.__dict__["name"] = name __props__.__dict__["origins"] = origins __props__.__dict__["partition"] = partition __props__.__dict__["snatpool"] = snatpool __props__.__dict__["sourceport"] = sourceport __props__.__dict__["translation"] = translation __props__.__dict__["vlans"] = vlans __props__.__dict__["vlansdisabled"] = vlansdisabled return Snat(resource_name, opts=opts, __props__=__props__) @property @pulumi.getter def autolasthop(self) -> pulumi.Output[Optional[str]]: return pulumi.get(self, "autolasthop") @property @pulumi.getter(name="fullPath") def full_path(self) -> pulumi.Output[Optional[str]]: return pulumi.get(self, "full_path") @property @pulumi.getter def mirror(self) -> pulumi.Output[Optional[str]]: return pulumi.get(self, "mirror") @property @pulumi.getter def name(self) -> pulumi.Output[str]: return pulumi.get(self, "name") @property @pulumi.getter def origins(self) -> pulumi.Output[Sequence['outputs.SnatOrigin']]: return pulumi.get(self, "origins") @property @pulumi.getter def partition(self) -> pulumi.Output[Optional[str]]: return pulumi.get(self, "partition") @property @pulumi.getter def snatpool(self) -> pulumi.Output[Optional[str]]: return pulumi.get(self, "snatpool") @property @pulumi.getter def sourceport(self) -> pulumi.Output[Optional[str]]: return pulumi.get(self, "sourceport") @property @pulumi.getter def translation(self) -> pulumi.Output[Optional[str]]: return pulumi.get(self, "translation") @property @pulumi.getter def vlans(self) -> pulumi.Output[Optional[Sequence[str]]]: return pulumi.get(self, "vlans") @property @pulumi.getter def vlansdisabled(self) -> pulumi.Output[Optional[bool]]: return pulumi.get(self, "vlansdisabled")
true
true
f72cad63668c1a50f31829882512b8a9df77f041
12,170
py
Python
keystone-moon/keystone/tests/unit/test_backend_endpoint_policy.py
hashnfv/hashnfv-moon
daaba34fa2ed4426bc0fde359e54a5e1b872208c
[ "Apache-2.0" ]
1
2019-05-08T06:09:35.000Z
2019-05-08T06:09:35.000Z
keystone-moon/keystone/tests/unit/test_backend_endpoint_policy.py
hashnfv/hashnfv-moon
daaba34fa2ed4426bc0fde359e54a5e1b872208c
[ "Apache-2.0" ]
4
2018-08-22T14:51:02.000Z
2018-10-17T14:04:26.000Z
keystone-moon/keystone/tests/unit/test_backend_endpoint_policy.py
hashnfv/hashnfv-moon
daaba34fa2ed4426bc0fde359e54a5e1b872208c
[ "Apache-2.0" ]
5
2018-08-03T17:19:34.000Z
2019-01-11T15:54:42.000Z
# Copyright 2014 IBM Corp. # # 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 uuid from six.moves import range from testtools import matchers from keystone import exception from keystone.tests import unit class PolicyAssociationTests(object): def _assert_correct_policy(self, endpoint, policy): ref = ( self.endpoint_policy_api.get_policy_for_endpoint(endpoint['id'])) self.assertEqual(policy['id'], ref['id']) def _assert_correct_endpoints(self, policy, endpoint_list): endpoint_id_list = [ep['id'] for ep in endpoint_list] endpoints = ( self.endpoint_policy_api.list_endpoints_for_policy(policy['id'])) self.assertThat(endpoints, matchers.HasLength(len(endpoint_list))) for endpoint in endpoints: self.assertIn(endpoint['id'], endpoint_id_list) def load_sample_data(self): """Create sample data to test policy associations. The following data is created: - 3 regions, in a hierarchy, 0 -> 1 -> 2 (where 0 is top) - 3 services - 6 endpoints, 2 in each region, with a mixture of services: 0 - region 0, Service 0 1 - region 0, Service 1 2 - region 1, Service 1 3 - region 1, Service 2 4 - region 2, Service 2 5 - region 2, Service 0 """ def new_endpoint(region_id, service_id): endpoint = unit.new_endpoint_ref(interface='test', region_id=region_id, service_id=service_id, url='/url') self.endpoint.append(self.catalog_api.create_endpoint( endpoint['id'], endpoint)) self.policy = [] self.endpoint = [] self.service = [] self.region = [] parent_region_id = None for i in range(3): policy = unit.new_policy_ref() self.policy.append(self.policy_api.create_policy(policy['id'], policy)) service = unit.new_service_ref() self.service.append(self.catalog_api.create_service(service['id'], service)) region = unit.new_region_ref(parent_region_id=parent_region_id) # Link the regions together as a hierarchy, [0] at the top parent_region_id = region['id'] self.region.append(self.catalog_api.create_region(region)) new_endpoint(self.region[0]['id'], self.service[0]['id']) new_endpoint(self.region[0]['id'], self.service[1]['id']) new_endpoint(self.region[1]['id'], self.service[1]['id']) new_endpoint(self.region[1]['id'], self.service[2]['id']) new_endpoint(self.region[2]['id'], self.service[2]['id']) new_endpoint(self.region[2]['id'], self.service[0]['id']) def test_policy_to_endpoint_association_crud(self): self.endpoint_policy_api.create_policy_association( self.policy[0]['id'], endpoint_id=self.endpoint[0]['id']) self.endpoint_policy_api.check_policy_association( self.policy[0]['id'], endpoint_id=self.endpoint[0]['id']) self.endpoint_policy_api.delete_policy_association( self.policy[0]['id'], endpoint_id=self.endpoint[0]['id']) self.assertRaises(exception.NotFound, self.endpoint_policy_api.check_policy_association, self.policy[0]['id'], endpoint_id=self.endpoint[0]['id']) def test_overwriting_policy_to_endpoint_association(self): self.endpoint_policy_api.create_policy_association( self.policy[0]['id'], endpoint_id=self.endpoint[0]['id']) self.endpoint_policy_api.create_policy_association( self.policy[1]['id'], endpoint_id=self.endpoint[0]['id']) self.assertRaises(exception.NotFound, self.endpoint_policy_api.check_policy_association, self.policy[0]['id'], endpoint_id=self.endpoint[0]['id']) self.endpoint_policy_api.check_policy_association( self.policy[1]['id'], endpoint_id=self.endpoint[0]['id']) def test_invalid_policy_to_endpoint_association(self): self.assertRaises(exception.InvalidPolicyAssociation, self.endpoint_policy_api.create_policy_association, self.policy[0]['id']) self.assertRaises(exception.InvalidPolicyAssociation, self.endpoint_policy_api.create_policy_association, self.policy[0]['id'], endpoint_id=self.endpoint[0]['id'], region_id=self.region[0]['id']) self.assertRaises(exception.InvalidPolicyAssociation, self.endpoint_policy_api.create_policy_association, self.policy[0]['id'], endpoint_id=self.endpoint[0]['id'], service_id=self.service[0]['id']) self.assertRaises(exception.InvalidPolicyAssociation, self.endpoint_policy_api.create_policy_association, self.policy[0]['id'], region_id=self.region[0]['id']) def test_policy_to_explicit_endpoint_association(self): # Associate policy 0 with endpoint 0 self.endpoint_policy_api.create_policy_association( self.policy[0]['id'], endpoint_id=self.endpoint[0]['id']) self._assert_correct_policy(self.endpoint[0], self.policy[0]) self._assert_correct_endpoints(self.policy[0], [self.endpoint[0]]) self.assertRaises(exception.NotFound, self.endpoint_policy_api.get_policy_for_endpoint, uuid.uuid4().hex) def test_policy_to_service_association(self): self.endpoint_policy_api.create_policy_association( self.policy[0]['id'], service_id=self.service[0]['id']) self.endpoint_policy_api.create_policy_association( self.policy[1]['id'], service_id=self.service[1]['id']) # Endpoints 0 and 5 are part of service 0 self._assert_correct_policy(self.endpoint[0], self.policy[0]) self._assert_correct_policy(self.endpoint[5], self.policy[0]) self._assert_correct_endpoints( self.policy[0], [self.endpoint[0], self.endpoint[5]]) # Endpoints 1 and 2 are part of service 1 self._assert_correct_policy(self.endpoint[1], self.policy[1]) self._assert_correct_policy(self.endpoint[2], self.policy[1]) self._assert_correct_endpoints( self.policy[1], [self.endpoint[1], self.endpoint[2]]) def test_policy_to_region_and_service_association(self): self.endpoint_policy_api.create_policy_association( self.policy[0]['id'], service_id=self.service[0]['id'], region_id=self.region[0]['id']) self.endpoint_policy_api.create_policy_association( self.policy[1]['id'], service_id=self.service[1]['id'], region_id=self.region[1]['id']) self.endpoint_policy_api.create_policy_association( self.policy[2]['id'], service_id=self.service[2]['id'], region_id=self.region[2]['id']) # Endpoint 0 is in region 0 with service 0, so should get policy 0 self._assert_correct_policy(self.endpoint[0], self.policy[0]) # Endpoint 5 is in Region 2 with service 0, so should also get # policy 0 by searching up the tree to Region 0 self._assert_correct_policy(self.endpoint[5], self.policy[0]) # Looking the other way round, policy 2 should only be in use by # endpoint 4, since that's the only endpoint in region 2 with the # correct service self._assert_correct_endpoints( self.policy[2], [self.endpoint[4]]) # Policy 1 should only be in use by endpoint 2, since that's the only # endpoint in region 1 (and region 2 below it) with the correct service self._assert_correct_endpoints( self.policy[1], [self.endpoint[2]]) # Policy 0 should be in use by endpoint 0, as well as 5 (since 5 is # of the correct service and in region 2 below it) self._assert_correct_endpoints( self.policy[0], [self.endpoint[0], self.endpoint[5]]) def test_delete_association_by_entity(self): self.endpoint_policy_api.create_policy_association( self.policy[0]['id'], endpoint_id=self.endpoint[0]['id']) self.endpoint_policy_api.delete_association_by_endpoint( self.endpoint[0]['id']) self.assertRaises(exception.NotFound, self.endpoint_policy_api.check_policy_association, self.policy[0]['id'], endpoint_id=self.endpoint[0]['id']) # Make sure deleting it again is silent - since this method is used # in response to notifications by the controller. self.endpoint_policy_api.delete_association_by_endpoint( self.endpoint[0]['id']) # Now try with service - ensure both combined region & service # associations and explicit service ones are removed self.endpoint_policy_api.create_policy_association( self.policy[0]['id'], service_id=self.service[0]['id'], region_id=self.region[0]['id']) self.endpoint_policy_api.create_policy_association( self.policy[1]['id'], service_id=self.service[0]['id'], region_id=self.region[1]['id']) self.endpoint_policy_api.create_policy_association( self.policy[0]['id'], service_id=self.service[0]['id']) self.endpoint_policy_api.delete_association_by_service( self.service[0]['id']) self.assertRaises(exception.NotFound, self.endpoint_policy_api.check_policy_association, self.policy[0]['id'], service_id=self.service[0]['id'], region_id=self.region[0]['id']) self.assertRaises(exception.NotFound, self.endpoint_policy_api.check_policy_association, self.policy[1]['id'], service_id=self.service[0]['id'], region_id=self.region[1]['id']) self.assertRaises(exception.NotFound, self.endpoint_policy_api.check_policy_association, self.policy[0]['id'], service_id=self.service[0]['id']) # Finally, check delete by region self.endpoint_policy_api.create_policy_association( self.policy[0]['id'], service_id=self.service[0]['id'], region_id=self.region[0]['id']) self.endpoint_policy_api.delete_association_by_region( self.region[0]['id']) self.assertRaises(exception.NotFound, self.endpoint_policy_api.check_policy_association, self.policy[0]['id'], service_id=self.service[0]['id'], region_id=self.region[0]['id']) self.assertRaises(exception.NotFound, self.endpoint_policy_api.check_policy_association, self.policy[0]['id'], service_id=self.service[0]['id'])
48.68
79
0.607313
import uuid from six.moves import range from testtools import matchers from keystone import exception from keystone.tests import unit class PolicyAssociationTests(object): def _assert_correct_policy(self, endpoint, policy): ref = ( self.endpoint_policy_api.get_policy_for_endpoint(endpoint['id'])) self.assertEqual(policy['id'], ref['id']) def _assert_correct_endpoints(self, policy, endpoint_list): endpoint_id_list = [ep['id'] for ep in endpoint_list] endpoints = ( self.endpoint_policy_api.list_endpoints_for_policy(policy['id'])) self.assertThat(endpoints, matchers.HasLength(len(endpoint_list))) for endpoint in endpoints: self.assertIn(endpoint['id'], endpoint_id_list) def load_sample_data(self): def new_endpoint(region_id, service_id): endpoint = unit.new_endpoint_ref(interface='test', region_id=region_id, service_id=service_id, url='/url') self.endpoint.append(self.catalog_api.create_endpoint( endpoint['id'], endpoint)) self.policy = [] self.endpoint = [] self.service = [] self.region = [] parent_region_id = None for i in range(3): policy = unit.new_policy_ref() self.policy.append(self.policy_api.create_policy(policy['id'], policy)) service = unit.new_service_ref() self.service.append(self.catalog_api.create_service(service['id'], service)) region = unit.new_region_ref(parent_region_id=parent_region_id) parent_region_id = region['id'] self.region.append(self.catalog_api.create_region(region)) new_endpoint(self.region[0]['id'], self.service[0]['id']) new_endpoint(self.region[0]['id'], self.service[1]['id']) new_endpoint(self.region[1]['id'], self.service[1]['id']) new_endpoint(self.region[1]['id'], self.service[2]['id']) new_endpoint(self.region[2]['id'], self.service[2]['id']) new_endpoint(self.region[2]['id'], self.service[0]['id']) def test_policy_to_endpoint_association_crud(self): self.endpoint_policy_api.create_policy_association( self.policy[0]['id'], endpoint_id=self.endpoint[0]['id']) self.endpoint_policy_api.check_policy_association( self.policy[0]['id'], endpoint_id=self.endpoint[0]['id']) self.endpoint_policy_api.delete_policy_association( self.policy[0]['id'], endpoint_id=self.endpoint[0]['id']) self.assertRaises(exception.NotFound, self.endpoint_policy_api.check_policy_association, self.policy[0]['id'], endpoint_id=self.endpoint[0]['id']) def test_overwriting_policy_to_endpoint_association(self): self.endpoint_policy_api.create_policy_association( self.policy[0]['id'], endpoint_id=self.endpoint[0]['id']) self.endpoint_policy_api.create_policy_association( self.policy[1]['id'], endpoint_id=self.endpoint[0]['id']) self.assertRaises(exception.NotFound, self.endpoint_policy_api.check_policy_association, self.policy[0]['id'], endpoint_id=self.endpoint[0]['id']) self.endpoint_policy_api.check_policy_association( self.policy[1]['id'], endpoint_id=self.endpoint[0]['id']) def test_invalid_policy_to_endpoint_association(self): self.assertRaises(exception.InvalidPolicyAssociation, self.endpoint_policy_api.create_policy_association, self.policy[0]['id']) self.assertRaises(exception.InvalidPolicyAssociation, self.endpoint_policy_api.create_policy_association, self.policy[0]['id'], endpoint_id=self.endpoint[0]['id'], region_id=self.region[0]['id']) self.assertRaises(exception.InvalidPolicyAssociation, self.endpoint_policy_api.create_policy_association, self.policy[0]['id'], endpoint_id=self.endpoint[0]['id'], service_id=self.service[0]['id']) self.assertRaises(exception.InvalidPolicyAssociation, self.endpoint_policy_api.create_policy_association, self.policy[0]['id'], region_id=self.region[0]['id']) def test_policy_to_explicit_endpoint_association(self): self.endpoint_policy_api.create_policy_association( self.policy[0]['id'], endpoint_id=self.endpoint[0]['id']) self._assert_correct_policy(self.endpoint[0], self.policy[0]) self._assert_correct_endpoints(self.policy[0], [self.endpoint[0]]) self.assertRaises(exception.NotFound, self.endpoint_policy_api.get_policy_for_endpoint, uuid.uuid4().hex) def test_policy_to_service_association(self): self.endpoint_policy_api.create_policy_association( self.policy[0]['id'], service_id=self.service[0]['id']) self.endpoint_policy_api.create_policy_association( self.policy[1]['id'], service_id=self.service[1]['id']) self._assert_correct_policy(self.endpoint[0], self.policy[0]) self._assert_correct_policy(self.endpoint[5], self.policy[0]) self._assert_correct_endpoints( self.policy[0], [self.endpoint[0], self.endpoint[5]]) self._assert_correct_policy(self.endpoint[1], self.policy[1]) self._assert_correct_policy(self.endpoint[2], self.policy[1]) self._assert_correct_endpoints( self.policy[1], [self.endpoint[1], self.endpoint[2]]) def test_policy_to_region_and_service_association(self): self.endpoint_policy_api.create_policy_association( self.policy[0]['id'], service_id=self.service[0]['id'], region_id=self.region[0]['id']) self.endpoint_policy_api.create_policy_association( self.policy[1]['id'], service_id=self.service[1]['id'], region_id=self.region[1]['id']) self.endpoint_policy_api.create_policy_association( self.policy[2]['id'], service_id=self.service[2]['id'], region_id=self.region[2]['id']) self._assert_correct_policy(self.endpoint[0], self.policy[0]) self._assert_correct_policy(self.endpoint[5], self.policy[0]) # correct service self._assert_correct_endpoints( self.policy[2], [self.endpoint[4]]) # Policy 1 should only be in use by endpoint 2, since that's the only self._assert_correct_endpoints( self.policy[1], [self.endpoint[2]]) self._assert_correct_endpoints( self.policy[0], [self.endpoint[0], self.endpoint[5]]) def test_delete_association_by_entity(self): self.endpoint_policy_api.create_policy_association( self.policy[0]['id'], endpoint_id=self.endpoint[0]['id']) self.endpoint_policy_api.delete_association_by_endpoint( self.endpoint[0]['id']) self.assertRaises(exception.NotFound, self.endpoint_policy_api.check_policy_association, self.policy[0]['id'], endpoint_id=self.endpoint[0]['id']) self.endpoint_policy_api.delete_association_by_endpoint( self.endpoint[0]['id']) self.endpoint_policy_api.create_policy_association( self.policy[0]['id'], service_id=self.service[0]['id'], region_id=self.region[0]['id']) self.endpoint_policy_api.create_policy_association( self.policy[1]['id'], service_id=self.service[0]['id'], region_id=self.region[1]['id']) self.endpoint_policy_api.create_policy_association( self.policy[0]['id'], service_id=self.service[0]['id']) self.endpoint_policy_api.delete_association_by_service( self.service[0]['id']) self.assertRaises(exception.NotFound, self.endpoint_policy_api.check_policy_association, self.policy[0]['id'], service_id=self.service[0]['id'], region_id=self.region[0]['id']) self.assertRaises(exception.NotFound, self.endpoint_policy_api.check_policy_association, self.policy[1]['id'], service_id=self.service[0]['id'], region_id=self.region[1]['id']) self.assertRaises(exception.NotFound, self.endpoint_policy_api.check_policy_association, self.policy[0]['id'], service_id=self.service[0]['id']) self.endpoint_policy_api.create_policy_association( self.policy[0]['id'], service_id=self.service[0]['id'], region_id=self.region[0]['id']) self.endpoint_policy_api.delete_association_by_region( self.region[0]['id']) self.assertRaises(exception.NotFound, self.endpoint_policy_api.check_policy_association, self.policy[0]['id'], service_id=self.service[0]['id'], region_id=self.region[0]['id']) self.assertRaises(exception.NotFound, self.endpoint_policy_api.check_policy_association, self.policy[0]['id'], service_id=self.service[0]['id'])
true
true
f72cae2c89049bcff133dee51ea839c617f5fd7f
372
py
Python
supervisely/src/mask_image.py
supervisely-ecosystem/ritm-interactive-segmentation
c86df3c7c95ce20ffd3c9cc5e3f07abe8c162f4c
[ "MIT" ]
1
2022-03-25T14:36:18.000Z
2022-03-25T14:36:18.000Z
supervisely/src/mask_image.py
supervisely-ecosystem/ritm-interactive-segmentation
c86df3c7c95ce20ffd3c9cc5e3f07abe8c162f4c
[ "MIT" ]
null
null
null
supervisely/src/mask_image.py
supervisely-ecosystem/ritm-interactive-segmentation
c86df3c7c95ce20ffd3c9cc5e3f07abe8c162f4c
[ "MIT" ]
1
2022-03-17T06:39:39.000Z
2022-03-17T06:39:39.000Z
import sly_globals as g def get_mask_from_clicks(image_np, clicks_list): g.CONTROLLER.set_image(image_np) for click in clicks_list: g.CONTROLLER.add_click(click.coords[1], click.coords[0], click.is_positive) try: res_mask = g.CONTROLLER.result_mask except Exception(f"Couldn't process image"): res_mask = None return res_mask
28.615385
83
0.712366
import sly_globals as g def get_mask_from_clicks(image_np, clicks_list): g.CONTROLLER.set_image(image_np) for click in clicks_list: g.CONTROLLER.add_click(click.coords[1], click.coords[0], click.is_positive) try: res_mask = g.CONTROLLER.result_mask except Exception(f"Couldn't process image"): res_mask = None return res_mask
true
true
f72caed168c08d84dcc3dd7cb27e247c5df1716d
348
py
Python
Algorithms/kadane_algorithm/python-kadane-algorithm-O(n).py
omega07/Yet_Another_Algorithms_Repository
7c967e115e96b3c07010a3bf94ca1cdb898a6e82
[ "MIT" ]
33
2019-10-14T19:19:43.000Z
2021-11-30T13:40:20.000Z
Algorithms/kadane_algorithm/python-kadane-algorithm-O(n).py
omega07/Yet_Another_Algorithms_Repository
7c967e115e96b3c07010a3bf94ca1cdb898a6e82
[ "MIT" ]
317
2019-10-14T18:35:22.000Z
2020-03-03T17:45:06.000Z
Algorithms/kadane_algorithm/python-kadane-algorithm-O(n).py
omega07/Yet_Another_Algorithms_Repository
7c967e115e96b3c07010a3bf94ca1cdb898a6e82
[ "MIT" ]
332
2019-10-14T18:39:08.000Z
2021-09-02T16:19:11.000Z
def maxSubArraySum(a,size): max_so_far =a[0] curr_max = a[0] for i in range(1,size): curr_max = max(a[i], curr_max + a[i]) max_so_far = max(max_so_far,curr_max) return max_so_far a = [-2, -3, 4, -1, -2, 1, 5, -3] print("Maximum contiguous sum is" , maxSubArraySum(a,len(a)))
23.2
61
0.531609
def maxSubArraySum(a,size): max_so_far =a[0] curr_max = a[0] for i in range(1,size): curr_max = max(a[i], curr_max + a[i]) max_so_far = max(max_so_far,curr_max) return max_so_far a = [-2, -3, 4, -1, -2, 1, 5, -3] print("Maximum contiguous sum is" , maxSubArraySum(a,len(a)))
true
true
f72caeec9c99f7dddcbe170095eba9f6591f69ab
910
py
Python
dwavebinarycsp/package_info.py
JoelPasvolsky/dwavebinarycsp
ef260bff6d606d8176b287bb6e27a05d6f72de9f
[ "Apache-2.0" ]
null
null
null
dwavebinarycsp/package_info.py
JoelPasvolsky/dwavebinarycsp
ef260bff6d606d8176b287bb6e27a05d6f72de9f
[ "Apache-2.0" ]
null
null
null
dwavebinarycsp/package_info.py
JoelPasvolsky/dwavebinarycsp
ef260bff6d606d8176b287bb6e27a05d6f72de9f
[ "Apache-2.0" ]
null
null
null
# Copyright 2018 D-Wave Systems Inc. # # 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. # # ================================================================================================ __version__ = '0.1.3' __author__ = 'D-Wave Systems Inc.' __authoremail__ = 'acondello@dwavesys.com' __description__ = 'Solves constraints satisfaction problems with binary quadratic model samplers'
43.333333
98
0.661538
__version__ = '0.1.3' __author__ = 'D-Wave Systems Inc.' __authoremail__ = 'acondello@dwavesys.com' __description__ = 'Solves constraints satisfaction problems with binary quadratic model samplers'
true
true
f72cb12504a8487b6ebb6f694946918cd78f6d7b
267
py
Python
output/models/nist_data/atomic/integer/schema_instance/nistschema_sv_iv_atomic_integer_total_digits_2_xsd/__init__.py
tefra/xsdata-w3c-tests
b6b6a4ac4e0ab610e4b50d868510a8b7105b1a5f
[ "MIT" ]
1
2021-08-14T17:59:21.000Z
2021-08-14T17:59:21.000Z
output/models/nist_data/atomic/integer/schema_instance/nistschema_sv_iv_atomic_integer_total_digits_2_xsd/__init__.py
tefra/xsdata-w3c-tests
b6b6a4ac4e0ab610e4b50d868510a8b7105b1a5f
[ "MIT" ]
4
2020-02-12T21:30:44.000Z
2020-04-15T20:06:46.000Z
output/models/nist_data/atomic/integer/schema_instance/nistschema_sv_iv_atomic_integer_total_digits_2_xsd/__init__.py
tefra/xsdata-w3c-tests
b6b6a4ac4e0ab610e4b50d868510a8b7105b1a5f
[ "MIT" ]
null
null
null
from output.models.nist_data.atomic.integer.schema_instance.nistschema_sv_iv_atomic_integer_total_digits_2_xsd.nistschema_sv_iv_atomic_integer_total_digits_2 import NistschemaSvIvAtomicIntegerTotalDigits2 __all__ = [ "NistschemaSvIvAtomicIntegerTotalDigits2", ]
44.5
204
0.898876
from output.models.nist_data.atomic.integer.schema_instance.nistschema_sv_iv_atomic_integer_total_digits_2_xsd.nistschema_sv_iv_atomic_integer_total_digits_2 import NistschemaSvIvAtomicIntegerTotalDigits2 __all__ = [ "NistschemaSvIvAtomicIntegerTotalDigits2", ]
true
true
f72cb1f015fcd1360def9463bd8e6047da25b737
11,947
py
Python
examples/ex_icub_trust_cognitive_architecture/endorsement.py
riccardobrue/SOM-example-1
8a977e73844f9206ee1704be577f8a7521d2b306
[ "MIT" ]
null
null
null
examples/ex_icub_trust_cognitive_architecture/endorsement.py
riccardobrue/SOM-example-1
8a977e73844f9206ee1704be577f8a7521d2b306
[ "MIT" ]
null
null
null
examples/ex_icub_trust_cognitive_architecture/endorsement.py
riccardobrue/SOM-example-1
8a977e73844f9206ee1704be577f8a7521d2b306
[ "MIT" ]
1
2021-03-16T16:02:16.000Z
2021-03-16T16:02:16.000Z
#!/usr/bin/python # The MIT License (MIT) # # Copyright (c) 2017 Massimiliano Patacchiola # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. #ATTENTION: to work it requires to lunch the iCub world: # yarpserver # ./iCub_SIM # ./iKinGazeCtrl --from configSim.ini # yarpdev --device opencv_grabber # yarp connect /grabber /icubSim/texture/screen # # For the cartesian controller of the left arm # ./simCartesianControl # ./iKinCartesianSolver --context simCartesianControl --part left_arm # PocketSphinx valid Commands are: # The prefix [iCub] or [hey] is optional # learn <object name> # this is a <object name> # forget <object name> # what is this # find the <object name> # stop detection # look at me from speech_recognition import SpeechRecognizer from icub import iCub import cv2 import random import time import os import sys def initialise(): # Initialise the speech recognition engine and the iCub controller my_speech = SpeechRecognizer( hmm_path="/home/massimiliano/pyERA/examples/ex_icub_trust_cognitive_architecture/sphinx/model/en-us/en-us", language_model_path="/home/massimiliano/pyERA/examples/ex_icub_trust_cognitive_architecture/sphinx/model/en-us/en-us.lm.bin", dictionary_path="/home/massimiliano/pyERA/examples/ex_icub_trust_cognitive_architecture/sphinx/data/icub.dic", grammar_path="/home/massimiliano/pyERA/examples/ex_icub_trust_cognitive_architecture/sphinx/data/icub.gram", rule_name='icub.basicCmd', fsg_name="icub") # iCub initialization my_icub = iCub(icub_root='/icubSim') # Load acapela configuration from file my_icub.set_acapela_credential("./acapela_config.csv") account_login, application_login, application_password, service_url = my_icub.get_acapela_credential() print("[ACAPELA]Acapela configuration parameters:") print("Account Login: " + str(account_login)) print("Application Login: " + str(application_login)) print("Account Password: " + str(application_password)) print("Service URL: " + str(service_url)) print("") # Return the objects return my_speech, my_icub def speech_to_action(speech_string): """ Take the sentence from the speech recognition and plan an action <action> = (learn new object | watch | inspect | find | search | look | what | start | stop); <target> = (ball | cup | book | dog | chair | table | at me | is this | movement detection); @param speech_string: @return: """ if speech_string.find('learn') > -1 or speech_string.find('this is a') > -1: response_list = ['I like to learn! This is a ', 'Ok, this is a ', 'I learned a new object, ', ''] object_name = speech_string.rsplit(None, 1)[-1] response_string = response_list[random.randint(0, len(response_list)-1)] + object_name state = 'learn' elif speech_string.find('what is this') > -1: response_string = "" state = 'what' elif speech_string.find('find the') > -1 or speech_string.find('search the') > -1: object_name = speech_string.rsplit(None, 1)[-1] object_path = "./objects/" + str(object_name) + ".png" if not os.path.isfile(object_path): print("[SPEECH-TO-ACTION][WARNING] " + "this file does not exist: " + str(object_path) + "\n") response_string = "Sorry I do not know this object!" state = 'key' else: response_list = ["Ok, now I'm looking for a ", 'Ok I will track the ', 'Ready to track the '] response_string = response_list[random.randint(0, len(response_list)-1)] + object_name state = 'movedetect on' elif speech_string.find('stop detection') > -1: response_list = ["Ok, no more movements", 'Ok I will stop it', "I'm gonna stop it!"] response_string = response_list[random.randint(0, len(response_list)-1)] state = 'movedetect off' elif speech_string.find('look at me') > -1: response_list = ["Ok!", 'Sure!'] response_string = response_list[random.randint(0, len(response_list)-1)] state = 'look' else: response_list = ["Sorry I did not understand.", 'Sorry, can you repeat?', 'Repeat again please.'] response_string = response_list[random.randint(0,len(response_list)-1)] state = 'key' return response_string, state def main(): inputfile = '' outputfile = '' informant_name = '' if len(sys.argv) == 1 or len(sys.argv) > 4: print("python familiarization.py <inputfile> <outputfilename> <informant_name>") elif len(sys.argv) == 4: inputfile = sys.argv[1] outputfile = sys.argv[2] informant_name = sys.argv[3] print("Input file: " + str(inputfile)) print("Output file: " + str(outputfile)) print("Informant Name: " + str(informant_name)) STATE = 'show' speech_string = "" fovea_offset = 40 # side of the fovea square my_speech, my_icub = initialise() is_connected = my_icub.check_connection() if is_connected: print("[STATE Init] intenet connection present.") else: print("[STATE Init][ERROR] internet connection not present!!!") my_icub.say_something(text="I'm ready!") cv2.namedWindow('main') while True: if STATE == 'record': #image = my_icub.return_left_camera_image(mode='BGR') my_speech.record_audio("/tmp/audio.wav", seconds=3, extension='wav', harddev='3,0') raw_file_path = my_speech.convert_to_raw(file_name="/tmp/audio.wav", file_name_raw="/tmp/audio.raw", extension='wav') speech_string = my_speech.return_text_from_audio("/tmp/audio.raw") print("[STATE " + str(STATE) + "] " + "Speech recognised: " + speech_string) STATE = 'understand' elif STATE == 'understand': response_string, local_state = speech_to_action(speech_string) print("[STATE " + str(STATE) + "] " + "Speech recognised: " + speech_string) print("[STATE " + str(STATE) + "] " + "Next state: " + local_state) my_icub.say_something(text=response_string) STATE = local_state elif STATE == 'show': left_image = my_icub.return_left_camera_image(mode='BGR') img_cx = int(left_image.shape[1] / 2) img_cy = int(left_image.shape[0] / 2) cv2.rectangle(left_image, (img_cx-fovea_offset, img_cy-fovea_offset), (img_cx+fovea_offset, img_cy+fovea_offset), (0, 255, 0), 1) cv2.imshow('main', left_image) STATE = 'key' elif STATE == 'movedetect on': object_name = response_string.rsplit(None, 1)[-1] print("[STATE " + str(STATE) + "] " + "start tracking of: " + str(object_name) + "\n") object_path = "./objects/" + str(object_name) + ".png" if my_icub.is_movement_detection(): my_icub.stop_movement_detection() time.sleep(0.5) my_icub.start_movement_detection(template_path=object_path, delay=1.0) else: my_icub.start_movement_detection(template_path=object_path, delay=1.0) STATE = 'key' elif STATE == 'movedetect off': print("[STATE " + str(STATE) + "] " + "stop movement tracking" + "\n") my_icub.stop_movement_detection() time.sleep(0.5) my_icub.reset_head_pose() STATE = 'key' elif STATE == 'look': print("[STATE " + str(STATE) + "] " + "gaze reset" + "\n") my_icub.reset_head_pose() STATE = 'key' elif STATE == 'learn': object_name = response_string.rsplit(None, 1)[-1] print("[STATE " + str(STATE) + "] " + "Learning new object: " + object_name + "\n") left_image = my_icub.return_left_camera_image(mode='BGR') #left_image = image img_cx = int(left_image.shape[1] / 2) img_cy = int(left_image.shape[0] / 2) left_image = left_image[img_cy-fovea_offset:img_cy+fovea_offset, img_cx-fovea_offset:img_cx+fovea_offset] my_icub.learn_object_from_histogram(left_image, object_name) print("[STATE " + str(STATE) + "] " + "Writing new template in ./objects/" + object_name + ".png" + "\n") cv2.imwrite('./objects/' + str(object_name) + '.png', left_image) STATE = 'key' elif STATE == 'what': print("[STATE " + str(STATE) + "] " + "Recalling object from memory..." + "\n") left_image = my_icub.return_left_camera_image(mode='BGR') #left_image = image img_cx = int(left_image.shape[1] / 2) img_cy = int(left_image.shape[0] / 2) left_image = left_image[img_cy-25:img_cy+25, img_cx-25:img_cx+25] object_name = my_icub.recall_object_from_histogram(left_image) if object_name is None: my_icub.say_something("My memory is empty. Teach me something!") else: print("[STATE " + str(STATE) + "] " + "Name returned: " + str(object_name) + "\n") response_list = ["Let me see. I think this is a ", "Let me think. It's a ", "Just a second. It may be a ", "It should be a "] response_string = response_list[random.randint(0, len(response_list) - 1)] my_icub.say_something(response_string + str(object_name)) STATE = 'key' elif STATE == 'key': key_pressed = cv2.waitKey(10) # delay in millisecond if key_pressed==113: #q=QUIT print("[STATE " + str(STATE) + "] " + "Button (q)uit pressed..." + "\n") STATE = "close" elif key_pressed==110: #n= print("[STATE " + str(STATE) + "] " + "Button (n) pressed..." + "\n") elif key_pressed==102: #f= print("[STATE " + str(STATE) + "] " + "Button (f) pressed..." + "\n") elif key_pressed == 114: # r=RECORD print("[STATE " + str(STATE) + "] " + "Button (r)ecord pressed..." + "\n") STATE = "record" else: STATE = 'show' elif STATE == 'close': my_icub.say_something(text="See you soon, bye bye!") my_icub.stop_movement_detection() my_icub.close() cv2.destroyAllWindows() break if __name__ == "__main__": main()
44.913534
133
0.601657
from speech_recognition import SpeechRecognizer from icub import iCub import cv2 import random import time import os import sys def initialise(): my_speech = SpeechRecognizer( hmm_path="/home/massimiliano/pyERA/examples/ex_icub_trust_cognitive_architecture/sphinx/model/en-us/en-us", language_model_path="/home/massimiliano/pyERA/examples/ex_icub_trust_cognitive_architecture/sphinx/model/en-us/en-us.lm.bin", dictionary_path="/home/massimiliano/pyERA/examples/ex_icub_trust_cognitive_architecture/sphinx/data/icub.dic", grammar_path="/home/massimiliano/pyERA/examples/ex_icub_trust_cognitive_architecture/sphinx/data/icub.gram", rule_name='icub.basicCmd', fsg_name="icub") my_icub = iCub(icub_root='/icubSim') my_icub.set_acapela_credential("./acapela_config.csv") account_login, application_login, application_password, service_url = my_icub.get_acapela_credential() print("[ACAPELA]Acapela configuration parameters:") print("Account Login: " + str(account_login)) print("Application Login: " + str(application_login)) print("Account Password: " + str(application_password)) print("Service URL: " + str(service_url)) print("") return my_speech, my_icub def speech_to_action(speech_string): if speech_string.find('learn') > -1 or speech_string.find('this is a') > -1: response_list = ['I like to learn! This is a ', 'Ok, this is a ', 'I learned a new object, ', ''] object_name = speech_string.rsplit(None, 1)[-1] response_string = response_list[random.randint(0, len(response_list)-1)] + object_name state = 'learn' elif speech_string.find('what is this') > -1: response_string = "" state = 'what' elif speech_string.find('find the') > -1 or speech_string.find('search the') > -1: object_name = speech_string.rsplit(None, 1)[-1] object_path = "./objects/" + str(object_name) + ".png" if not os.path.isfile(object_path): print("[SPEECH-TO-ACTION][WARNING] " + "this file does not exist: " + str(object_path) + "\n") response_string = "Sorry I do not know this object!" state = 'key' else: response_list = ["Ok, now I'm looking for a ", 'Ok I will track the ', 'Ready to track the '] response_string = response_list[random.randint(0, len(response_list)-1)] + object_name state = 'movedetect on' elif speech_string.find('stop detection') > -1: response_list = ["Ok, no more movements", 'Ok I will stop it', "I'm gonna stop it!"] response_string = response_list[random.randint(0, len(response_list)-1)] state = 'movedetect off' elif speech_string.find('look at me') > -1: response_list = ["Ok!", 'Sure!'] response_string = response_list[random.randint(0, len(response_list)-1)] state = 'look' else: response_list = ["Sorry I did not understand.", 'Sorry, can you repeat?', 'Repeat again please.'] response_string = response_list[random.randint(0,len(response_list)-1)] state = 'key' return response_string, state def main(): inputfile = '' outputfile = '' informant_name = '' if len(sys.argv) == 1 or len(sys.argv) > 4: print("python familiarization.py <inputfile> <outputfilename> <informant_name>") elif len(sys.argv) == 4: inputfile = sys.argv[1] outputfile = sys.argv[2] informant_name = sys.argv[3] print("Input file: " + str(inputfile)) print("Output file: " + str(outputfile)) print("Informant Name: " + str(informant_name)) STATE = 'show' speech_string = "" fovea_offset = 40 my_speech, my_icub = initialise() is_connected = my_icub.check_connection() if is_connected: print("[STATE Init] intenet connection present.") else: print("[STATE Init][ERROR] internet connection not present!!!") my_icub.say_something(text="I'm ready!") cv2.namedWindow('main') while True: if STATE == 'record': #image = my_icub.return_left_camera_image(mode='BGR') my_speech.record_audio("/tmp/audio.wav", seconds=3, extension='wav', harddev='3,0') raw_file_path = my_speech.convert_to_raw(file_name="/tmp/audio.wav", file_name_raw="/tmp/audio.raw", extension='wav') speech_string = my_speech.return_text_from_audio("/tmp/audio.raw") print("[STATE " + str(STATE) + "] " + "Speech recognised: " + speech_string) STATE = 'understand' elif STATE == 'understand': response_string, local_state = speech_to_action(speech_string) print("[STATE " + str(STATE) + "] " + "Speech recognised: " + speech_string) print("[STATE " + str(STATE) + "] " + "Next state: " + local_state) my_icub.say_something(text=response_string) STATE = local_state elif STATE == 'show': left_image = my_icub.return_left_camera_image(mode='BGR') img_cx = int(left_image.shape[1] / 2) img_cy = int(left_image.shape[0] / 2) cv2.rectangle(left_image, (img_cx-fovea_offset, img_cy-fovea_offset), (img_cx+fovea_offset, img_cy+fovea_offset), (0, 255, 0), 1) cv2.imshow('main', left_image) STATE = 'key' elif STATE == 'movedetect on': object_name = response_string.rsplit(None, 1)[-1] print("[STATE " + str(STATE) + "] " + "start tracking of: " + str(object_name) + "\n") object_path = "./objects/" + str(object_name) + ".png" if my_icub.is_movement_detection(): my_icub.stop_movement_detection() time.sleep(0.5) my_icub.start_movement_detection(template_path=object_path, delay=1.0) else: my_icub.start_movement_detection(template_path=object_path, delay=1.0) STATE = 'key' elif STATE == 'movedetect off': print("[STATE " + str(STATE) + "] " + "stop movement tracking" + "\n") my_icub.stop_movement_detection() time.sleep(0.5) my_icub.reset_head_pose() STATE = 'key' elif STATE == 'look': print("[STATE " + str(STATE) + "] " + "gaze reset" + "\n") my_icub.reset_head_pose() STATE = 'key' elif STATE == 'learn': object_name = response_string.rsplit(None, 1)[-1] print("[STATE " + str(STATE) + "] " + "Learning new object: " + object_name + "\n") left_image = my_icub.return_left_camera_image(mode='BGR') #left_image = image img_cx = int(left_image.shape[1] / 2) img_cy = int(left_image.shape[0] / 2) left_image = left_image[img_cy-fovea_offset:img_cy+fovea_offset, img_cx-fovea_offset:img_cx+fovea_offset] my_icub.learn_object_from_histogram(left_image, object_name) print("[STATE " + str(STATE) + "] " + "Writing new template in ./objects/" + object_name + ".png" + "\n") cv2.imwrite('./objects/' + str(object_name) + '.png', left_image) STATE = 'key' elif STATE == 'what': print("[STATE " + str(STATE) + "] " + "Recalling object from memory..." + "\n") left_image = my_icub.return_left_camera_image(mode='BGR') #left_image = image img_cx = int(left_image.shape[1] / 2) img_cy = int(left_image.shape[0] / 2) left_image = left_image[img_cy-25:img_cy+25, img_cx-25:img_cx+25] object_name = my_icub.recall_object_from_histogram(left_image) if object_name is None: my_icub.say_something("My memory is empty. Teach me something!") else: print("[STATE " + str(STATE) + "] " + "Name returned: " + str(object_name) + "\n") response_list = ["Let me see. I think this is a ", "Let me think. It's a ", "Just a second. It may be a ", "It should be a "] response_string = response_list[random.randint(0, len(response_list) - 1)] my_icub.say_something(response_string + str(object_name)) STATE = 'key' elif STATE == 'key': key_pressed = cv2.waitKey(10) if key_pressed==113: print("[STATE " + str(STATE) + "] " + "Button (q)uit pressed..." + "\n") STATE = "close" elif key_pressed==110: print("[STATE " + str(STATE) + "] " + "Button (n) pressed..." + "\n") elif key_pressed==102: print("[STATE " + str(STATE) + "] " + "Button (f) pressed..." + "\n") elif key_pressed == 114: print("[STATE " + str(STATE) + "] " + "Button (r)ecord pressed..." + "\n") STATE = "record" else: STATE = 'show' elif STATE == 'close': my_icub.say_something(text="See you soon, bye bye!") my_icub.stop_movement_detection() my_icub.close() cv2.destroyAllWindows() break if __name__ == "__main__": main()
true
true
f72cb22b484e4768378d4a3b0201733382c540d7
2,332
py
Python
tests/integration/test_sdv.py
joanvaquer/SDV
83e4fdf0ff72e6c5b72cfc8c6ec9584dbd34de28
[ "MIT" ]
null
null
null
tests/integration/test_sdv.py
joanvaquer/SDV
83e4fdf0ff72e6c5b72cfc8c6ec9584dbd34de28
[ "MIT" ]
null
null
null
tests/integration/test_sdv.py
joanvaquer/SDV
83e4fdf0ff72e6c5b72cfc8c6ec9584dbd34de28
[ "MIT" ]
null
null
null
from sdv import SDV, load_demo def test_sdv(): metadata, tables = load_demo(metadata=True) sdv = SDV() sdv.fit(metadata, tables) # Sample all sampled = sdv.sample_all() assert set(sampled.keys()) == {'users', 'sessions', 'transactions'} assert len(sampled['users']) == 10 # Sample with children sampled = sdv.sample('users', reset_primary_keys=True) assert set(sampled.keys()) == {'users', 'sessions', 'transactions'} assert len(sampled['users']) == 10 # Sample without children users = sdv.sample('users', sample_children=False) assert users.shape == tables['users'].shape assert set(users.columns) == set(tables['users'].columns) sessions = sdv.sample('sessions', sample_children=False) assert sessions.shape == tables['sessions'].shape assert set(sessions.columns) == set(tables['sessions'].columns) transactions = sdv.sample('transactions', sample_children=False) assert transactions.shape == tables['transactions'].shape assert set(transactions.columns) == set(tables['transactions'].columns) def test_sdv_multiparent(): metadata, tables = load_demo('got_families', metadata=True) sdv = SDV() sdv.fit(metadata, tables) # Sample all sampled = sdv.sample_all() assert set(sampled.keys()) == {'characters', 'families', 'character_families'} assert len(sampled['characters']) == 7 # Sample with children sampled = sdv.sample('characters', reset_primary_keys=True) assert set(sampled.keys()) == {'characters', 'character_families'} assert len(sampled['characters']) == 7 assert 'family_id' in sampled['character_families'] # Sample without children characters = sdv.sample('characters', sample_children=False) assert characters.shape == tables['characters'].shape assert set(characters.columns) == set(tables['characters'].columns) families = sdv.sample('families', sample_children=False) assert families.shape == tables['families'].shape assert set(families.columns) == set(tables['families'].columns) character_families = sdv.sample('character_families', sample_children=False) assert character_families.shape == tables['character_families'].shape assert set(character_families.columns) == set(tables['character_families'].columns)
31.945205
87
0.694683
from sdv import SDV, load_demo def test_sdv(): metadata, tables = load_demo(metadata=True) sdv = SDV() sdv.fit(metadata, tables) sampled = sdv.sample_all() assert set(sampled.keys()) == {'users', 'sessions', 'transactions'} assert len(sampled['users']) == 10 sampled = sdv.sample('users', reset_primary_keys=True) assert set(sampled.keys()) == {'users', 'sessions', 'transactions'} assert len(sampled['users']) == 10 users = sdv.sample('users', sample_children=False) assert users.shape == tables['users'].shape assert set(users.columns) == set(tables['users'].columns) sessions = sdv.sample('sessions', sample_children=False) assert sessions.shape == tables['sessions'].shape assert set(sessions.columns) == set(tables['sessions'].columns) transactions = sdv.sample('transactions', sample_children=False) assert transactions.shape == tables['transactions'].shape assert set(transactions.columns) == set(tables['transactions'].columns) def test_sdv_multiparent(): metadata, tables = load_demo('got_families', metadata=True) sdv = SDV() sdv.fit(metadata, tables) sampled = sdv.sample_all() assert set(sampled.keys()) == {'characters', 'families', 'character_families'} assert len(sampled['characters']) == 7 sampled = sdv.sample('characters', reset_primary_keys=True) assert set(sampled.keys()) == {'characters', 'character_families'} assert len(sampled['characters']) == 7 assert 'family_id' in sampled['character_families'] characters = sdv.sample('characters', sample_children=False) assert characters.shape == tables['characters'].shape assert set(characters.columns) == set(tables['characters'].columns) families = sdv.sample('families', sample_children=False) assert families.shape == tables['families'].shape assert set(families.columns) == set(tables['families'].columns) character_families = sdv.sample('character_families', sample_children=False) assert character_families.shape == tables['character_families'].shape assert set(character_families.columns) == set(tables['character_families'].columns)
true
true
f72cb255bbd9dbaa14f82003586431b14c8cdf93
340
py
Python
WebApp/admin.py
divij-pherwani/PythonProject
3ba262be580022cffc840f4cf967363eb7d3417b
[ "MIT" ]
null
null
null
WebApp/admin.py
divij-pherwani/PythonProject
3ba262be580022cffc840f4cf967363eb7d3417b
[ "MIT" ]
null
null
null
WebApp/admin.py
divij-pherwani/PythonProject
3ba262be580022cffc840f4cf967363eb7d3417b
[ "MIT" ]
null
null
null
from django.contrib import admin from .models import StudentDetail, UniversityDetail, CourseDetail, CourseName, ApplicationDetail admin.site.register(StudentDetail) admin.site.register(UniversityDetail) admin.site.register(CourseDetail) admin.site.register(CourseName) admin.site.register(ApplicationDetail) # Register your models here.
28.333333
96
0.844118
from django.contrib import admin from .models import StudentDetail, UniversityDetail, CourseDetail, CourseName, ApplicationDetail admin.site.register(StudentDetail) admin.site.register(UniversityDetail) admin.site.register(CourseDetail) admin.site.register(CourseName) admin.site.register(ApplicationDetail)
true
true
f72cb2583a8f94f5dbbfd81abcd00d5e5a7903fa
2,490
py
Python
serpcord/models/guild.py
PgBiel/serpcord
482736dc691027417edcd6500cdfbf9053f92b63
[ "MIT" ]
null
null
null
serpcord/models/guild.py
PgBiel/serpcord
482736dc691027417edcd6500cdfbf9053f92b63
[ "MIT" ]
null
null
null
serpcord/models/guild.py
PgBiel/serpcord
482736dc691027417edcd6500cdfbf9053f92b63
[ "MIT" ]
null
null
null
import typing import datetime from typing import Mapping, Any, Optional, Iterable, List from .model_abc import JsonAPIModel from .snowflake import Snowflake from .user import User from .enums import PermissionFlags from .permissions import Role from serpcord.utils.model import _init_model_from_mapping_json_data if typing.TYPE_CHECKING: from serpcord.botclient import BotClient class GuildMember(JsonAPIModel[Mapping[str, Any]]): # TODO: Optional[Guild] - make sure the guild itself adds itself def __init__(self, client: "BotClient", user: User, # TODO: docs + slots *, nick: Optional[str] = None, guild_avatar_hash: Optional[str] = None, role_ids: Iterable[Snowflake], roles: Iterable[Role], joined_at: datetime.datetime, premium_since: Optional[datetime.datetime] = None, is_deaf: bool, is_muted: bool, is_pending: bool = False, permissions: Optional[PermissionFlags] = None, communication_disabled_until: Optional[datetime.datetime] = None): self.client: "BotClient" = client self.user: User = user # NOTE: Must be injected in MESSAGE_CREATE / MESSAGE_UPDATE events (not provided by API) self.nick: Optional[str] = str(nick) if nick is not None else None self.guild_avatar_hash: Optional[str] = str(guild_avatar_hash) if guild_avatar_hash is not None else None self.role_ids: List[Snowflake] = list(role_ids) self.joined_at: datetime.datetime = joined_at self.premium_since: Optional[datetime.datetime] = premium_since self.is_deaf = bool(is_deaf) self.is_muted = bool(is_muted) self.is_pending = bool(is_pending) self.permissions = PermissionFlags(permissions) if permissions is not None else None self.communication_disabled_until: Optional[datetime.datetime] = communication_disabled_until @property def id(self) -> Snowflake: return self.user.id @property def username(self) -> str: return self.user.username @property def display_name(self) -> str: return self.nick or self.username @classmethod def _from_json_data(cls, client: "BotClient", json_data: Mapping[str, Any]): return _init_model_from_mapping_json_data(cls, client, json_data, rename=dict( avatar="guild_avatar_hash", roles="role_ids", deaf="is_deaf", muted="is_muted", pending="is_pending" ), type_check_types=True)
46.111111
120
0.701606
import typing import datetime from typing import Mapping, Any, Optional, Iterable, List from .model_abc import JsonAPIModel from .snowflake import Snowflake from .user import User from .enums import PermissionFlags from .permissions import Role from serpcord.utils.model import _init_model_from_mapping_json_data if typing.TYPE_CHECKING: from serpcord.botclient import BotClient class GuildMember(JsonAPIModel[Mapping[str, Any]]): def __init__(self, client: "BotClient", user: User, *, nick: Optional[str] = None, guild_avatar_hash: Optional[str] = None, role_ids: Iterable[Snowflake], roles: Iterable[Role], joined_at: datetime.datetime, premium_since: Optional[datetime.datetime] = None, is_deaf: bool, is_muted: bool, is_pending: bool = False, permissions: Optional[PermissionFlags] = None, communication_disabled_until: Optional[datetime.datetime] = None): self.client: "BotClient" = client self.user: User = user self.nick: Optional[str] = str(nick) if nick is not None else None self.guild_avatar_hash: Optional[str] = str(guild_avatar_hash) if guild_avatar_hash is not None else None self.role_ids: List[Snowflake] = list(role_ids) self.joined_at: datetime.datetime = joined_at self.premium_since: Optional[datetime.datetime] = premium_since self.is_deaf = bool(is_deaf) self.is_muted = bool(is_muted) self.is_pending = bool(is_pending) self.permissions = PermissionFlags(permissions) if permissions is not None else None self.communication_disabled_until: Optional[datetime.datetime] = communication_disabled_until @property def id(self) -> Snowflake: return self.user.id @property def username(self) -> str: return self.user.username @property def display_name(self) -> str: return self.nick or self.username @classmethod def _from_json_data(cls, client: "BotClient", json_data: Mapping[str, Any]): return _init_model_from_mapping_json_data(cls, client, json_data, rename=dict( avatar="guild_avatar_hash", roles="role_ids", deaf="is_deaf", muted="is_muted", pending="is_pending" ), type_check_types=True)
true
true
f72cb27896211cd7a2fb7552b1e8abcbeb59a726
713
py
Python
dns/migrations/0016_autozones_path.py
prorevizor/noc
37e44b8afc64318b10699c06a1138eee9e7d6a4e
[ "BSD-3-Clause" ]
84
2017-10-22T11:01:39.000Z
2022-02-27T03:43:48.000Z
dns/migrations/0016_autozones_path.py
prorevizor/noc
37e44b8afc64318b10699c06a1138eee9e7d6a4e
[ "BSD-3-Clause" ]
22
2017-12-11T07:21:56.000Z
2021-09-23T02:53:50.000Z
dns/migrations/0016_autozones_path.py
prorevizor/noc
37e44b8afc64318b10699c06a1138eee9e7d6a4e
[ "BSD-3-Clause" ]
23
2017-12-06T06:59:52.000Z
2022-02-24T00:02:25.000Z
# ---------------------------------------------------------------------- # autozones_path # ---------------------------------------------------------------------- # Copyright (C) 2007-2019 The NOC Project # See LICENSE for details # ---------------------------------------------------------------------- # Third-party modules from django.db import models # NOC modules from noc.core.migration.base import BaseMigration class Migration(BaseMigration): def migrate(self): self.db.add_column( "dns_dnsserver", "autozones_path", models.CharField( "Autozones path", max_length=256, blank=True, null=True, default="autozones" ), )
29.708333
92
0.4446
from django.db import models from noc.core.migration.base import BaseMigration class Migration(BaseMigration): def migrate(self): self.db.add_column( "dns_dnsserver", "autozones_path", models.CharField( "Autozones path", max_length=256, blank=True, null=True, default="autozones" ), )
true
true
f72cb379e5c099506c5177d3a7d4578f63d14794
8,765
py
Python
models/resnet_cifar_quant.py
mengjian0502/GroupLasso_Quant
1c54c940739babf86e362ffc57752c2aa4c8986d
[ "MIT" ]
null
null
null
models/resnet_cifar_quant.py
mengjian0502/GroupLasso_Quant
1c54c940739babf86e362ffc57752c2aa4c8986d
[ "MIT" ]
null
null
null
models/resnet_cifar_quant.py
mengjian0502/GroupLasso_Quant
1c54c940739babf86e362ffc57752c2aa4c8986d
[ "MIT" ]
null
null
null
""" ResNet on CIFAR10 """ import torch import torch.nn as nn import torch.nn.functional as F from torch.nn import init from .quant import ClippedReLU, int_conv2d, int_linear from .mpdr_score import get_mpdr_score import math class DownsampleA(nn.Module): def __init__(self, nIn, nOut, stride): super(DownsampleA, self).__init__() assert stride == 2 self.avg = nn.AvgPool2d(kernel_size=1, stride=stride) def forward(self, x): x = self.avg(x) return torch.cat((x, x.mul(0)), 1) class ResNetBasicblock(nn.Module): expansion = 1 """ RexNet basicblock (https://github.com/facebook/fb.resnet.torch/blob/master/models/resnet.lua) """ def __init__(self, inplanes, planes, stride=1, downsample=None, wbit=4, abit=4, alpha_init=10, mode='mean', k=2, ch_group=16, push=False): super(ResNetBasicblock, self).__init__() # self.conv_a = nn.Conv2d(inplanes, planes, kernel_size=3, stride=stride, padding=1, bias=False) # quantization self.conv_a = int_conv2d(inplanes, planes, kernel_size=3, stride=stride, padding=1, bias=False, nbit=wbit, mode=mode, k=k, ch_group=ch_group, push=push) # quantization self.bn_a = nn.BatchNorm2d(planes) self.relu1 = ClippedReLU(num_bits=abit, alpha=alpha_init, inplace=True) # Clipped ReLU function 4 - bits # self.relu1 = nn.ReLU(inplace=True) self.conv_b = int_conv2d(planes, planes, kernel_size=3, stride=1, padding=1, bias=False, nbit=wbit, mode=mode, k=k, ch_group=ch_group, push=push) # quantization # self.conv_b = nn.Conv2d(planes, planes, kernel_size=3, stride=1, padding=1, bias=False) # quantization self.bn_b = nn.BatchNorm2d(planes) self.relu2 = ClippedReLU(num_bits=abit, alpha=alpha_init, inplace=True) # Clipped ReLU function 4 - bits self.downsample = downsample def forward(self, x): residual = x basicblock = self.conv_a(x) basicblock = self.bn_a(basicblock) basicblock = self.relu1(basicblock) basicblock = self.conv_b(basicblock) basicblock = self.bn_b(basicblock) if self.downsample is not None: residual = self.downsample(x) return self.relu2(residual + basicblock) class CifarResNet(nn.Module): """ ResNet optimized for the Cifar dataset, as specified in https://arxiv.org/abs/1512.03385.pdf """ def __init__(self, depth, num_classes, wbit=4, abit=4, alpha_init=10, mode='mean', k=2, ch_group=16, push=False): """ Constructor Args: depth: number of layers. num_classes: number of classes base_width: base width """ super(CifarResNet, self).__init__() block = ResNetBasicblock #Model type specifies number of layers for CIFAR-10 and CIFAR-100 model assert (depth - 2) % 6 == 0, 'depth should be one of 20, 32, 44, 56, 110' layer_blocks = (depth - 2) // 6 print ('CifarResNet : Depth : {} , Layers for each block : {}'.format(depth, layer_blocks)) self.num_classes = num_classes self.ch_group = ch_group # self.conv_1_3x3 = nn.Conv2d(3, 16, kernel_size=3, stride=1, padding=1, bias=False) self.conv_1_3x3 = int_conv2d(3, 16, kernel_size=3, stride=1, padding=1, bias=False, nbit=wbit, mode=mode, k=k, ch_group=ch_group, push=False) # skip the push process for the first conv layer self.relu0 = ClippedReLU(num_bits=abit, alpha=alpha_init, inplace=True) self.bn_1 = nn.BatchNorm2d(16) self.inplanes = 16 self.stage_1 = self._make_layer(block, 16, layer_blocks, 1, wbit=wbit, abit=abit, alpha_init=alpha_init, mode=mode, k=k, ch_group=ch_group, push=push) self.stage_2 = self._make_layer(block, 32, layer_blocks, 2, wbit=wbit, abit=abit, alpha_init=alpha_init, mode=mode, k=k, ch_group=ch_group, push=push) self.stage_3 = self._make_layer(block, 64, layer_blocks, 2, wbit=wbit, abit=abit, alpha_init=alpha_init, mode=mode, k=k, ch_group=ch_group, push=push) self.avgpool = nn.AvgPool2d(8) self.classifier = int_linear(64*block.expansion, num_classes, nbit=wbit, mode=mode, k=k, ch_group=ch_group, push=False) # skip the push process for the last fc layer for m in self.modules(): if isinstance(m, nn.Conv2d): n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels m.weight.data.normal_(0, math.sqrt(2. / n)) #m.bias.data.zero_() elif isinstance(m, nn.BatchNorm2d): m.weight.data.fill_(1) m.bias.data.zero_() elif isinstance(m, nn.Linear): init.kaiming_normal_(m.weight) m.bias.data.zero_() def _make_layer(self, block, planes, blocks, stride=1, wbit=4, abit=4, alpha_init=10, mode='mean', k=2, ch_group=16, push=False): downsample = None if stride != 1 or self.inplanes != planes * block.expansion: downsample = nn.Sequential( int_conv2d(self.inplanes, planes * block.expansion, kernel_size=1, stride=stride, bias=False, nbit=wbit, mode=mode, k=k, ch_group=ch_group, push=False), nn.BatchNorm2d(planes * block.expansion), ) layers = [] layers.append(block(self.inplanes, planes, stride, downsample, wbit=wbit, abit=abit, alpha_init=alpha_init, mode=mode, k=k, ch_group=ch_group, push=push)) self.inplanes = planes * block.expansion for i in range(1, blocks): layers.append(block(self.inplanes, planes, wbit=wbit, abit=abit, alpha_init=alpha_init, mode=mode, k=k, ch_group=ch_group, push=push)) return nn.Sequential(*layers) def forward(self, x): x = self.conv_1_3x3(x) x = self.relu0(self.bn_1(x)) x = self.stage_1(x) x = self.stage_2(x) x = self.stage_3(x) x = self.avgpool(x) x = x.view(x.size(0), -1) return self.classifier(x) def get_group_val(self): val = torch.Tensor() if torch.cuda.is_available(): val = val.cuda() count = 0 for m in self.modules(): if isinstance(m, int_conv2d): kw = m.weight.size(2) if kw != 1: if not count in [0]: w_l = m.weight num_group = w_l.size(0) * w_l.size(1) // self.ch_group w_l = w_l.view(w_l.size(0), w_l.size(1) // self.ch_group, self.ch_group, kw, kw) w_l = w_l.contiguous().view((num_group, self.ch_group*kw*kw)) g = w_l.pow(2).sum(dim=1).pow(1/2) val = torch.cat((val.view(-1), g.view(-1))) count += 1 return val def get_global_thre(self, ratio): grp_val = self.get_group_val() # grp_mean = grp_val.mean() # threshold = ratio * grp_mean sorted_block_values, indices = torch.sort(grp_val.contiguous().view(-1)) thre_index = int(grp_val.data.numel() * ratio) threshold = sorted_block_values[thre_index] return threshold def get_group_mp(self): val = torch.Tensor() if torch.cuda.is_available(): val = val.cuda() count = 0 for m in self.modules(): if isinstance(m, int_conv2d): kw = m.weight.size(2) if kw != 1: if not count in [0]: w_l = m.weight num_group = w_l.size(0) * w_l.size(1) // self.ch_group w_l = w_l.view(w_l.size(0), w_l.size(1) // self.ch_group, self.ch_group, kw, kw) w_l = w_l.contiguous().view((num_group, self.ch_group*kw*kw)) g = w_l.abs().mean(dim=1) val = torch.cat((val.view(-1), g.view(-1))) count += 1 return val def get_global_mp_thre(self, ratio): grp_val = self.get_group_mp() sorted_block_values, indices = torch.sort(grp_val.contiguous().view(-1)) thre_index = int(grp_val.data.numel() * ratio) threshold = sorted_block_values[thre_index] return threshold def get_group_mpdr(self): val = torch.Tensor() if torch.cuda.is_available(): val = val.cuda() count = 0 for m in self.modules(): if isinstance(m, int_conv2d): kw = m.weight.size(2) if kw != 1: if not count in [0]: w_l = get_mpdr_score(m.weight) num_group = w_l.size(0) * w_l.size(1) // self.ch_group w_l = w_l.view(w_l.size(0), w_l.size(1) // self.ch_group, self.ch_group, kw, kw) w_l = w_l.contiguous().view((num_group, self.ch_group*kw*kw)) g = w_l.mean(dim=1) # compute the mean of the mpdr score val = torch.cat((val.view(-1), g.view(-1))) count += 1 return val def get_global_mpdr_thre(self, ratio): grp_val = self.get_group_mpdr() sorted_block_values, indices = torch.sort(grp_val.contiguous().view(-1)) thre_index = int(grp_val.data.numel() * ratio) threshold = sorted_block_values[thre_index] return threshold class resnet20_quant: base=CifarResNet args = list() kwargs = {'depth': 20} class resnet32_quant: base=CifarResNet args = list() kwargs = {'depth': 32}
37.780172
196
0.650542
import torch import torch.nn as nn import torch.nn.functional as F from torch.nn import init from .quant import ClippedReLU, int_conv2d, int_linear from .mpdr_score import get_mpdr_score import math class DownsampleA(nn.Module): def __init__(self, nIn, nOut, stride): super(DownsampleA, self).__init__() assert stride == 2 self.avg = nn.AvgPool2d(kernel_size=1, stride=stride) def forward(self, x): x = self.avg(x) return torch.cat((x, x.mul(0)), 1) class ResNetBasicblock(nn.Module): expansion = 1 def __init__(self, inplanes, planes, stride=1, downsample=None, wbit=4, abit=4, alpha_init=10, mode='mean', k=2, ch_group=16, push=False): super(ResNetBasicblock, self).__init__() _a = int_conv2d(inplanes, planes, kernel_size=3, stride=stride, padding=1, bias=False, nbit=wbit, mode=mode, k=k, ch_group=ch_group, push=push) self.bn_a = nn.BatchNorm2d(planes) self.relu1 = ClippedReLU(num_bits=abit, alpha=alpha_init, inplace=True) self.conv_b = int_conv2d(planes, planes, kernel_size=3, stride=1, padding=1, bias=False, nbit=wbit, mode=mode, k=k, ch_group=ch_group, push=push) = nn.BatchNorm2d(planes) self.relu2 = ClippedReLU(num_bits=abit, alpha=alpha_init, inplace=True) self.downsample = downsample def forward(self, x): residual = x basicblock = self.conv_a(x) basicblock = self.bn_a(basicblock) basicblock = self.relu1(basicblock) basicblock = self.conv_b(basicblock) basicblock = self.bn_b(basicblock) if self.downsample is not None: residual = self.downsample(x) return self.relu2(residual + basicblock) class CifarResNet(nn.Module): def __init__(self, depth, num_classes, wbit=4, abit=4, alpha_init=10, mode='mean', k=2, ch_group=16, push=False): super(CifarResNet, self).__init__() block = ResNetBasicblock assert (depth - 2) % 6 == 0, 'depth should be one of 20, 32, 44, 56, 110' layer_blocks = (depth - 2) // 6 print ('CifarResNet : Depth : {} , Layers for each block : {}'.format(depth, layer_blocks)) self.num_classes = num_classes self.ch_group = ch_group self.conv_1_3x3 = int_conv2d(3, 16, kernel_size=3, stride=1, padding=1, bias=False, nbit=wbit, mode=mode, k=k, ch_group=ch_group, push=False) self.relu0 = ClippedReLU(num_bits=abit, alpha=alpha_init, inplace=True) self.bn_1 = nn.BatchNorm2d(16) self.inplanes = 16 self.stage_1 = self._make_layer(block, 16, layer_blocks, 1, wbit=wbit, abit=abit, alpha_init=alpha_init, mode=mode, k=k, ch_group=ch_group, push=push) self.stage_2 = self._make_layer(block, 32, layer_blocks, 2, wbit=wbit, abit=abit, alpha_init=alpha_init, mode=mode, k=k, ch_group=ch_group, push=push) self.stage_3 = self._make_layer(block, 64, layer_blocks, 2, wbit=wbit, abit=abit, alpha_init=alpha_init, mode=mode, k=k, ch_group=ch_group, push=push) self.avgpool = nn.AvgPool2d(8) self.classifier = int_linear(64*block.expansion, num_classes, nbit=wbit, mode=mode, k=k, ch_group=ch_group, push=False) for m in self.modules(): if isinstance(m, nn.Conv2d): n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels m.weight.data.normal_(0, math.sqrt(2. / n)) elif isinstance(m, nn.BatchNorm2d): m.weight.data.fill_(1) m.bias.data.zero_() elif isinstance(m, nn.Linear): init.kaiming_normal_(m.weight) m.bias.data.zero_() def _make_layer(self, block, planes, blocks, stride=1, wbit=4, abit=4, alpha_init=10, mode='mean', k=2, ch_group=16, push=False): downsample = None if stride != 1 or self.inplanes != planes * block.expansion: downsample = nn.Sequential( int_conv2d(self.inplanes, planes * block.expansion, kernel_size=1, stride=stride, bias=False, nbit=wbit, mode=mode, k=k, ch_group=ch_group, push=False), nn.BatchNorm2d(planes * block.expansion), ) layers = [] layers.append(block(self.inplanes, planes, stride, downsample, wbit=wbit, abit=abit, alpha_init=alpha_init, mode=mode, k=k, ch_group=ch_group, push=push)) self.inplanes = planes * block.expansion for i in range(1, blocks): layers.append(block(self.inplanes, planes, wbit=wbit, abit=abit, alpha_init=alpha_init, mode=mode, k=k, ch_group=ch_group, push=push)) return nn.Sequential(*layers) def forward(self, x): x = self.conv_1_3x3(x) x = self.relu0(self.bn_1(x)) x = self.stage_1(x) x = self.stage_2(x) x = self.stage_3(x) x = self.avgpool(x) x = x.view(x.size(0), -1) return self.classifier(x) def get_group_val(self): val = torch.Tensor() if torch.cuda.is_available(): val = val.cuda() count = 0 for m in self.modules(): if isinstance(m, int_conv2d): kw = m.weight.size(2) if kw != 1: if not count in [0]: w_l = m.weight num_group = w_l.size(0) * w_l.size(1) // self.ch_group w_l = w_l.view(w_l.size(0), w_l.size(1) // self.ch_group, self.ch_group, kw, kw) w_l = w_l.contiguous().view((num_group, self.ch_group*kw*kw)) g = w_l.pow(2).sum(dim=1).pow(1/2) val = torch.cat((val.view(-1), g.view(-1))) count += 1 return val def get_global_thre(self, ratio): grp_val = self.get_group_val() sorted_block_values, indices = torch.sort(grp_val.contiguous().view(-1)) thre_index = int(grp_val.data.numel() * ratio) threshold = sorted_block_values[thre_index] return threshold def get_group_mp(self): val = torch.Tensor() if torch.cuda.is_available(): val = val.cuda() count = 0 for m in self.modules(): if isinstance(m, int_conv2d): kw = m.weight.size(2) if kw != 1: if not count in [0]: w_l = m.weight num_group = w_l.size(0) * w_l.size(1) // self.ch_group w_l = w_l.view(w_l.size(0), w_l.size(1) // self.ch_group, self.ch_group, kw, kw) w_l = w_l.contiguous().view((num_group, self.ch_group*kw*kw)) g = w_l.abs().mean(dim=1) val = torch.cat((val.view(-1), g.view(-1))) count += 1 return val def get_global_mp_thre(self, ratio): grp_val = self.get_group_mp() sorted_block_values, indices = torch.sort(grp_val.contiguous().view(-1)) thre_index = int(grp_val.data.numel() * ratio) threshold = sorted_block_values[thre_index] return threshold def get_group_mpdr(self): val = torch.Tensor() if torch.cuda.is_available(): val = val.cuda() count = 0 for m in self.modules(): if isinstance(m, int_conv2d): kw = m.weight.size(2) if kw != 1: if not count in [0]: w_l = get_mpdr_score(m.weight) num_group = w_l.size(0) * w_l.size(1) // self.ch_group w_l = w_l.view(w_l.size(0), w_l.size(1) // self.ch_group, self.ch_group, kw, kw) w_l = w_l.contiguous().view((num_group, self.ch_group*kw*kw)) g = w_l.mean(dim=1) val = torch.cat((val.view(-1), g.view(-1))) count += 1 return val def get_global_mpdr_thre(self, ratio): grp_val = self.get_group_mpdr() sorted_block_values, indices = torch.sort(grp_val.contiguous().view(-1)) thre_index = int(grp_val.data.numel() * ratio) threshold = sorted_block_values[thre_index] return threshold class resnet20_quant: base=CifarResNet args = list() kwargs = {'depth': 20} class resnet32_quant: base=CifarResNet args = list() kwargs = {'depth': 32}
true
true
f72cb40930dc9e29198e8bc1f4a2818b2e161a8f
449
py
Python
util.py
codefordc/us-congress-pizza-flag-tracker
766c72e01e2c01342d4c6dbe2108fded2022ee74
[ "CC0-1.0" ]
5
2021-01-31T14:29:43.000Z
2021-07-15T16:22:30.000Z
util.py
rajindermavi/us-congress-pizza-flag-tracker
10827f3d6f2ef0cc434a475fc9782fc840cb81ab
[ "CC0-1.0" ]
85
2021-05-12T23:31:29.000Z
2022-03-30T21:23:58.000Z
util.py
rajindermavi/us-congress-pizza-flag-tracker
10827f3d6f2ef0cc434a475fc9782fc840cb81ab
[ "CC0-1.0" ]
8
2021-04-11T16:44:15.000Z
2021-10-30T21:14:17.000Z
import json from config import db from models import UserModel def table_record_to_json(record): modelClass = type(record) columns = [record for record in filter(lambda item: not item.startswith('_'),modelClass.__dict__)] json_value = {column_name: str(getattr(record, column_name))for column_name in columns} return json_value def table_to_json(table): return { "data": [table_record_to_json(record) for record in table] }
28.0625
102
0.752784
import json from config import db from models import UserModel def table_record_to_json(record): modelClass = type(record) columns = [record for record in filter(lambda item: not item.startswith('_'),modelClass.__dict__)] json_value = {column_name: str(getattr(record, column_name))for column_name in columns} return json_value def table_to_json(table): return { "data": [table_record_to_json(record) for record in table] }
true
true
f72cb478099ad21f4b980eaa5ef8fdbe1740ca81
519
py
Python
models/utils.py
clabrugere/numpy-basics
81efb4b8ac58fc17dc8f6c676004bbc3a99a92c3
[ "MIT" ]
1
2020-10-27T18:05:26.000Z
2020-10-27T18:05:26.000Z
models/utils.py
clabrugere/numpy-basics
81efb4b8ac58fc17dc8f6c676004bbc3a99a92c3
[ "MIT" ]
null
null
null
models/utils.py
clabrugere/numpy-basics
81efb4b8ac58fc17dc8f6c676004bbc3a99a92c3
[ "MIT" ]
null
null
null
import numpy as np def confusion_matrix(y_true, y_hat, threshold=.5): def _to_class(y): return np.array([1 if i >= threshold else 0 for i in y]) n_classes = len(np.unique(y_true)) cm = np.zeros((n_classes, n_classes)) y_hat = _to_class(y_hat) for a, p in zip(y_true, y_hat): cm[a, p] += 1 return cm def f1_score(cm): precision = cm[0, 0] / cm[0, :].sum() recall = cm[0, 0] / cm[:, 0].sum() return 2 * (precision * recall) / (precision + recall)
24.714286
64
0.572254
import numpy as np def confusion_matrix(y_true, y_hat, threshold=.5): def _to_class(y): return np.array([1 if i >= threshold else 0 for i in y]) n_classes = len(np.unique(y_true)) cm = np.zeros((n_classes, n_classes)) y_hat = _to_class(y_hat) for a, p in zip(y_true, y_hat): cm[a, p] += 1 return cm def f1_score(cm): precision = cm[0, 0] / cm[0, :].sum() recall = cm[0, 0] / cm[:, 0].sum() return 2 * (precision * recall) / (precision + recall)
true
true
f72cb4e3d578253909cb6f62152c5f20859236b5
276
py
Python
translator/app/modules/speech.py
sharad461/nepali-translator
d35ba1586e4ad14ddae71b24caf49aac66d63a2e
[ "Apache-2.0" ]
29
2019-08-04T03:05:23.000Z
2021-12-14T14:09:57.000Z
translator/app/modules/speech.py
sharad461/nepali-translator
d35ba1586e4ad14ddae71b24caf49aac66d63a2e
[ "Apache-2.0" ]
3
2020-10-09T01:35:45.000Z
2021-06-02T12:24:31.000Z
translator/app/modules/speech.py
sharad461/nepali-translator
d35ba1586e4ad14ddae71b24caf49aac66d63a2e
[ "Apache-2.0" ]
9
2019-11-04T10:01:34.000Z
2021-12-20T02:03:40.000Z
import speech_recognition as sr def rec(): r = sr.Recognizer() with sr.Microphone() as source: audio = r.listen(source) try: text = r.recognize_google(audio) return(text) except: return("Sorry, couldn't recognize your voice. Please try again.")
21.230769
68
0.666667
import speech_recognition as sr def rec(): r = sr.Recognizer() with sr.Microphone() as source: audio = r.listen(source) try: text = r.recognize_google(audio) return(text) except: return("Sorry, couldn't recognize your voice. Please try again.")
true
true
f72cb63e07c6ebb1781cffd6e5ba78d6f5d59509
1,201
py
Python
sonata/datamodules/base_datamodule.py
sergevkim/sonata
2250b60174628ee76fb7d54bf50e4b8b07b505d5
[ "MIT" ]
1
2021-03-15T19:01:43.000Z
2021-03-15T19:01:43.000Z
sonata/datamodules/base_datamodule.py
sergevkim/sonata
2250b60174628ee76fb7d54bf50e4b8b07b505d5
[ "MIT" ]
null
null
null
sonata/datamodules/base_datamodule.py
sergevkim/sonata
2250b60174628ee76fb7d54bf50e4b8b07b505d5
[ "MIT" ]
null
null
null
from abc import ABC, abstractmethod from pathlib import Path import torch from torch import Tensor from torch.utils.data import Dataset, DataLoader class BaseDataModule(ABC): def __init__( self, data_path: Path, batch_size: int, num_workers: int, ): super().__init__() self.data_path = data_path self.batch_size = batch_size self.num_workers = num_workers @staticmethod def prepare_data( data_path: Path, ): pass @abstractmethod def setup( self, val_ratio: float, ) -> None: pass def train_dataloader(self) -> DataLoader: train_dataloader = DataLoader( dataset=self.train_dataset, batch_size=self.batch_size, num_workers=self.num_workers, ) return train_dataloader def val_dataloader(self) -> DataLoader: val_dataloader = DataLoader( dataset=self.val_dataset, batch_size=self.batch_size, num_workers=self.num_workers, ) return val_dataloader def test_dataloader(self): pass
21.836364
48
0.587843
from abc import ABC, abstractmethod from pathlib import Path import torch from torch import Tensor from torch.utils.data import Dataset, DataLoader class BaseDataModule(ABC): def __init__( self, data_path: Path, batch_size: int, num_workers: int, ): super().__init__() self.data_path = data_path self.batch_size = batch_size self.num_workers = num_workers @staticmethod def prepare_data( data_path: Path, ): pass @abstractmethod def setup( self, val_ratio: float, ) -> None: pass def train_dataloader(self) -> DataLoader: train_dataloader = DataLoader( dataset=self.train_dataset, batch_size=self.batch_size, num_workers=self.num_workers, ) return train_dataloader def val_dataloader(self) -> DataLoader: val_dataloader = DataLoader( dataset=self.val_dataset, batch_size=self.batch_size, num_workers=self.num_workers, ) return val_dataloader def test_dataloader(self): pass
true
true
f72cb68570a41741af7a25b02a5d19503e0f3386
3,806
py
Python
netket/operator/boson.py
gpescia/MyNetKet
958510966a5870d9d491de0628903cf1fc210921
[ "Apache-2.0" ]
null
null
null
netket/operator/boson.py
gpescia/MyNetKet
958510966a5870d9d491de0628903cf1fc210921
[ "Apache-2.0" ]
11
2021-07-12T15:20:14.000Z
2022-01-17T09:40:41.000Z
netket/operator/boson.py
gpescia/MyNetKet
958510966a5870d9d491de0628903cf1fc210921
[ "Apache-2.0" ]
1
2021-04-25T15:47:32.000Z
2021-04-25T15:47:32.000Z
# Copyright 2021 The NetKet Authors - 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 netket.utils.types import DType from netket.hilbert import AbstractHilbert from ._local_operator import LocalOperator as _LocalOperator def destroy( hilbert: AbstractHilbert, site: int, dtype: DType = float ) -> _LocalOperator: """ Builds the boson destruction operator :math:`\\hat{a}` acting on the `site`-th of the Hilbert space `hilbert`. If `hilbert` is a non-Bosonic space of local dimension M, it is considered as a bosonic space of local dimension M. Args: hilbert: The hilbert space site: the site on which this operator acts Returns: The resulting Local Operator """ import numpy as np N = hilbert.size_at_index(site) D = np.array([np.sqrt(m) for m in np.arange(1, N)]) mat = np.diag(D, 1) return _LocalOperator(hilbert, mat, [site], dtype=dtype) def create(hilbert: AbstractHilbert, site: int, dtype: DType = float) -> _LocalOperator: """ Builds the boson creation operator :math:`\\hat{a}^\\dagger` acting on the `site`-th of the Hilbert space `hilbert`. If `hilbert` is a non-Bosonic space of local dimension M, it is considered as a bosonic space of local dimension M. Args: hilbert: The hilbert space site: the site on which this operator acts Returns: The resulting Local Operator """ import numpy as np N = hilbert.size_at_index(site) D = np.array([np.sqrt(m) for m in np.arange(1, N)]) mat = np.diag(D, -1) return _LocalOperator(hilbert, mat, [site], dtype=dtype) def number(hilbert: AbstractHilbert, site: int, dtype: DType = float) -> _LocalOperator: """ Builds the number operator :math:`\\hat{a}^\\dagger\\hat{a}` acting on the `site`-th of the Hilbert space `hilbert`. If `hilbert` is a non-Bosonic space of local dimension M, it is considered as a bosonic space of local dimension M. Args: hilbert: The hilbert space site: the site on which this operator acts Returns: The resulting Local Operator """ import numpy as np N = hilbert.size_at_index(site) D = np.array([m for m in np.arange(0, N)]) mat = np.diag(D, 0) return _LocalOperator(hilbert, mat, [site], dtype=dtype) def proj( hilbert: AbstractHilbert, site: int, n: int, dtype: DType = float ) -> _LocalOperator: """ Builds the projector operator :math:`|n\\rangle\\langle n |` acting on the `site`-th of the Hilbert space `hilbert` and collapsing on the state with `n` bosons. If `hilbert` is a non-Bosonic space of local dimension M, it is considered as a bosonic space of local dimension M. Args: hilbert: The hilbert space site: the site on which this operator acts n: the state on which to project Returns: the resulting operator """ import numpy as np N = hilbert.size_at_index(site) if n >= N: raise ValueError("Cannot project on a state above the cutoff.") D = np.array([0 for m in np.arange(0, N)]) D[n] = 1 mat = np.diag(D, 0) return _LocalOperator(hilbert, mat, [site], dtype=dtype) # clean up the module del AbstractHilbert, DType
29.503876
96
0.672622
from netket.utils.types import DType from netket.hilbert import AbstractHilbert from ._local_operator import LocalOperator as _LocalOperator def destroy( hilbert: AbstractHilbert, site: int, dtype: DType = float ) -> _LocalOperator: import numpy as np N = hilbert.size_at_index(site) D = np.array([np.sqrt(m) for m in np.arange(1, N)]) mat = np.diag(D, 1) return _LocalOperator(hilbert, mat, [site], dtype=dtype) def create(hilbert: AbstractHilbert, site: int, dtype: DType = float) -> _LocalOperator: import numpy as np N = hilbert.size_at_index(site) D = np.array([np.sqrt(m) for m in np.arange(1, N)]) mat = np.diag(D, -1) return _LocalOperator(hilbert, mat, [site], dtype=dtype) def number(hilbert: AbstractHilbert, site: int, dtype: DType = float) -> _LocalOperator: import numpy as np N = hilbert.size_at_index(site) D = np.array([m for m in np.arange(0, N)]) mat = np.diag(D, 0) return _LocalOperator(hilbert, mat, [site], dtype=dtype) def proj( hilbert: AbstractHilbert, site: int, n: int, dtype: DType = float ) -> _LocalOperator: import numpy as np N = hilbert.size_at_index(site) if n >= N: raise ValueError("Cannot project on a state above the cutoff.") D = np.array([0 for m in np.arange(0, N)]) D[n] = 1 mat = np.diag(D, 0) return _LocalOperator(hilbert, mat, [site], dtype=dtype) del AbstractHilbert, DType
true
true
f72cb81ea991aa6ce3d971ea1b6e47347518c4cb
31
py
Python
day2/oddno1.py
nikhilsamninan/python-files
15198459081097058a939b40b5e8ef754e578fe0
[ "Apache-2.0" ]
null
null
null
day2/oddno1.py
nikhilsamninan/python-files
15198459081097058a939b40b5e8ef754e578fe0
[ "Apache-2.0" ]
null
null
null
day2/oddno1.py
nikhilsamninan/python-files
15198459081097058a939b40b5e8ef754e578fe0
[ "Apache-2.0" ]
null
null
null
print(tuple(range(201,400,2)))
15.5
30
0.709677
print(tuple(range(201,400,2)))
true
true
f72cb9eb47ac3d1bf036724169c33be5cd5d5d60
338
py
Python
dogstatsd/__init__.py
ian28223/datadog-unix-agent
09c75778b512361c83ff10e7cdb37b887bcaa8fe
[ "Apache-2.0" ]
13
2018-08-11T01:40:51.000Z
2022-01-02T09:07:43.000Z
dogstatsd/__init__.py
ian28223/datadog-unix-agent
09c75778b512361c83ff10e7cdb37b887bcaa8fe
[ "Apache-2.0" ]
21
2018-05-28T13:16:23.000Z
2021-08-19T15:43:40.000Z
dogstatsd/__init__.py
ian28223/datadog-unix-agent
09c75778b512361c83ff10e7cdb37b887bcaa8fe
[ "Apache-2.0" ]
15
2018-05-10T15:09:41.000Z
2022-03-21T06:46:21.000Z
# Unless explicitly stated otherwise all files in this repository are licensed # under the Apache License Version 2.0. # This product includes software developed at Datadog (https://www.datadoghq.com/). # Copyright 2018 Datadog, Inc. from .server import Server from .reporter import Reporter __all__ = [ "Server", "Reporter", ]
26
83
0.748521
from .server import Server from .reporter import Reporter __all__ = [ "Server", "Reporter", ]
true
true
f72cba691951b7828f5ece31e4d5727f90f7fb13
428
py
Python
gallery/migrations/0006_image_image.py
dennis027/Gallery
282c1807087beb2e2a5ea1d51b5b6891145c20a0
[ "MIT" ]
null
null
null
gallery/migrations/0006_image_image.py
dennis027/Gallery
282c1807087beb2e2a5ea1d51b5b6891145c20a0
[ "MIT" ]
null
null
null
gallery/migrations/0006_image_image.py
dennis027/Gallery
282c1807087beb2e2a5ea1d51b5b6891145c20a0
[ "MIT" ]
null
null
null
# Generated by Django 2.2 on 2021-07-03 12:00 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('gallery', '0005_remove_image_image'), ] operations = [ migrations.AddField( model_name='image', name='image', field=models.CharField(default=1, max_length=255), preserve_default=False, ), ]
21.4
62
0.598131
from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('gallery', '0005_remove_image_image'), ] operations = [ migrations.AddField( model_name='image', name='image', field=models.CharField(default=1, max_length=255), preserve_default=False, ), ]
true
true
f72cbb0f0e9ed11c2ce819bd187907cbc6229269
1,190
py
Python
examples/pure_jax.py
kingoflolz/DALL-E
d3f3e9a57a31b1e1cc74a449a9e6e5a0442f0ac7
[ "MIT" ]
7
2021-04-10T15:03:37.000Z
2021-07-05T02:49:51.000Z
examples/pure_jax.py
kingoflolz/DALL-E
d3f3e9a57a31b1e1cc74a449a9e6e5a0442f0ac7
[ "MIT" ]
null
null
null
examples/pure_jax.py
kingoflolz/DALL-E
d3f3e9a57a31b1e1cc74a449a9e6e5a0442f0ac7
[ "MIT" ]
1
2021-10-01T07:47:41.000Z
2021-10-01T07:47:41.000Z
import io import jax import requests import PIL from PIL import ImageOps import numpy as np import jax.numpy as jnp from dall_e_jax import get_encoder, get_decoder, map_pixels, unmap_pixels target_image_size = 256 def download_image(url): resp = requests.get(url) resp.raise_for_status() return PIL.Image.open(io.BytesIO(resp.content)) def preprocess(img): img = ImageOps.fit(img, [target_image_size,] * 2, method=0, bleed=0.0, centering=(0.5, 0.5)) img = np.expand_dims(np.transpose(np.array(img).astype(np.float32)/255, (2, 0, 1)), 0) return map_pixels(img) jax_enc_fn, jax_enc_params = get_encoder("encoder.pkl") jax_dec_fn, jax_dec_params = get_decoder("decoder.pkl") x = preprocess(download_image('https://assets.bwbx.io/images/users/iqjWHBFdfxIU/iKIWgaiJUtss/v2/1000x-1.jpg')) z_logits = jax_enc_fn(jax_enc_params, x) z = jnp.argmax(z_logits, axis=1) z = jnp.transpose(jax.nn.one_hot(z, num_classes=8192), (0, 3, 1, 2)) x_stats = jax_dec_fn(jax_dec_params, z) x_rec = unmap_pixels(jax.nn.sigmoid(x_stats[:, :3])) x_rec = np.transpose((np.array(x_rec[0]) * 255).astype(np.uint8), (1, 2, 0)) PIL.Image.fromarray(x_rec).save('reconstructed.png')
26.444444
110
0.730252
import io import jax import requests import PIL from PIL import ImageOps import numpy as np import jax.numpy as jnp from dall_e_jax import get_encoder, get_decoder, map_pixels, unmap_pixels target_image_size = 256 def download_image(url): resp = requests.get(url) resp.raise_for_status() return PIL.Image.open(io.BytesIO(resp.content)) def preprocess(img): img = ImageOps.fit(img, [target_image_size,] * 2, method=0, bleed=0.0, centering=(0.5, 0.5)) img = np.expand_dims(np.transpose(np.array(img).astype(np.float32)/255, (2, 0, 1)), 0) return map_pixels(img) jax_enc_fn, jax_enc_params = get_encoder("encoder.pkl") jax_dec_fn, jax_dec_params = get_decoder("decoder.pkl") x = preprocess(download_image('https://assets.bwbx.io/images/users/iqjWHBFdfxIU/iKIWgaiJUtss/v2/1000x-1.jpg')) z_logits = jax_enc_fn(jax_enc_params, x) z = jnp.argmax(z_logits, axis=1) z = jnp.transpose(jax.nn.one_hot(z, num_classes=8192), (0, 3, 1, 2)) x_stats = jax_dec_fn(jax_dec_params, z) x_rec = unmap_pixels(jax.nn.sigmoid(x_stats[:, :3])) x_rec = np.transpose((np.array(x_rec[0]) * 255).astype(np.uint8), (1, 2, 0)) PIL.Image.fromarray(x_rec).save('reconstructed.png')
true
true
f72cbbad2bdf77b532dac0c510c9856f9ed9388e
12,421
py
Python
src/run_joint_confidence_cdcOriginalGan.py
williamsashbee/Confident_classifier
cba3ef862b310afc3af6c4a62b524f032f45549e
[ "MIT" ]
null
null
null
src/run_joint_confidence_cdcOriginalGan.py
williamsashbee/Confident_classifier
cba3ef862b310afc3af6c4a62b524f032f45549e
[ "MIT" ]
null
null
null
src/run_joint_confidence_cdcOriginalGan.py
williamsashbee/Confident_classifier
cba3ef862b310afc3af6c4a62b524f032f45549e
[ "MIT" ]
null
null
null
############################################## # This code is based on samples from pytorch # ############################################## # Writer: Kimin Lee from __future__ import print_function import argparse import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import data_loader import numpy as np import torchvision.utils as vutils import models from torchvision import datasets, transforms from torch.autograd import Variable import os os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID" # see issue #152 os.environ["CUDA_VISIBLE_DEVICES"] = "5" # Training settings parser = argparse.ArgumentParser(description='Training code - joint confidence') parser.add_argument('--batch-size', type=int, default=128, help='input batch size for training') parser.add_argument('--epochs', type=int, default=100, help='number of epochs to train') parser.add_argument('--lr', type=float, default=0.0002, help='learning rate') parser.add_argument('--no-cuda', action='store_true', default=False, help='disables CUDA training') parser.add_argument('--seed', type=int, default=1, help='random seed') parser.add_argument('--log-interval', type=int, default=100, help='how many batches to wait before logging training status') parser.add_argument('--dataset', default='mnist', help='cifar10 | svhn') parser.add_argument('--dataroot', required=True, help='path to dataset') parser.add_argument('--imageSize', type=int, default=32, help='the height / width of the input image to network') parser.add_argument('--outf', default='.', help='folder to output images and model checkpoints') parser.add_argument('--wd', type=float, default=0.0, help='weight decay') parser.add_argument('--droprate', type=float, default=0.1, help='learning rate decay') parser.add_argument('--decreasing_lr', default='60', help='decreasing strategy') parser.add_argument('--num_classes', type=int, default=10, help='the # of classes') parser.add_argument('--beta', type=float, default=1, help='penalty parameter for KL term') args = parser.parse_args() if args.dataset == 'cifar10': args.beta = 0.1 args.batch_size = 64 print(args) args.cuda = not args.no_cuda and torch.cuda.is_available() print("Random Seed: ", args.seed) torch.manual_seed(args.seed) if args.cuda: torch.cuda.manual_seed(args.seed) kwargs = {'num_workers': 1, 'pin_memory': True} if args.cuda else {} print('load data: ', args.dataset) if args.dataset=='mnist': transform = transforms.Compose([ transforms.Scale(32), transforms.ToTensor(), transforms.Lambda(lambda x: x.repeat(3, 1, 1)), transforms.Normalize(mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5)) ]) train_loader = torch.utils.data.DataLoader( datasets.MNIST('data', train=True, download=True, transform=transform), batch_size=128, shuffle=True) test_loader = torch.utils.data.DataLoader( datasets.MNIST('data', train=False, download=True, transform=transform), batch_size=128, shuffle=True) else: train_loader, test_loader = data_loader.getTargetDataSet(args.dataset, args.batch_size, args.imageSize, args.dataroot) transform = transforms.Compose([ transforms.Scale(32), transforms.ToTensor(), transforms.Lambda(lambda x: x.repeat(3, 1, 1)), transforms.Normalize(mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5)) ]) train_loader_mnist = torch.utils.data.DataLoader( datasets.MNIST('data', train=True, download=True, transform=transform), batch_size=128, shuffle=True) print('Load model') model = models.vgg13() print(model) print('load GAN') nz = 100 G = models.cdcOriginalGenerator(1, nz, 64, 3) # ngpu, nz, ngf, nc D = models.cdcOriginalDiscriminator(1, 3, 64) # ngpu, nc, ndf G.weight_init(mean=0.0, std=0.02) D.weight_init(mean=0.0, std=0.02) # Initial setup for GAN real_label = 1 fake_label = 0 criterion = nn.BCELoss() nz = 100 print('Setup optimizer') lr = 0.0002 batch_size = 128 optimizer = optim.Adam(model.parameters(), lr=args.lr, weight_decay=args.wd) G_optimizer = optim.Adam(G.parameters(), lr=lr, betas=(0.5, 0.999)) D_optimizer = optim.Adam(D.parameters(), lr=lr, betas=(0.5, 0.999)) decreasing_lr = list(map(int, args.decreasing_lr.split(','))) onehot = torch.zeros(10, 10).cuda() onehot = onehot.scatter_(1, torch.cuda.LongTensor([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]).view(10, 1), 1).view(10, 10, 1, 1) img_size = 32 num_labels = 10 fraction = 1 fill = torch.zeros([num_labels, num_labels, img_size / fraction, img_size / fraction]).cuda() for i in range(num_labels): fill[i, i, :, :] = 1 fill = fill.cuda() # os.environ["CUDA_LAUNCH_BLOCKING"]="1" # Binary Cross Entropy loss BCE_loss = nn.BCELoss() # fixed_noise = torch.FloatTensor(64, nz, 1, 1).normal_(0, 1) fixed_noise = torch.randn((64, 100)).view(-1, 100, 1, 1) fixed_label = None if args.cuda: model.cuda() D.cuda() G.cuda() criterion.cuda() fixed_noise = fixed_noise.cuda() first = True def train(epoch): model.train() # D_train_loss = 0 # G_train_loss = 3 trg = 0 trd = 0 i = 0 for batch_idx, (data, y_labels) in enumerate(train_loader): uniform_dist = torch.Tensor(data.size(0), args.num_classes).fill_((1. / args.num_classes)).cuda() x_ = data.cuda() assert x_[0, :, :, :].shape == (3, 32, 32) global first if first: global fixed_noise global fixed_label first = False fixed_label = onehot[y_labels.squeeze()[:64]] print("saving fixed_label!") vutils.save_image(data[:64], '{}/{}jointConfidencerealReference{}.png'.format(args.outf, args.dataset, epoch), normalize=True) # train discriminator D D.zero_grad() y_ = y_labels mini_batch = x_.size()[0] y_real_ = torch.ones(mini_batch) y_fake_ = torch.zeros(mini_batch) y_real_, y_fake_ = Variable(y_real_.cuda()), Variable(y_fake_.cuda()) y_fill_ = fill[y_.squeeze().tolist()] # y_fill_ = fill[y_] assert y_fill_[0, y_.squeeze().tolist()[0], :, :].sum() == (img_size / fraction) ** 2 assert y_fill_.sum() == (img_size / fraction) ** 2 * mini_batch x_, y_fill_ = Variable(x_.cuda()), Variable(y_fill_.cuda()) D_result = D(x_, y_fill_).squeeze() D_real_loss = BCE_loss(D_result, y_real_) z_ = torch.randn((mini_batch, 100)).view(-1, 100, 1, 1) y_ = (torch.rand(mini_batch, 1) * num_labels).type(torch.LongTensor).squeeze() y_label_ = onehot[y_] y_fill_ = fill[y_] assert y_label_[0, y_[0]] == 1 assert y_label_.shape == (mini_batch, 10, 1, 1) assert y_fill_[0, y_[0], :, :].sum() == (img_size / fraction) ** 2 assert y_fill_.sum() == (img_size / fraction) ** 2 * mini_batch z_, y_label_, y_fill_ = Variable(z_.cuda()), Variable(y_label_.cuda()), Variable(y_fill_.cuda()) G_result = G(z_, y_label_) D_result = D(G_result, y_fill_).squeeze() D_fake_loss = BCE_loss(D_result, y_fake_) D_fake_score = D_result.data.mean() D_train_loss = D_real_loss + D_fake_loss trg += 1 if D_train_loss > .1: trd += 1 D_train_loss.backward() D_optimizer.step() # D_losses.append(D_train_loss.item()) # train generator G G.zero_grad() z_ = torch.randn((mini_batch, 100)).view(-1, 100, 1, 1) y_ = (torch.rand(mini_batch, 1) * num_labels).type(torch.LongTensor).squeeze() y_label_ = onehot[y_] y_fill_ = fill[y_] z_, y_label_, y_fill_ = Variable(z_.cuda()), Variable(y_label_.cuda()), Variable(y_fill_.cuda()) assert y_label_[0, y_[0]] == 1 assert y_label_.shape == (mini_batch, 10, 1, 1) assert y_fill_[0, y_[0], :, :].sum() == (img_size / fraction) ** 2 assert y_fill_.sum() == (img_size / fraction) ** 2 * mini_batch G_result = G(z_, y_label_) D_result = D(G_result, y_fill_).squeeze() G_train_loss = BCE_loss(D_result, y_real_) # minimize the true distribution KL_fake_output = F.log_softmax(model(G_result)) errG_KL = F.kl_div(KL_fake_output, uniform_dist) * args.num_classes generator_loss = G_train_loss + args.beta * errG_KL # 12.0, .65, 0e-8 generator_loss.backward() G_optimizer.step() # G_losses.append(G_train_loss.item()) ########################### # (3) Update classifier # ########################### # cross entropy loss optimizer.zero_grad() x_ = Variable(x_) output = F.log_softmax(model(x_)) loss = F.nll_loss(output.cuda(), y_labels.type(torch.cuda.LongTensor).squeeze()) # KL divergence #### z_ = torch.randn((data.shape[0], 100)).view(-1, 100, 1, 1).cuda() y_ = (torch.rand(data.shape[0], 1) * num_labels).type(torch.LongTensor).squeeze().cuda() y_label_ = onehot[y_] y_fill_ = fill[y_] assert y_label_[0, y_[0]] == 1 assert y_label_.shape == (data.shape[0], 10, 1, 1) assert y_fill_[0, y_[0], :, :].sum() == (img_size / fraction) ** 2 assert y_fill_.sum() == (img_size / fraction) ** 2 * data.shape[0] G_result = G(z_, y_label_) # !!!#D_result = D(G_result, y_fill_).squeeze() #### KL_fake_output = F.log_softmax(model(G_result)) KL_loss_fake = F.kl_div(KL_fake_output, uniform_dist) * args.num_classes total_loss = loss + args.beta * KL_loss_fake # total_loss = loss total_loss.backward() optimizer.step() if batch_idx % args.log_interval == 0: print( "Epoch {} , Descriminator loss {:.6f} Generator loss {:.6f} traingenerator {:.6f} traindiscriminator {:.6f}".format( epoch, D_train_loss, G_train_loss, trg, trd)) print('Classification Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}, KL fake Loss: {:.6f}'.format( epoch, batch_idx * len(data), len(train_loader.dataset), 100. * batch_idx / len(train_loader), loss.data.item(), KL_loss_fake.data.item())) # print('Classification Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}, KL fake Loss: {:.6f}'.format( # epoch, batch_idx * len(data), len(train_loader.dataset), # 100. * batch_idx / len(train_loader), loss.data.item(), KL_loss_fake.data.item())) fake = G(fixed_noise.cuda(), fixed_label) vutils.save_image(fake.data, '%s/MNISTcDCgan_samples_epoch_%03d.png' % (args.outf, epoch), normalize=True) def test(epoch): model.eval() test_loss = 0 correct = 0 total = 0 for data, target in test_loader: total += data.size(0) if args.cuda: data, target = data.cuda(), target.cuda() # data, target = Variable(data, volatile=True), Variable(target) output = F.log_softmax(model(data)) target = target.type( torch.LongTensor) # https://discuss.pytorch.org/t/runtimeerror-multi-target-not-supported-newbie/10216/4 if args.cuda: output = output.cuda() target = target.cuda() target = torch.squeeze(target) test_loss += F.nll_loss(output, target).data.item() pred = output.data.max(1)[1] # get the index of the max log-probability correct += pred.eq(target.data).cpu().sum() test_loss = test_loss test_loss /= len(test_loader) # loss function already averages over batch size print('\nTest set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\n'.format( test_loss, correct, total, 100. * correct / total)) for epoch in range(1, args.epochs + 1): train(epoch) test(epoch) if epoch in decreasing_lr: G_optimizer.param_groups[0]['lr'] *= args.droprate D_optimizer.param_groups[0]['lr'] *= args.droprate optimizer.param_groups[0]['lr'] *= args.droprate if epoch % 20 == 0: # do checkpointing torch.save(G.state_dict(), '%s/netG_epoch_%d.pth' % (args.outf, epoch)) torch.save(D.state_dict(), '%s/netD_epoch_%d.pth' % (args.outf, epoch)) torch.save(model.state_dict(), '%s/model_epoch_%d.pth' % (args.outf, epoch))
37.3003
132
0.622494
h.manual_seed(args.seed) if args.cuda: torch.cuda.manual_seed(args.seed) kwargs = {'num_workers': 1, 'pin_memory': True} if args.cuda else {} print('load data: ', args.dataset) if args.dataset=='mnist': transform = transforms.Compose([ transforms.Scale(32), transforms.ToTensor(), transforms.Lambda(lambda x: x.repeat(3, 1, 1)), transforms.Normalize(mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5)) ]) train_loader = torch.utils.data.DataLoader( datasets.MNIST('data', train=True, download=True, transform=transform), batch_size=128, shuffle=True) test_loader = torch.utils.data.DataLoader( datasets.MNIST('data', train=False, download=True, transform=transform), batch_size=128, shuffle=True) else: train_loader, test_loader = data_loader.getTargetDataSet(args.dataset, args.batch_size, args.imageSize, args.dataroot) transform = transforms.Compose([ transforms.Scale(32), transforms.ToTensor(), transforms.Lambda(lambda x: x.repeat(3, 1, 1)), transforms.Normalize(mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5)) ]) train_loader_mnist = torch.utils.data.DataLoader( datasets.MNIST('data', train=True, download=True, transform=transform), batch_size=128, shuffle=True) print('Load model') model = models.vgg13() print(model) print('load GAN') nz = 100 G = models.cdcOriginalGenerator(1, nz, 64, 3) D = models.cdcOriginalDiscriminator(1, 3, 64) G.weight_init(mean=0.0, std=0.02) D.weight_init(mean=0.0, std=0.02) real_label = 1 fake_label = 0 criterion = nn.BCELoss() nz = 100 print('Setup optimizer') lr = 0.0002 batch_size = 128 optimizer = optim.Adam(model.parameters(), lr=args.lr, weight_decay=args.wd) G_optimizer = optim.Adam(G.parameters(), lr=lr, betas=(0.5, 0.999)) D_optimizer = optim.Adam(D.parameters(), lr=lr, betas=(0.5, 0.999)) decreasing_lr = list(map(int, args.decreasing_lr.split(','))) onehot = torch.zeros(10, 10).cuda() onehot = onehot.scatter_(1, torch.cuda.LongTensor([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]).view(10, 1), 1).view(10, 10, 1, 1) img_size = 32 num_labels = 10 fraction = 1 fill = torch.zeros([num_labels, num_labels, img_size / fraction, img_size / fraction]).cuda() for i in range(num_labels): fill[i, i, :, :] = 1 fill = fill.cuda() BCE_loss = nn.BCELoss() fixed_noise = torch.randn((64, 100)).view(-1, 100, 1, 1) fixed_label = None if args.cuda: model.cuda() D.cuda() G.cuda() criterion.cuda() fixed_noise = fixed_noise.cuda() first = True def train(epoch): model.train() trg = 0 trd = 0 i = 0 for batch_idx, (data, y_labels) in enumerate(train_loader): uniform_dist = torch.Tensor(data.size(0), args.num_classes).fill_((1. / args.num_classes)).cuda() x_ = data.cuda() assert x_[0, :, :, :].shape == (3, 32, 32) global first if first: global fixed_noise global fixed_label first = False fixed_label = onehot[y_labels.squeeze()[:64]] print("saving fixed_label!") vutils.save_image(data[:64], '{}/{}jointConfidencerealReference{}.png'.format(args.outf, args.dataset, epoch), normalize=True) D.zero_grad() y_ = y_labels mini_batch = x_.size()[0] y_real_ = torch.ones(mini_batch) y_fake_ = torch.zeros(mini_batch) y_real_, y_fake_ = Variable(y_real_.cuda()), Variable(y_fake_.cuda()) y_fill_ = fill[y_.squeeze().tolist()] assert y_fill_[0, y_.squeeze().tolist()[0], :, :].sum() == (img_size / fraction) ** 2 assert y_fill_.sum() == (img_size / fraction) ** 2 * mini_batch x_, y_fill_ = Variable(x_.cuda()), Variable(y_fill_.cuda()) D_result = D(x_, y_fill_).squeeze() D_real_loss = BCE_loss(D_result, y_real_) z_ = torch.randn((mini_batch, 100)).view(-1, 100, 1, 1) y_ = (torch.rand(mini_batch, 1) * num_labels).type(torch.LongTensor).squeeze() y_label_ = onehot[y_] y_fill_ = fill[y_] assert y_label_[0, y_[0]] == 1 assert y_label_.shape == (mini_batch, 10, 1, 1) assert y_fill_[0, y_[0], :, :].sum() == (img_size / fraction) ** 2 assert y_fill_.sum() == (img_size / fraction) ** 2 * mini_batch z_, y_label_, y_fill_ = Variable(z_.cuda()), Variable(y_label_.cuda()), Variable(y_fill_.cuda()) G_result = G(z_, y_label_) D_result = D(G_result, y_fill_).squeeze() D_fake_loss = BCE_loss(D_result, y_fake_) D_fake_score = D_result.data.mean() D_train_loss = D_real_loss + D_fake_loss trg += 1 if D_train_loss > .1: trd += 1 D_train_loss.backward() D_optimizer.step() G.zero_grad() z_ = torch.randn((mini_batch, 100)).view(-1, 100, 1, 1) y_ = (torch.rand(mini_batch, 1) * num_labels).type(torch.LongTensor).squeeze() y_label_ = onehot[y_] y_fill_ = fill[y_] z_, y_label_, y_fill_ = Variable(z_.cuda()), Variable(y_label_.cuda()), Variable(y_fill_.cuda()) assert y_label_[0, y_[0]] == 1 assert y_label_.shape == (mini_batch, 10, 1, 1) assert y_fill_[0, y_[0], :, :].sum() == (img_size / fraction) ** 2 assert y_fill_.sum() == (img_size / fraction) ** 2 * mini_batch G_result = G(z_, y_label_) D_result = D(G_result, y_fill_).squeeze() G_train_loss = BCE_loss(D_result, y_real_) KL_fake_output = F.log_softmax(model(G_result)) errG_KL = F.kl_div(KL_fake_output, uniform_dist) * args.num_classes generator_loss = G_train_loss + args.beta * errG_KL generator_loss.backward() G_optimizer.step() pe[0] G_result = G(z_, y_label_) x(model(G_result)) KL_loss_fake = F.kl_div(KL_fake_output, uniform_dist) * args.num_classes total_loss = loss + args.beta * KL_loss_fake total_loss.backward() optimizer.step() if batch_idx % args.log_interval == 0: print( "Epoch {} , Descriminator loss {:.6f} Generator loss {:.6f} traingenerator {:.6f} traindiscriminator {:.6f}".format( epoch, D_train_loss, G_train_loss, trg, trd)) print('Classification Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}, KL fake Loss: {:.6f}'.format( epoch, batch_idx * len(data), len(train_loader.dataset), 100. * batch_idx / len(train_loader), loss.data.item(), KL_loss_fake.data.item())) fake = G(fixed_noise.cuda(), fixed_label) vutils.save_image(fake.data, '%s/MNISTcDCgan_samples_epoch_%03d.png' % (args.outf, epoch), normalize=True) def test(epoch): model.eval() test_loss = 0 correct = 0 total = 0 for data, target in test_loader: total += data.size(0) if args.cuda: data, target = data.cuda(), target.cuda() output = F.log_softmax(model(data)) target = target.type( torch.LongTensor) if args.cuda: output = output.cuda() target = target.cuda() target = torch.squeeze(target) test_loss += F.nll_loss(output, target).data.item() pred = output.data.max(1)[1] correct += pred.eq(target.data).cpu().sum() test_loss = test_loss test_loss /= len(test_loader) print('\nTest set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\n'.format( test_loss, correct, total, 100. * correct / total)) for epoch in range(1, args.epochs + 1): train(epoch) test(epoch) if epoch in decreasing_lr: G_optimizer.param_groups[0]['lr'] *= args.droprate D_optimizer.param_groups[0]['lr'] *= args.droprate optimizer.param_groups[0]['lr'] *= args.droprate if epoch % 20 == 0: torch.save(G.state_dict(), '%s/netG_epoch_%d.pth' % (args.outf, epoch)) torch.save(D.state_dict(), '%s/netD_epoch_%d.pth' % (args.outf, epoch)) torch.save(model.state_dict(), '%s/model_epoch_%d.pth' % (args.outf, epoch))
true
true
f72cbd007d1006b7c1318b34026adba9042de0cd
5,497
py
Python
tb_rest_client/models/models_ce/page_data_ota_package_info.py
jernkuan/thingsboard-python-rest-client
3fb25272507494e6d494b27ca2380d3c543562e5
[ "Apache-2.0" ]
null
null
null
tb_rest_client/models/models_ce/page_data_ota_package_info.py
jernkuan/thingsboard-python-rest-client
3fb25272507494e6d494b27ca2380d3c543562e5
[ "Apache-2.0" ]
null
null
null
tb_rest_client/models/models_ce/page_data_ota_package_info.py
jernkuan/thingsboard-python-rest-client
3fb25272507494e6d494b27ca2380d3c543562e5
[ "Apache-2.0" ]
1
2021-11-26T11:24:56.000Z
2021-11-26T11:24:56.000Z
# coding: utf-8 """ ThingsBoard REST API For instructions how to authorize requests please visit <a href='http://thingsboard.io/docs/reference/rest-api/'>REST API documentation page</a>. # noqa: E501 OpenAPI spec version: 2.0 Contact: info@thingsboard.io Generated by: https://github.com/swagger-api/swagger-codegen.git """ import pprint import re # noqa: F401 import six class PageDataOtaPackageInfo(object): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ """ Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ swagger_types = { 'data': 'list[OtaPackageInfo]', 'has_next': 'bool', 'total_elements': 'int', 'total_pages': 'int' } attribute_map = { 'data': 'data', 'has_next': 'hasNext', 'total_elements': 'totalElements', 'total_pages': 'totalPages' } def __init__(self, data=None, has_next=None, total_elements=None, total_pages=None): # noqa: E501 """PageDataOtaPackageInfo - a model defined in Swagger""" # noqa: E501 self._data = None self._has_next = None self._total_elements = None self._total_pages = None self.discriminator = None if data is not None: self.data = data if has_next is not None: self.has_next = has_next if total_elements is not None: self.total_elements = total_elements if total_pages is not None: self.total_pages = total_pages @property def data(self): """Gets the data of this PageDataOtaPackageInfo. # noqa: E501 :return: The data of this PageDataOtaPackageInfo. # noqa: E501 :rtype: list[OtaPackageInfo] """ return self._data @data.setter def data(self, data): """Sets the data of this PageDataOtaPackageInfo. :param data: The data of this PageDataOtaPackageInfo. # noqa: E501 :type: list[OtaPackageInfo] """ self._data = data @property def has_next(self): """Gets the has_next of this PageDataOtaPackageInfo. # noqa: E501 :return: The has_next of this PageDataOtaPackageInfo. # noqa: E501 :rtype: bool """ return self._has_next @has_next.setter def has_next(self, has_next): """Sets the has_next of this PageDataOtaPackageInfo. :param has_next: The has_next of this PageDataOtaPackageInfo. # noqa: E501 :type: bool """ self._has_next = has_next @property def total_elements(self): """Gets the total_elements of this PageDataOtaPackageInfo. # noqa: E501 :return: The total_elements of this PageDataOtaPackageInfo. # noqa: E501 :rtype: int """ return self._total_elements @total_elements.setter def total_elements(self, total_elements): """Sets the total_elements of this PageDataOtaPackageInfo. :param total_elements: The total_elements of this PageDataOtaPackageInfo. # noqa: E501 :type: int """ self._total_elements = total_elements @property def total_pages(self): """Gets the total_pages of this PageDataOtaPackageInfo. # noqa: E501 :return: The total_pages of this PageDataOtaPackageInfo. # noqa: E501 :rtype: int """ return self._total_pages @total_pages.setter def total_pages(self, total_pages): """Sets the total_pages of this PageDataOtaPackageInfo. :param total_pages: The total_pages of this PageDataOtaPackageInfo. # noqa: E501 :type: int """ self._total_pages = total_pages def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value if issubclass(PageDataOtaPackageInfo, dict): for key, value in self.items(): result[key] = value return result def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, PageDataOtaPackageInfo): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Returns true if both objects are not equal""" return not self == other
29.084656
163
0.593778
import pprint import re import six class PageDataOtaPackageInfo(object): swagger_types = { 'data': 'list[OtaPackageInfo]', 'has_next': 'bool', 'total_elements': 'int', 'total_pages': 'int' } attribute_map = { 'data': 'data', 'has_next': 'hasNext', 'total_elements': 'totalElements', 'total_pages': 'totalPages' } def __init__(self, data=None, has_next=None, total_elements=None, total_pages=None): self._data = None self._has_next = None self._total_elements = None self._total_pages = None self.discriminator = None if data is not None: self.data = data if has_next is not None: self.has_next = has_next if total_elements is not None: self.total_elements = total_elements if total_pages is not None: self.total_pages = total_pages @property def data(self): return self._data @data.setter def data(self, data): self._data = data @property def has_next(self): return self._has_next @has_next.setter def has_next(self, has_next): self._has_next = has_next @property def total_elements(self): return self._total_elements @total_elements.setter def total_elements(self, total_elements): self._total_elements = total_elements @property def total_pages(self): return self._total_pages @total_pages.setter def total_pages(self, total_pages): self._total_pages = total_pages def to_dict(self): result = {} for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value if issubclass(PageDataOtaPackageInfo, dict): for key, value in self.items(): result[key] = value return result def to_str(self): return pprint.pformat(self.to_dict()) def __repr__(self): return self.to_str() def __eq__(self, other): if not isinstance(other, PageDataOtaPackageInfo): return False return self.__dict__ == other.__dict__ def __ne__(self, other): return not self == other
true
true
f72cbd8032bfba00a07e989b6b537df95ff4361b
8,128
py
Python
Chapter2/LFM.py
7125messi/rencommend_system_learning
4a8bcef241c4c0357cfbe4d1a9828b847974b69c
[ "Apache-2.0" ]
3
2019-10-10T15:49:42.000Z
2020-05-31T07:39:10.000Z
Chapter2/LFM.py
7125messi/rencommend_system_learning
4a8bcef241c4c0357cfbe4d1a9828b847974b69c
[ "Apache-2.0" ]
null
null
null
Chapter2/LFM.py
7125messi/rencommend_system_learning
4a8bcef241c4c0357cfbe4d1a9828b847974b69c
[ "Apache-2.0" ]
2
2019-09-18T07:59:48.000Z
2020-01-16T15:00:48.000Z
# 导入包 import random import math import numpy as np import time from tqdm import tqdm from tqdm import trange # 1 通用函数定义 ## 定义装饰器,监控运行时间 def timmer(func): def wrapper(*args, **kwargs): start_time = time.time() res = func(*args, **kwargs) stop_time = time.time() print('Func {},run time:{}'.format(func.__name__,stop_time - start_time)) return res return wrapper ## 数据处理相关 ### load data ### split data class Dataset(): def __init__(self,fp): self.data = self.loadData(fp) @timmer def loadData(self,fp): data = [] for l in open(fp): data.append(tuple(map(int, l.strip().split('::')[:2]))) return data @timmer def splitData(self, M, k, seed=1): ''' :params: data, 加载的所有(user, item)数据条目 :params: M, 划分的数目,最后需要取M折的平均 :params: k, 本次是第几次划分,k~[0, M) :params: seed, random的种子数,对于不同的k应设置成一样的 :return: train, test ''' train , test = [], [] random.seed(seed) for user, item in self.data: # 这里与书中的不一致,本人认为取M-1较为合理,因randint是左右都覆盖的 if random.randint(0, M-1) == k: test.append((user, item)) else: train.append((user, item)) # 处理成字典的形式,user->set(items) def convert_dict(data): data_dict = {} for user, item in data: if user not in data_dict: data_dict[user] = set() data_dict[user].add(item) data_dict = {k: list(data_dict[k]) for k in data_dict} return data_dict return convert_dict(train), convert_dict(test) ## 评价指标 ### Precision ### Recall ### Coverage ### Popularity(Novelty) class Metric(): def __init__(self, train, test, GetRecommendation): ''' :params: train, 训练数据 :params: test, 测试数据 :params: GetRecommendation, 为某个用户获取推荐物品的接口函数 ''' self.train = train self.test = test self.GetRecommendation = GetRecommendation self.recs = self.getRec() # 为test中的每个用户进行推荐 def getRec(self): recs = {} for user in self.test: rank = self.GetRecommendation(user) recs[user] = rank return recs # 定义精确率指标计算方式 def precision(self): all, hit = 0, 0 for user in self.test: test_items = set(self.test[user]) rank = self.recs[user] for item, score in rank: if item in test_items: hit += 1 all += len(rank) return round(hit / all * 100, 2) # 定义召回率指标计算方式 def recall(self): all, hit = 0, 0 for user in self.test: test_items = set(self.test[user]) rank = self.recs[user] for item, score in rank: if item in test_items: hit += 1 all += len(test_items) return round(hit / all * 100, 2) # 定义覆盖率指标计算方式 def coverage(self): all_item, recom_item = set(), set() for user in self.test: for item in self.train[user]: all_item.add(item) rank = self.recs[user] for item, score in rank: recom_item.add(item) return round(len(recom_item) / len(all_item) * 100, 2) # 定义新颖度指标计算方式 def popularity(self): # 计算物品的流行度 item_pop = {} for user in self.train: for item in self.train[user]: if item not in item_pop: item_pop[item] = 0 item_pop[item] += 1 num, pop = 0, 0 for user in self.test: rank = self.recs[user] for item, score in rank: # 取对数,防止因长尾问题带来的被流行物品所主导 pop += math.log(1 + item_pop[item]) num += 1 return round(pop / num, 6) def eval(self): metric = {'Precision': self.precision(), 'Recall': self.recall(), 'Coverage': self.coverage(), 'Popularity': self.popularity()} print('Metric:', metric) return metric # 2 LFM算法实现 def LFM(train,ratio,K,lr,step,lmbda,N): ''' :params: train, 训练数据 :params: ratio, 负采样的正负比例 :params: K, 隐语义个数 :params: lr, 初始学习率 :params: step, 迭代次数 :params: lmbda, 正则化系数 :params: N, 推荐TopN物品的个数 :return: GetRecommendation, 获取推荐结果的接口 ''' all_items = {} for user in train: for item in train[user]: if item not in all_items: all_items[item] = 0 all_items[item] += 1 all_items = list(all_items.items()) items = [x[0] for x in all_items] pops = [x[1] for x in all_items] # 负采样函数(按照流行度就行采样) def nSample(data,ratio): new_data = {} # 正样本 for user in data: if user not in new_data: new_data[user] = {} for item in data[user]: new_data[user][item] = 1 # 负样本 for user in new_data: seen = set(new_data[user]) pos_num = len(seen) item = np.random.choice(items, int(pos_num * ratio * 3), pops) item = [x for x in item if x not in seen][:int(pos_num * ratio)] new_data[user].update({x: 0 for x in item}) return new_data # 训练 P, Q = {}, {} for user in train: P[user] = np.random.random(K) for item in items: Q[item] = np.random.random(K) for s in trange(step): data = nSample(train, ratio) for user in data: for item in data[user]: eui = data[user][item] - (P[user] * Q[item]).sum() P[user] += lr * (Q[item] * eui - lmbda * P[user]) Q[item] += lr * (P[user] * eui - lmbda * Q[item]) lr *= 0.9 # 调整学习率 # 获取接口函数 def GetRecommendation(user): seen_items = set(train[user]) recs = {} for item in items: if item not in seen_items: recs[item] = (P[user] * Q[item]).sum() recs = list(sorted(recs.items(), key=lambda x: x[1], reverse=True))[:N] return recs return GetRecommendation # 3 LFM实验 ## M=8, N=10, ratio=[1, 2, 3, 5, 10, 20] class Experiment(): def __init__(self, M, N, ratio=1, K=100, lr=0.02, step=100, lmbda=0.01, fp='../dataset/ml-1m/ratings.dat'): ''' :params: M, 进行多少次实验 :params: N, TopN推荐物品的个数 :params: ratio, 正负样本比例 :params: K, 隐语义个数 :params: lr, 学习率 :params: step, 训练步数 :params: lmbda, 正则化系数 :params: fp, 数据文件路径 ''' self.M = M self.K = K self.N = N self.ratio = ratio self.lr = lr self.step = step self.lmbda = lmbda self.fp = fp self.alg = LFM # 定义单次实验 @timmer def worker(self, train, test): ''' :params: train, 训练数据集 :params: test, 测试数据集 :return: 各指标的值 ''' getRecommendation = self.alg(train, self.ratio, self.K, self.lr, self.step, self.lmbda, self.N) metric = Metric(train, test, getRecommendation) return metric.eval() # 多次实验取平均 @timmer def run(self): metrics = {'Precision': 0, 'Recall': 0, 'Coverage': 0, 'Popularity': 0} dataset = Dataset(self.fp) for ii in range(self.M): train, test = dataset.splitData(self.M, ii) print('Experiment {}:'.format(ii)) metric = self.worker(train, test) metrics = {k: metrics[k]+metric[k] for k in metrics} metrics = {k: metrics[k] / self.M for k in metrics} print('Average Result (M={}, N={}, ratio={}): {}'.format(\ self.M, self.N, self.ratio, metrics)) # LFM实验(运行时间较长,这里没贴实验结果) M, N = 8, 10 for r in [1, 2, 3, 5, 10, 20]: exp = Experiment(M, N, ratio=r) exp.run()
29.028571
93
0.506275
import random import math import numpy as np import time from tqdm import tqdm from tqdm import trange nc): def wrapper(*args, **kwargs): start_time = time.time() res = func(*args, **kwargs) stop_time = time.time() print('Func {},run time:{}'.format(func.__name__,stop_time - start_time)) return res return wrapper elf.data = self.loadData(fp) @timmer def loadData(self,fp): data = [] for l in open(fp): data.append(tuple(map(int, l.strip().split('::')[:2]))) return data @timmer def splitData(self, M, k, seed=1): train , test = [], [] random.seed(seed) for user, item in self.data: if random.randint(0, M-1) == k: test.append((user, item)) else: train.append((user, item)) def convert_dict(data): data_dict = {} for user, item in data: if user not in data_dict: data_dict[user] = set() data_dict[user].add(item) data_dict = {k: list(data_dict[k]) for k in data_dict} return data_dict return convert_dict(train), convert_dict(test) self.test = test self.GetRecommendation = GetRecommendation self.recs = self.getRec() def getRec(self): recs = {} for user in self.test: rank = self.GetRecommendation(user) recs[user] = rank return recs def precision(self): all, hit = 0, 0 for user in self.test: test_items = set(self.test[user]) rank = self.recs[user] for item, score in rank: if item in test_items: hit += 1 all += len(rank) return round(hit / all * 100, 2) def recall(self): all, hit = 0, 0 for user in self.test: test_items = set(self.test[user]) rank = self.recs[user] for item, score in rank: if item in test_items: hit += 1 all += len(test_items) return round(hit / all * 100, 2) def coverage(self): all_item, recom_item = set(), set() for user in self.test: for item in self.train[user]: all_item.add(item) rank = self.recs[user] for item, score in rank: recom_item.add(item) return round(len(recom_item) / len(all_item) * 100, 2) def popularity(self): item_pop = {} for user in self.train: for item in self.train[user]: if item not in item_pop: item_pop[item] = 0 item_pop[item] += 1 num, pop = 0, 0 for user in self.test: rank = self.recs[user] for item, score in rank: pop += math.log(1 + item_pop[item]) num += 1 return round(pop / num, 6) def eval(self): metric = {'Precision': self.precision(), 'Recall': self.recall(), 'Coverage': self.coverage(), 'Popularity': self.popularity()} print('Metric:', metric) return metric def LFM(train,ratio,K,lr,step,lmbda,N): all_items = {} for user in train: for item in train[user]: if item not in all_items: all_items[item] = 0 all_items[item] += 1 all_items = list(all_items.items()) items = [x[0] for x in all_items] pops = [x[1] for x in all_items] def nSample(data,ratio): new_data = {} for user in data: if user not in new_data: new_data[user] = {} for item in data[user]: new_data[user][item] = 1 for user in new_data: seen = set(new_data[user]) pos_num = len(seen) item = np.random.choice(items, int(pos_num * ratio * 3), pops) item = [x for x in item if x not in seen][:int(pos_num * ratio)] new_data[user].update({x: 0 for x in item}) return new_data P, Q = {}, {} for user in train: P[user] = np.random.random(K) for item in items: Q[item] = np.random.random(K) for s in trange(step): data = nSample(train, ratio) for user in data: for item in data[user]: eui = data[user][item] - (P[user] * Q[item]).sum() P[user] += lr * (Q[item] * eui - lmbda * P[user]) Q[item] += lr * (P[user] * eui - lmbda * Q[item]) lr *= 0.9 def GetRecommendation(user): seen_items = set(train[user]) recs = {} for item in items: if item not in seen_items: recs[item] = (P[user] * Q[item]).sum() recs = list(sorted(recs.items(), key=lambda x: x[1], reverse=True))[:N] return recs return GetRecommendation self, M, N, ratio=1, K=100, lr=0.02, step=100, lmbda=0.01, fp='../dataset/ml-1m/ratings.dat'): self.M = M self.K = K self.N = N self.ratio = ratio self.lr = lr self.step = step self.lmbda = lmbda self.fp = fp self.alg = LFM @timmer def worker(self, train, test): getRecommendation = self.alg(train, self.ratio, self.K, self.lr, self.step, self.lmbda, self.N) metric = Metric(train, test, getRecommendation) return metric.eval() @timmer def run(self): metrics = {'Precision': 0, 'Recall': 0, 'Coverage': 0, 'Popularity': 0} dataset = Dataset(self.fp) for ii in range(self.M): train, test = dataset.splitData(self.M, ii) print('Experiment {}:'.format(ii)) metric = self.worker(train, test) metrics = {k: metrics[k]+metric[k] for k in metrics} metrics = {k: metrics[k] / self.M for k in metrics} print('Average Result (M={}, N={}, ratio={}): {}'.format(\ self.M, self.N, self.ratio, metrics)) M, N = 8, 10 for r in [1, 2, 3, 5, 10, 20]: exp = Experiment(M, N, ratio=r) exp.run()
true
true
f72cbd82ce65ea7deeb9b12673a6fa17f65eaeaa
2,015
py
Python
intake_questgdal/base.py
Aquaveo/intake_questgdal
c11cd111a53b7270391c6923d0e252c4abbbc56b
[ "BSD-3-Clause" ]
null
null
null
intake_questgdal/base.py
Aquaveo/intake_questgdal
c11cd111a53b7270391c6923d0e252c4abbbc56b
[ "BSD-3-Clause" ]
1
2019-06-06T15:28:15.000Z
2019-06-06T15:28:15.000Z
intake_questgdal/base.py
Aquaveo/intake_questgdal
c11cd111a53b7270391c6923d0e252c4abbbc56b
[ "BSD-3-Clause" ]
null
null
null
from intake.source.base import DataSource, Schema import rasterio import xarray as xr import warnings # from . import __version__ class quest_gdal_base(DataSource): """Reads an HDF5 table Parameters ---------- path: str File to load. tablename: str Name of table to load. metadata: Arbitrary information to associate with this source. """ #version = __version__ version = '0.0.1' container = 'dataframe' partition_access = False path = '' # def _get_schema(self): # self._schema = Schema( # datashape=None, # dtype=None, # shape=None, # npartitions=1, # extra_metadata={} # ) # return self._schema def _get_schema(self): if self.path is not '': xarr = xr.open_rasterio(self.path) ds2 = xr.Dataset({'raster': xarr}) metadata = { 'dims': dict(ds2.dims), 'data_vars': {k: list(ds2[k].coords) for k in ds2.data_vars.keys()}, 'coords': tuple(ds2.coords.keys()), 'array': 'raster' } atts = ['transform', 'crs', 'res', 'is_tiled', 'nodatavals'] for att in atts: if att in xarr.attrs: metadata[att] = xarr.attrs[att] return Schema( datashape=None, dtype = str(xarr.dtype), shape=xarr.shape, npartitions=1, extra_metadata=metadata ) else: self._schema = Schema( datashape=None, dtype=None, shape=None, npartitions=1, extra_metadata={} ) return self._schema def _get_partition(self, _): return None def _close(self): pass def raster_data(self, path): return rasterio.open(path)
26.168831
72
0.4933
from intake.source.base import DataSource, Schema import rasterio import xarray as xr import warnings class quest_gdal_base(DataSource): version = '0.0.1' container = 'dataframe' partition_access = False path = '' def _get_schema(self): if self.path is not '': xarr = xr.open_rasterio(self.path) ds2 = xr.Dataset({'raster': xarr}) metadata = { 'dims': dict(ds2.dims), 'data_vars': {k: list(ds2[k].coords) for k in ds2.data_vars.keys()}, 'coords': tuple(ds2.coords.keys()), 'array': 'raster' } atts = ['transform', 'crs', 'res', 'is_tiled', 'nodatavals'] for att in atts: if att in xarr.attrs: metadata[att] = xarr.attrs[att] return Schema( datashape=None, dtype = str(xarr.dtype), shape=xarr.shape, npartitions=1, extra_metadata=metadata ) else: self._schema = Schema( datashape=None, dtype=None, shape=None, npartitions=1, extra_metadata={} ) return self._schema def _get_partition(self, _): return None def _close(self): pass def raster_data(self, path): return rasterio.open(path)
true
true
f72cbdde941379a53be16076b51cf17c429ca67d
6,353
py
Python
mooringlicensing/management/commands/approval_renewal_notices.py
jawaidm/mooringlicensing
b22e74209da8655c8ad3af99e00f36d17c8ef73f
[ "Apache-2.0" ]
null
null
null
mooringlicensing/management/commands/approval_renewal_notices.py
jawaidm/mooringlicensing
b22e74209da8655c8ad3af99e00f36d17c8ef73f
[ "Apache-2.0" ]
2
2021-03-05T06:48:11.000Z
2021-03-26T08:14:17.000Z
mooringlicensing/management/commands/approval_renewal_notices.py
jawaidm/mooringlicensing
b22e74209da8655c8ad3af99e00f36d17c8ef73f
[ "Apache-2.0" ]
2
2021-09-19T15:45:19.000Z
2021-10-05T05:07:41.000Z
from django.core.management.base import BaseCommand from django.utils import timezone from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.db.models import Q from mooringlicensing.components.approvals.models import ( Approval, WaitingListAllocation, AnnualAdmissionPermit, AuthorisedUserPermit, MooringLicence, DcvPermit, ) from ledger.accounts.models import EmailUser from datetime import timedelta from mooringlicensing.components.proposals.email import send_approval_renewal_email_notification import logging from mooringlicensing.components.main.models import NumberOfDaysType, NumberOfDaysSetting from mooringlicensing.settings import ( CODE_DAYS_FOR_RENEWAL_WLA, CODE_DAYS_FOR_RENEWAL_AAP, CODE_DAYS_FOR_RENEWAL_AUP, CODE_DAYS_FOR_RENEWAL_ML, CODE_DAYS_FOR_RENEWAL_DCVP, ) logger = logging.getLogger(__name__) class Command(BaseCommand): help = 'Send Approval renewal notice when approval is due to expire in 30 days' def perform_per_type(self, number_of_days_code, approval_class, updates, errors): today = timezone.localtime(timezone.now()).date() # Retrieve the number of days before expiry date of the approvals to email days_type = NumberOfDaysType.objects.get(code=number_of_days_code) days_setting = NumberOfDaysSetting.get_setting_by_date(days_type, today) if not days_setting: # No number of days found raise ImproperlyConfigured("NumberOfDays: {} is not defined for the date: {}".format(days_type.name, today)) expiry_notification_date = today + timedelta(days=days_setting.number_of_days) logger.info('Running command {}'.format(__name__)) # Construct queries queries = Q() if number_of_days_code == CODE_DAYS_FOR_RENEWAL_DCVP: queries &= Q(end_date__lte=expiry_notification_date) queries &= Q(renewal_sent=False) queries &= Q(status__in=[DcvPermit.DCV_PERMIT_STATUS_CURRENT,]) else: queries &= Q(expiry_date__lte=expiry_notification_date) queries &= Q(renewal_sent=False) queries &= Q(replaced_by__isnull=True) queries &= Q(status__in=(Approval.APPROVAL_STATUS_CURRENT, Approval.APPROVAL_STATUS_SUSPENDED)) approvals = approval_class.objects.filter(queries) for a in approvals: try: if approval_class == DcvPermit: # send_approval_renewal_email_notification_dcvp(a) pass else: a.generate_renewal_doc() send_approval_renewal_email_notification(a) a.renewal_sent = True a.save() logger.info('Renewal notice sent for Approval {}'.format(a.id)) updates.append(a.lodgement_number) except Exception as e: err_msg = 'Error sending renewal notice for Approval {}'.format(a.lodgement_number) logger.error('{}\n{}'.format(err_msg, str(e))) errors.append(err_msg) def handle(self, *args, **options): try: user = EmailUser.objects.get(email=settings.CRON_EMAIL) except: user = EmailUser.objects.create(email=settings.CRON_EMAIL, password='') updates, errors = [], [] self.perform_per_type(CODE_DAYS_FOR_RENEWAL_WLA, WaitingListAllocation, updates, errors) self.perform_per_type(CODE_DAYS_FOR_RENEWAL_AAP, AnnualAdmissionPermit, updates, errors) self.perform_per_type(CODE_DAYS_FOR_RENEWAL_AUP, AuthorisedUserPermit, updates, errors) self.perform_per_type(CODE_DAYS_FOR_RENEWAL_ML, MooringLicence, updates, errors) # today = timezone.localtime(timezone.now()).date() # # # Retrieve the number of days before expiry date of the approvals to email # days_type = NumberOfDaysType.objects.get(code=CODE_DAYS_FOR_RENEWAL) # days_setting = NumberOfDaysSetting.get_setting_by_date(days_type, today) # if not days_setting: # # No number of days found # raise ImproperlyConfigured("NumberOfDays: {} is not defined for the date: {}".format(days_type.name, today)) # # expiry_notification_date = today + timedelta(days=days_setting.number_of_days) # # # Construct queries # queries = Q() # queries &= Q(expiry_date__lte=expiry_notification_date) # queries &= Q(renewal_sent=False) # queries &= Q(replaced_by__isnull=True) # queries &= Q(status__in=(Approval.APPROVAL_STATUS_CURRENT, Approval.APPROVAL_STATUS_SUSPENDED)) # # # For debug # # params = options.get('params') # # debug = True if params.get('debug', 'f').lower() in ['true', 't', 'yes', 'y'] else False # # approval_lodgement_number = params.get('approval_renewal_notices_lodgement_number', 'no-lodgement-number') # # if debug: # # queries = queries | Q(lodgement_number__iexact=approval_lodgement_number) # # logger.info('Running command {}'.format(__name__)) # # for a in Approval.objects.filter(**renewal_conditions): # for a in Approval.objects.filter(queries): # # if a.status == Approval.APPROVAL_STATUS_CURRENT or a.status == Approval.APPROVAL_STATUS_SUSPENDED: # try: # a.generate_renewal_doc() # send_approval_renewal_email_notification(a) # a.renewal_sent = True # a.save() # logger.info('Renewal notice sent for Approval {}'.format(a.id)) # updates.append(a.lodgement_number) # except Exception as e: # err_msg = 'Error sending renewal notice for Approval {}'.format(a.lodgement_number) # logger.error('{}\n{}'.format(err_msg, str(e))) # errors.append(err_msg) cmd_name = __name__.split('.')[-1].replace('_', ' ').upper() err_str = '<strong style="color: red;">Errors: {}</strong>'.format(len(errors)) if len(errors)>0 else '<strong style="color: green;">Errors: 0</strong>' msg = '<p>{} completed. {}. IDs updated: {}.</p>'.format(cmd_name, err_str, updates) logger.info(msg) print(msg) # will redirect to cron_tasks.log file, by the parent script
45.705036
160
0.668346
from django.core.management.base import BaseCommand from django.utils import timezone from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.db.models import Q from mooringlicensing.components.approvals.models import ( Approval, WaitingListAllocation, AnnualAdmissionPermit, AuthorisedUserPermit, MooringLicence, DcvPermit, ) from ledger.accounts.models import EmailUser from datetime import timedelta from mooringlicensing.components.proposals.email import send_approval_renewal_email_notification import logging from mooringlicensing.components.main.models import NumberOfDaysType, NumberOfDaysSetting from mooringlicensing.settings import ( CODE_DAYS_FOR_RENEWAL_WLA, CODE_DAYS_FOR_RENEWAL_AAP, CODE_DAYS_FOR_RENEWAL_AUP, CODE_DAYS_FOR_RENEWAL_ML, CODE_DAYS_FOR_RENEWAL_DCVP, ) logger = logging.getLogger(__name__) class Command(BaseCommand): help = 'Send Approval renewal notice when approval is due to expire in 30 days' def perform_per_type(self, number_of_days_code, approval_class, updates, errors): today = timezone.localtime(timezone.now()).date() days_type = NumberOfDaysType.objects.get(code=number_of_days_code) days_setting = NumberOfDaysSetting.get_setting_by_date(days_type, today) if not days_setting: raise ImproperlyConfigured("NumberOfDays: {} is not defined for the date: {}".format(days_type.name, today)) expiry_notification_date = today + timedelta(days=days_setting.number_of_days) logger.info('Running command {}'.format(__name__)) queries = Q() if number_of_days_code == CODE_DAYS_FOR_RENEWAL_DCVP: queries &= Q(end_date__lte=expiry_notification_date) queries &= Q(renewal_sent=False) queries &= Q(status__in=[DcvPermit.DCV_PERMIT_STATUS_CURRENT,]) else: queries &= Q(expiry_date__lte=expiry_notification_date) queries &= Q(renewal_sent=False) queries &= Q(replaced_by__isnull=True) queries &= Q(status__in=(Approval.APPROVAL_STATUS_CURRENT, Approval.APPROVAL_STATUS_SUSPENDED)) approvals = approval_class.objects.filter(queries) for a in approvals: try: if approval_class == DcvPermit: pass else: a.generate_renewal_doc() send_approval_renewal_email_notification(a) a.renewal_sent = True a.save() logger.info('Renewal notice sent for Approval {}'.format(a.id)) updates.append(a.lodgement_number) except Exception as e: err_msg = 'Error sending renewal notice for Approval {}'.format(a.lodgement_number) logger.error('{}\n{}'.format(err_msg, str(e))) errors.append(err_msg) def handle(self, *args, **options): try: user = EmailUser.objects.get(email=settings.CRON_EMAIL) except: user = EmailUser.objects.create(email=settings.CRON_EMAIL, password='') updates, errors = [], [] self.perform_per_type(CODE_DAYS_FOR_RENEWAL_WLA, WaitingListAllocation, updates, errors) self.perform_per_type(CODE_DAYS_FOR_RENEWAL_AAP, AnnualAdmissionPermit, updates, errors) self.perform_per_type(CODE_DAYS_FOR_RENEWAL_AUP, AuthorisedUserPermit, updates, errors) self.perform_per_type(CODE_DAYS_FOR_RENEWAL_ML, MooringLicence, updates, errors)
true
true
f72cbe35893af2f1b2c363e8fe4e587be57b909c
6,321
py
Python
InterventionsMIP/main.py
haoxiangyang89/COVID_Staged_Alert
4c2cc5ef1d38c140875380a5f10a0fe1eaf8a47a
[ "MIT" ]
1
2021-06-24T19:27:01.000Z
2021-06-24T19:27:01.000Z
InterventionsMIP/main.py
haoxiangyang89/COVID_Staged_Alert
4c2cc5ef1d38c140875380a5f10a0fe1eaf8a47a
[ "MIT" ]
null
null
null
InterventionsMIP/main.py
haoxiangyang89/COVID_Staged_Alert
4c2cc5ef1d38c140875380a5f10a0fe1eaf8a47a
[ "MIT" ]
3
2021-12-15T13:32:25.000Z
2022-02-24T13:57:07.000Z
from InterventionsMIP import project_path, instances_path import multiprocessing as mp from threshold_policy import threshold_policy_search from interventions import Intervension from epi_params import EpiSetup, ParamDistribution from utils import parse_arguments from reporting.plotting import plot_stoch_simulations from instances import load_instance if __name__ == '__main__': # Parse arguments args = parse_arguments() # Parse city and get corresponding instance instance = load_instance(args.city, setup_file_name=args.f) # TODO Read command line args for n_proc for better integration with crunch n_proc = args.n_proc # TODO: pull out n_replicas_train and n_replicas_test to a config file n_replicas_train = args.train_reps n_replicas_test = args.test_reps # Create the pool (Note: pool needs to be created only once to run on a cluster) mp_pool = mp.Pool(n_proc) if n_proc > 1 else None for sc in [0]: for co in [0.95]: for base_line_train in [0.4]: for base_line_test in [0.4]: for const in ['test']: #[10 * i for i in range(0, 21)] + [215, 1000]: policy_class = 'step' instance_name = f'local_{instance.city}_SC{sc}_CO{co}_BLTrain{base_line_train}_BLTest_{base_line_test}_{policy_class}_{const}' print('\n============================================') print(instance_name) #TODO: This list should be longe to include all possible transmission reduction values # that might come in the instance file interventions_train = [ Intervension(0, 0, 0, instance.epi, instance.N), Intervension(1, 0, 0, instance.epi, instance.N), Intervension(0, 0, base_line_train, instance.epi, instance.N), Intervension(1, 0, base_line_train, instance.epi, instance.N), Intervension(1, 0, 0.9, instance.epi, instance.N), Intervension(0, co, base_line_train, instance.epi, instance.N), Intervension(1, co, base_line_train, instance.epi, instance.N), Intervension(1, co, 0.9, instance.epi, instance.N), Intervension(1, 0, 0.95, instance.epi, instance.N), Intervension(0, 0, 0.95, instance.epi, instance.N) ] interventions_test = [ Intervension(0, 0, 0, instance.epi, instance.N), Intervension(1, 0, 0, instance.epi, instance.N), Intervension(0, 0, base_line_test, instance.epi, instance.N), Intervension(1, 0, base_line_test, instance.epi, instance.N), Intervension(1, 0, 0.9, instance.epi, instance.N), Intervension(0, co, base_line_test, instance.epi, instance.N), Intervension(1, co, base_line_test, instance.epi, instance.N), Intervension(1, co, 0.9, instance.epi, instance.N), Intervension(1, 0, 0.95, instance.epi, instance.N), Intervension(0, 0, 0.95, instance.epi, instance.N) ] sd_levels_train = {'H': 0.9, 'L': base_line_train} sd_levels_test = {'H': 0.9, 'L': base_line_test} best_policy_replicas, policy_params = threshold_policy_search(instance, interventions_train, interventions_test, sd_levels_train, sd_levels_test, cocooning=co, school_closure=sc, mp_pool=mp_pool, n_replicas_train=n_replicas_train, n_replicas_test=n_replicas_test, instance_name=instance_name, policy={ 'class': policy_class, 'vals': [120, 216, 9] }, policy_class=policy_class) n_replicas = len(best_policy_replicas) plot_stoch_simulations( instance_name, best_policy_replicas, ['sim'] * n_replicas, plot_left_axis=['IH'], plot_right_axis=[], T=instance.T, #437, hosp_beds=instance.hosp_beds, population=instance.N.sum(), interventions=interventions_test, calendar=instance.cal, policy_params=policy_params, plot_triggers=True, plot_legend=True, show=True, align_axes=True, n_replicas=5, BL=base_line_test)
64.5
150
0.424933
from InterventionsMIP import project_path, instances_path import multiprocessing as mp from threshold_policy import threshold_policy_search from interventions import Intervension from epi_params import EpiSetup, ParamDistribution from utils import parse_arguments from reporting.plotting import plot_stoch_simulations from instances import load_instance if __name__ == '__main__': args = parse_arguments() instance = load_instance(args.city, setup_file_name=args.f) n_proc = args.n_proc n_replicas_train = args.train_reps n_replicas_test = args.test_reps mp_pool = mp.Pool(n_proc) if n_proc > 1 else None for sc in [0]: for co in [0.95]: for base_line_train in [0.4]: for base_line_test in [0.4]: for const in ['test']: policy_class = 'step' instance_name = f'local_{instance.city}_SC{sc}_CO{co}_BLTrain{base_line_train}_BLTest_{base_line_test}_{policy_class}_{const}' print('\n============================================') print(instance_name) interventions_train = [ Intervension(0, 0, 0, instance.epi, instance.N), Intervension(1, 0, 0, instance.epi, instance.N), Intervension(0, 0, base_line_train, instance.epi, instance.N), Intervension(1, 0, base_line_train, instance.epi, instance.N), Intervension(1, 0, 0.9, instance.epi, instance.N), Intervension(0, co, base_line_train, instance.epi, instance.N), Intervension(1, co, base_line_train, instance.epi, instance.N), Intervension(1, co, 0.9, instance.epi, instance.N), Intervension(1, 0, 0.95, instance.epi, instance.N), Intervension(0, 0, 0.95, instance.epi, instance.N) ] interventions_test = [ Intervension(0, 0, 0, instance.epi, instance.N), Intervension(1, 0, 0, instance.epi, instance.N), Intervension(0, 0, base_line_test, instance.epi, instance.N), Intervension(1, 0, base_line_test, instance.epi, instance.N), Intervension(1, 0, 0.9, instance.epi, instance.N), Intervension(0, co, base_line_test, instance.epi, instance.N), Intervension(1, co, base_line_test, instance.epi, instance.N), Intervension(1, co, 0.9, instance.epi, instance.N), Intervension(1, 0, 0.95, instance.epi, instance.N), Intervension(0, 0, 0.95, instance.epi, instance.N) ] sd_levels_train = {'H': 0.9, 'L': base_line_train} sd_levels_test = {'H': 0.9, 'L': base_line_test} best_policy_replicas, policy_params = threshold_policy_search(instance, interventions_train, interventions_test, sd_levels_train, sd_levels_test, cocooning=co, school_closure=sc, mp_pool=mp_pool, n_replicas_train=n_replicas_train, n_replicas_test=n_replicas_test, instance_name=instance_name, policy={ 'class': policy_class, 'vals': [120, 216, 9] }, policy_class=policy_class) n_replicas = len(best_policy_replicas) plot_stoch_simulations( instance_name, best_policy_replicas, ['sim'] * n_replicas, plot_left_axis=['IH'], plot_right_axis=[], T=instance.T, hosp_beds=instance.hosp_beds, population=instance.N.sum(), interventions=interventions_test, calendar=instance.cal, policy_params=policy_params, plot_triggers=True, plot_legend=True, show=True, align_axes=True, n_replicas=5, BL=base_line_test)
true
true
f72cbe73762b18771ed1651cd35031464722fae9
19,152
py
Python
official/nlp/transformer/transformer_main.py
873040/Abhishek
2ddd716e66bc5cc6e6f0787508dd07da0e02e75a
[ "Apache-2.0" ]
4
2020-03-13T14:01:32.000Z
2021-05-31T17:17:32.000Z
official/nlp/transformer/transformer_main.py
873040/Abhishek
2ddd716e66bc5cc6e6f0787508dd07da0e02e75a
[ "Apache-2.0" ]
10
2019-12-28T21:31:19.000Z
2020-04-12T20:01:58.000Z
official/nlp/transformer/transformer_main.py
873040/Abhishek
2ddd716e66bc5cc6e6f0787508dd07da0e02e75a
[ "Apache-2.0" ]
8
2020-04-12T04:30:33.000Z
2021-09-17T20:54:44.000Z
# Copyright 2018 The TensorFlow Authors. 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. # ============================================================================== """Train and evaluate the Transformer model. See README for description of setting the training schedule and evaluating the BLEU score. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import tempfile from absl import app from absl import flags from absl import logging import tensorflow as tf from official.modeling import performance from official.nlp.transformer import compute_bleu from official.nlp.transformer import data_pipeline from official.nlp.transformer import metrics from official.nlp.transformer import misc from official.nlp.transformer import optimizer from official.nlp.transformer import transformer from official.nlp.transformer import translate from official.nlp.transformer.utils import tokenizer from official.utils.flags import core as flags_core from official.utils.logs import logger from official.utils.misc import distribution_utils from official.utils.misc import keras_utils INF = int(1e9) BLEU_DIR = "bleu" _SINGLE_SAMPLE = 1 def translate_and_compute_bleu(model, params, subtokenizer, bleu_source, bleu_ref, distribution_strategy=None): """Translate file and report the cased and uncased bleu scores. Args: model: A Keras model, used to generate the translations. params: A dictionary, containing the translation related parameters. subtokenizer: A subtokenizer object, used for encoding and decoding source and translated lines. bleu_source: A file containing source sentences for translation. bleu_ref: A file containing the reference for the translated sentences. distribution_strategy: A platform distribution strategy, used for TPU based translation. Returns: uncased_score: A float, the case insensitive BLEU score. cased_score: A float, the case sensitive BLEU score. """ # Create temporary file to store translation. tmp = tempfile.NamedTemporaryFile(delete=False) tmp_filename = tmp.name translate.translate_file( model, params, subtokenizer, bleu_source, output_file=tmp_filename, print_all_translations=False, distribution_strategy=distribution_strategy) # Compute uncased and cased bleu scores. uncased_score = compute_bleu.bleu_wrapper(bleu_ref, tmp_filename, False) cased_score = compute_bleu.bleu_wrapper(bleu_ref, tmp_filename, True) os.remove(tmp_filename) return uncased_score, cased_score def evaluate_and_log_bleu(model, params, bleu_source, bleu_ref, vocab_file, distribution_strategy=None): """Calculate and record the BLEU score. Args: model: A Keras model, used to generate the translations. params: A dictionary, containing the translation related parameters. bleu_source: A file containing source sentences for translation. bleu_ref: A file containing the reference for the translated sentences. vocab_file: A file containing the vocabulary for translation. distribution_strategy: A platform distribution strategy, used for TPU based translation. Returns: uncased_score: A float, the case insensitive BLEU score. cased_score: A float, the case sensitive BLEU score. """ subtokenizer = tokenizer.Subtokenizer(vocab_file) uncased_score, cased_score = translate_and_compute_bleu( model, params, subtokenizer, bleu_source, bleu_ref, distribution_strategy) logging.info("Bleu score (uncased): %s", uncased_score) logging.info("Bleu score (cased): %s", cased_score) return uncased_score, cased_score class TransformerTask(object): """Main entry of Transformer model.""" def __init__(self, flags_obj): """Init function of TransformerMain. Args: flags_obj: Object containing parsed flag values, i.e., FLAGS. Raises: ValueError: if not using static batch for input data on TPU. """ self.flags_obj = flags_obj self.predict_model = None # Add flag-defined parameters to params object num_gpus = flags_core.get_num_gpus(flags_obj) self.params = params = misc.get_model_params(flags_obj.param_set, num_gpus) params["num_gpus"] = num_gpus params["use_ctl"] = flags_obj.use_ctl params["data_dir"] = flags_obj.data_dir params["model_dir"] = flags_obj.model_dir params["static_batch"] = flags_obj.static_batch params["max_length"] = flags_obj.max_length params["decode_batch_size"] = flags_obj.decode_batch_size params["decode_max_length"] = flags_obj.decode_max_length params["padded_decode"] = flags_obj.padded_decode params["num_parallel_calls"] = ( flags_obj.num_parallel_calls or tf.data.experimental.AUTOTUNE) params["use_synthetic_data"] = flags_obj.use_synthetic_data params["batch_size"] = flags_obj.batch_size or params["default_batch_size"] params["repeat_dataset"] = None params["dtype"] = flags_core.get_tf_dtype(flags_obj) params["enable_tensorboard"] = flags_obj.enable_tensorboard params["enable_metrics_in_training"] = flags_obj.enable_metrics_in_training params["steps_between_evals"] = flags_obj.steps_between_evals params["enable_checkpointing"] = flags_obj.enable_checkpointing self.distribution_strategy = distribution_utils.get_distribution_strategy( distribution_strategy=flags_obj.distribution_strategy, num_gpus=num_gpus, all_reduce_alg=flags_obj.all_reduce_alg, num_packs=flags_obj.num_packs, tpu_address=flags_obj.tpu or "") if self.use_tpu: params["num_replicas"] = self.distribution_strategy.num_replicas_in_sync if not params["static_batch"]: raise ValueError("TPU requires static batch for input data.") else: logging.info("Running transformer with num_gpus = %d", num_gpus) if self.distribution_strategy: logging.info("For training, using distribution strategy: %s", self.distribution_strategy) else: logging.info("Not using any distribution strategy.") performance.set_mixed_precision_policy( params["dtype"], flags_core.get_loss_scale(flags_obj, default_for_fp16="dynamic")) @property def use_tpu(self): if self.distribution_strategy: return isinstance(self.distribution_strategy, tf.distribute.experimental.TPUStrategy) return False def train(self): """Trains the model.""" params = self.params flags_obj = self.flags_obj # Sets config options. keras_utils.set_session_config(enable_xla=flags_obj.enable_xla) _ensure_dir(flags_obj.model_dir) with distribution_utils.get_strategy_scope(self.distribution_strategy): model = transformer.create_model(params, is_train=True) opt = self._create_optimizer() current_step = 0 checkpoint = tf.train.Checkpoint(model=model, optimizer=opt) latest_checkpoint = tf.train.latest_checkpoint(flags_obj.model_dir) if latest_checkpoint: checkpoint.restore(latest_checkpoint) logging.info("Loaded checkpoint %s", latest_checkpoint) current_step = opt.iterations.numpy() if params["use_ctl"]: train_loss_metric = tf.keras.metrics.Mean( "training_loss", dtype=tf.float32) if params["enable_tensorboard"]: summary_writer = tf.compat.v2.summary.create_file_writer( flags_obj.model_dir) else: summary_writer = tf.compat.v2.summary.create_noop_writer() train_metrics = [train_loss_metric] if params["enable_metrics_in_training"]: train_metrics = train_metrics + model.metrics else: model.compile(opt) model.summary() if self.use_tpu: # Different from experimental_distribute_dataset, # experimental_distribute_datasets_from_function requires # per-replica/local batch size. params["batch_size"] /= self.distribution_strategy.num_replicas_in_sync train_ds = ( self.distribution_strategy .experimental_distribute_datasets_from_function( lambda ctx: data_pipeline.train_input_fn(params, ctx))) else: train_ds = data_pipeline.train_input_fn(params) map_data_fn = data_pipeline.map_data_for_transformer_fn train_ds = train_ds.map( map_data_fn, num_parallel_calls=params["num_parallel_calls"]) if params["use_ctl"]: train_ds_iterator = iter(train_ds) callbacks = self._create_callbacks(flags_obj.model_dir, 0, params) # Only TimeHistory callback is supported for CTL if params["use_ctl"]: callbacks = [cb for cb in callbacks if isinstance(cb, keras_utils.TimeHistory)] # TODO(b/139418525): Refactor the custom training loop logic. @tf.function def train_steps(iterator, steps): """Training steps function for TPU runs. Args: iterator: The input iterator of the training dataset. steps: An integer, the number of training steps. Returns: A float, the loss value. """ def _step_fn(inputs): """Per-replica step function.""" inputs, targets = inputs with tf.GradientTape() as tape: logits = model([inputs, targets], training=True) loss = metrics.transformer_loss(logits, targets, params["label_smoothing"], params["vocab_size"]) # Scales the loss, which results in using the average loss across all # of the replicas for backprop. scaled_loss = loss / self.distribution_strategy.num_replicas_in_sync # De-dupes variables due to keras tracking issues. tvars = list({id(v): v for v in model.trainable_variables}.values()) grads = tape.gradient(scaled_loss, tvars) opt.apply_gradients(zip(grads, tvars)) # For reporting, the metric takes the mean of losses. train_loss_metric.update_state(loss) for _ in tf.range(steps): train_loss_metric.reset_states() self.distribution_strategy.run( _step_fn, args=(next(iterator),)) cased_score, uncased_score = None, None cased_score_history, uncased_score_history = [], [] while current_step < flags_obj.train_steps: remaining_steps = flags_obj.train_steps - current_step train_steps_per_eval = ( remaining_steps if remaining_steps < flags_obj.steps_between_evals else flags_obj.steps_between_evals) current_iteration = current_step // flags_obj.steps_between_evals logging.info( "Start train iteration at global step:{}".format(current_step)) history = None if params["use_ctl"]: if not self.use_tpu: raise NotImplementedError( "Custom training loop on GPUs is not implemented.") # Runs training steps. with summary_writer.as_default(): for cb in callbacks: cb.on_epoch_begin(current_iteration) cb.on_batch_begin(0) train_steps( train_ds_iterator, tf.convert_to_tensor(train_steps_per_eval, dtype=tf.int32)) current_step += train_steps_per_eval train_loss = train_loss_metric.result().numpy().astype(float) logging.info("Train Step: %d/%d / loss = %s", current_step, flags_obj.train_steps, train_loss) for cb in callbacks: cb.on_batch_end(train_steps_per_eval - 1) cb.on_epoch_end(current_iteration) if params["enable_tensorboard"]: for metric_obj in train_metrics: tf.compat.v2.summary.scalar(metric_obj.name, metric_obj.result(), current_step) summary_writer.flush() for cb in callbacks: cb.on_train_end() if flags_obj.enable_checkpointing: # avoid check-pointing when running for benchmarking. checkpoint_name = checkpoint.save( os.path.join(flags_obj.model_dir, "ctl_step_{}.ckpt".format(current_step))) logging.info("Saved checkpoint to %s", checkpoint_name) else: if self.use_tpu: raise NotImplementedError( "Keras model.fit on TPUs is not implemented.") history = model.fit( train_ds, initial_epoch=current_iteration, epochs=current_iteration + 1, steps_per_epoch=train_steps_per_eval, callbacks=callbacks, # If TimeHistory is enabled, progress bar would be messy. Increase # the verbose level to get rid of it. verbose=(2 if flags_obj.enable_time_history else 1)) current_step += train_steps_per_eval logging.info("Train history: {}".format(history.history)) logging.info("End train iteration at global step:{}".format(current_step)) if (flags_obj.bleu_source and flags_obj.bleu_ref): uncased_score, cased_score = self.eval() cased_score_history.append([current_iteration + 1, cased_score]) uncased_score_history.append([current_iteration + 1, uncased_score]) stats = ({ "loss": train_loss } if history is None else misc.build_stats(history, callbacks)) if uncased_score and cased_score: stats["bleu_uncased"] = uncased_score stats["bleu_cased"] = cased_score stats["bleu_uncased_history"] = uncased_score_history stats["bleu_cased_history"] = cased_score_history return stats def eval(self): """Evaluates the model.""" distribution_strategy = self.distribution_strategy if self.use_tpu else None # We only want to create the model under DS scope for TPU case. # When 'distribution_strategy' is None, a no-op DummyContextManager will # be used. with distribution_utils.get_strategy_scope(distribution_strategy): if not self.predict_model: self.predict_model = transformer.create_model(self.params, False) self._load_weights_if_possible( self.predict_model, tf.train.latest_checkpoint(self.flags_obj.model_dir)) self.predict_model.summary() return evaluate_and_log_bleu( self.predict_model, self.params, self.flags_obj.bleu_source, self.flags_obj.bleu_ref, self.flags_obj.vocab_file, distribution_strategy) def predict(self): """Predicts result from the model.""" params = self.params flags_obj = self.flags_obj with tf.name_scope("model"): model = transformer.create_model(params, is_train=False) self._load_weights_if_possible( model, tf.train.latest_checkpoint(self.flags_obj.model_dir)) model.summary() subtokenizer = tokenizer.Subtokenizer(flags_obj.vocab_file) ds = data_pipeline.eval_input_fn(params) ds = ds.map(lambda x, y: x).take(_SINGLE_SAMPLE) ret = model.predict(ds) val_outputs, _ = ret length = len(val_outputs) for i in range(length): translate.translate_from_input(val_outputs[i], subtokenizer) def _create_callbacks(self, cur_log_dir, init_steps, params): """Creates a list of callbacks.""" sfunc = optimizer.LearningRateFn(params["learning_rate"], params["hidden_size"], params["learning_rate_warmup_steps"]) scheduler_callback = optimizer.LearningRateScheduler(sfunc, init_steps) callbacks = misc.get_callbacks(params["steps_between_evals"]) callbacks.append(scheduler_callback) if params["enable_checkpointing"]: ckpt_full_path = os.path.join(cur_log_dir, "cp-{epoch:04d}.ckpt") callbacks.append( tf.keras.callbacks.ModelCheckpoint( ckpt_full_path, save_weights_only=True)) return callbacks def _load_weights_if_possible(self, model, init_weight_path=None): """Loads model weights when it is provided.""" if init_weight_path: logging.info("Load weights: {}".format(init_weight_path)) # TODO(b/139414977): Having the same variable restoring method for both # TPU and GPU. if self.use_tpu: checkpoint = tf.train.Checkpoint( model=model, optimizer=self._create_optimizer()) checkpoint.restore(init_weight_path) else: model.load_weights(init_weight_path) else: logging.info("Weights not loaded from path:{}".format(init_weight_path)) def _create_optimizer(self): """Creates optimizer.""" params = self.params lr_schedule = optimizer.LearningRateSchedule( params["learning_rate"], params["hidden_size"], params["learning_rate_warmup_steps"]) opt = tf.keras.optimizers.Adam( lr_schedule if self.use_tpu else params["learning_rate"], params["optimizer_adam_beta1"], params["optimizer_adam_beta2"], epsilon=params["optimizer_adam_epsilon"]) opt = performance.configure_optimizer( opt, use_float16=params["dtype"] == tf.float16, use_graph_rewrite=self.flags_obj.fp16_implementation == "graph_rewrite", loss_scale=flags_core.get_loss_scale( self.flags_obj, default_for_fp16="dynamic")) return opt def _ensure_dir(log_dir): """Makes log dir if not existed.""" if not tf.io.gfile.exists(log_dir): tf.io.gfile.makedirs(log_dir) def main(_): flags_obj = flags.FLAGS with logger.benchmark_context(flags_obj): task = TransformerTask(flags_obj) # Execute flag override logic for better model performance if flags_obj.tf_gpu_thread_mode: keras_utils.set_gpu_thread_mode_and_count( per_gpu_thread_count=flags_obj.per_gpu_thread_count, gpu_thread_mode=flags_obj.tf_gpu_thread_mode, num_gpus=flags_obj.num_gpus, datasets_num_private_threads=flags_obj.datasets_num_private_threads) if flags_obj.mode == "train": task.train() elif flags_obj.mode == "predict": task.predict() elif flags_obj.mode == "eval": task.eval() else: raise ValueError("Invalid mode {}".format(flags_obj.mode)) if __name__ == "__main__": logging.set_verbosity(logging.INFO) misc.define_transformer_flags() app.run(main)
38.457831
80
0.688753
from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import tempfile from absl import app from absl import flags from absl import logging import tensorflow as tf from official.modeling import performance from official.nlp.transformer import compute_bleu from official.nlp.transformer import data_pipeline from official.nlp.transformer import metrics from official.nlp.transformer import misc from official.nlp.transformer import optimizer from official.nlp.transformer import transformer from official.nlp.transformer import translate from official.nlp.transformer.utils import tokenizer from official.utils.flags import core as flags_core from official.utils.logs import logger from official.utils.misc import distribution_utils from official.utils.misc import keras_utils INF = int(1e9) BLEU_DIR = "bleu" _SINGLE_SAMPLE = 1 def translate_and_compute_bleu(model, params, subtokenizer, bleu_source, bleu_ref, distribution_strategy=None): tmp = tempfile.NamedTemporaryFile(delete=False) tmp_filename = tmp.name translate.translate_file( model, params, subtokenizer, bleu_source, output_file=tmp_filename, print_all_translations=False, distribution_strategy=distribution_strategy) uncased_score = compute_bleu.bleu_wrapper(bleu_ref, tmp_filename, False) cased_score = compute_bleu.bleu_wrapper(bleu_ref, tmp_filename, True) os.remove(tmp_filename) return uncased_score, cased_score def evaluate_and_log_bleu(model, params, bleu_source, bleu_ref, vocab_file, distribution_strategy=None): subtokenizer = tokenizer.Subtokenizer(vocab_file) uncased_score, cased_score = translate_and_compute_bleu( model, params, subtokenizer, bleu_source, bleu_ref, distribution_strategy) logging.info("Bleu score (uncased): %s", uncased_score) logging.info("Bleu score (cased): %s", cased_score) return uncased_score, cased_score class TransformerTask(object): def __init__(self, flags_obj): self.flags_obj = flags_obj self.predict_model = None num_gpus = flags_core.get_num_gpus(flags_obj) self.params = params = misc.get_model_params(flags_obj.param_set, num_gpus) params["num_gpus"] = num_gpus params["use_ctl"] = flags_obj.use_ctl params["data_dir"] = flags_obj.data_dir params["model_dir"] = flags_obj.model_dir params["static_batch"] = flags_obj.static_batch params["max_length"] = flags_obj.max_length params["decode_batch_size"] = flags_obj.decode_batch_size params["decode_max_length"] = flags_obj.decode_max_length params["padded_decode"] = flags_obj.padded_decode params["num_parallel_calls"] = ( flags_obj.num_parallel_calls or tf.data.experimental.AUTOTUNE) params["use_synthetic_data"] = flags_obj.use_synthetic_data params["batch_size"] = flags_obj.batch_size or params["default_batch_size"] params["repeat_dataset"] = None params["dtype"] = flags_core.get_tf_dtype(flags_obj) params["enable_tensorboard"] = flags_obj.enable_tensorboard params["enable_metrics_in_training"] = flags_obj.enable_metrics_in_training params["steps_between_evals"] = flags_obj.steps_between_evals params["enable_checkpointing"] = flags_obj.enable_checkpointing self.distribution_strategy = distribution_utils.get_distribution_strategy( distribution_strategy=flags_obj.distribution_strategy, num_gpus=num_gpus, all_reduce_alg=flags_obj.all_reduce_alg, num_packs=flags_obj.num_packs, tpu_address=flags_obj.tpu or "") if self.use_tpu: params["num_replicas"] = self.distribution_strategy.num_replicas_in_sync if not params["static_batch"]: raise ValueError("TPU requires static batch for input data.") else: logging.info("Running transformer with num_gpus = %d", num_gpus) if self.distribution_strategy: logging.info("For training, using distribution strategy: %s", self.distribution_strategy) else: logging.info("Not using any distribution strategy.") performance.set_mixed_precision_policy( params["dtype"], flags_core.get_loss_scale(flags_obj, default_for_fp16="dynamic")) @property def use_tpu(self): if self.distribution_strategy: return isinstance(self.distribution_strategy, tf.distribute.experimental.TPUStrategy) return False def train(self): params = self.params flags_obj = self.flags_obj keras_utils.set_session_config(enable_xla=flags_obj.enable_xla) _ensure_dir(flags_obj.model_dir) with distribution_utils.get_strategy_scope(self.distribution_strategy): model = transformer.create_model(params, is_train=True) opt = self._create_optimizer() current_step = 0 checkpoint = tf.train.Checkpoint(model=model, optimizer=opt) latest_checkpoint = tf.train.latest_checkpoint(flags_obj.model_dir) if latest_checkpoint: checkpoint.restore(latest_checkpoint) logging.info("Loaded checkpoint %s", latest_checkpoint) current_step = opt.iterations.numpy() if params["use_ctl"]: train_loss_metric = tf.keras.metrics.Mean( "training_loss", dtype=tf.float32) if params["enable_tensorboard"]: summary_writer = tf.compat.v2.summary.create_file_writer( flags_obj.model_dir) else: summary_writer = tf.compat.v2.summary.create_noop_writer() train_metrics = [train_loss_metric] if params["enable_metrics_in_training"]: train_metrics = train_metrics + model.metrics else: model.compile(opt) model.summary() if self.use_tpu: params["batch_size"] /= self.distribution_strategy.num_replicas_in_sync train_ds = ( self.distribution_strategy .experimental_distribute_datasets_from_function( lambda ctx: data_pipeline.train_input_fn(params, ctx))) else: train_ds = data_pipeline.train_input_fn(params) map_data_fn = data_pipeline.map_data_for_transformer_fn train_ds = train_ds.map( map_data_fn, num_parallel_calls=params["num_parallel_calls"]) if params["use_ctl"]: train_ds_iterator = iter(train_ds) callbacks = self._create_callbacks(flags_obj.model_dir, 0, params) if params["use_ctl"]: callbacks = [cb for cb in callbacks if isinstance(cb, keras_utils.TimeHistory)] @tf.function def train_steps(iterator, steps): def _step_fn(inputs): inputs, targets = inputs with tf.GradientTape() as tape: logits = model([inputs, targets], training=True) loss = metrics.transformer_loss(logits, targets, params["label_smoothing"], params["vocab_size"]) scaled_loss = loss / self.distribution_strategy.num_replicas_in_sync tvars = list({id(v): v for v in model.trainable_variables}.values()) grads = tape.gradient(scaled_loss, tvars) opt.apply_gradients(zip(grads, tvars)) train_loss_metric.update_state(loss) for _ in tf.range(steps): train_loss_metric.reset_states() self.distribution_strategy.run( _step_fn, args=(next(iterator),)) cased_score, uncased_score = None, None cased_score_history, uncased_score_history = [], [] while current_step < flags_obj.train_steps: remaining_steps = flags_obj.train_steps - current_step train_steps_per_eval = ( remaining_steps if remaining_steps < flags_obj.steps_between_evals else flags_obj.steps_between_evals) current_iteration = current_step // flags_obj.steps_between_evals logging.info( "Start train iteration at global step:{}".format(current_step)) history = None if params["use_ctl"]: if not self.use_tpu: raise NotImplementedError( "Custom training loop on GPUs is not implemented.") with summary_writer.as_default(): for cb in callbacks: cb.on_epoch_begin(current_iteration) cb.on_batch_begin(0) train_steps( train_ds_iterator, tf.convert_to_tensor(train_steps_per_eval, dtype=tf.int32)) current_step += train_steps_per_eval train_loss = train_loss_metric.result().numpy().astype(float) logging.info("Train Step: %d/%d / loss = %s", current_step, flags_obj.train_steps, train_loss) for cb in callbacks: cb.on_batch_end(train_steps_per_eval - 1) cb.on_epoch_end(current_iteration) if params["enable_tensorboard"]: for metric_obj in train_metrics: tf.compat.v2.summary.scalar(metric_obj.name, metric_obj.result(), current_step) summary_writer.flush() for cb in callbacks: cb.on_train_end() if flags_obj.enable_checkpointing: checkpoint_name = checkpoint.save( os.path.join(flags_obj.model_dir, "ctl_step_{}.ckpt".format(current_step))) logging.info("Saved checkpoint to %s", checkpoint_name) else: if self.use_tpu: raise NotImplementedError( "Keras model.fit on TPUs is not implemented.") history = model.fit( train_ds, initial_epoch=current_iteration, epochs=current_iteration + 1, steps_per_epoch=train_steps_per_eval, callbacks=callbacks, verbose=(2 if flags_obj.enable_time_history else 1)) current_step += train_steps_per_eval logging.info("Train history: {}".format(history.history)) logging.info("End train iteration at global step:{}".format(current_step)) if (flags_obj.bleu_source and flags_obj.bleu_ref): uncased_score, cased_score = self.eval() cased_score_history.append([current_iteration + 1, cased_score]) uncased_score_history.append([current_iteration + 1, uncased_score]) stats = ({ "loss": train_loss } if history is None else misc.build_stats(history, callbacks)) if uncased_score and cased_score: stats["bleu_uncased"] = uncased_score stats["bleu_cased"] = cased_score stats["bleu_uncased_history"] = uncased_score_history stats["bleu_cased_history"] = cased_score_history return stats def eval(self): distribution_strategy = self.distribution_strategy if self.use_tpu else None with distribution_utils.get_strategy_scope(distribution_strategy): if not self.predict_model: self.predict_model = transformer.create_model(self.params, False) self._load_weights_if_possible( self.predict_model, tf.train.latest_checkpoint(self.flags_obj.model_dir)) self.predict_model.summary() return evaluate_and_log_bleu( self.predict_model, self.params, self.flags_obj.bleu_source, self.flags_obj.bleu_ref, self.flags_obj.vocab_file, distribution_strategy) def predict(self): params = self.params flags_obj = self.flags_obj with tf.name_scope("model"): model = transformer.create_model(params, is_train=False) self._load_weights_if_possible( model, tf.train.latest_checkpoint(self.flags_obj.model_dir)) model.summary() subtokenizer = tokenizer.Subtokenizer(flags_obj.vocab_file) ds = data_pipeline.eval_input_fn(params) ds = ds.map(lambda x, y: x).take(_SINGLE_SAMPLE) ret = model.predict(ds) val_outputs, _ = ret length = len(val_outputs) for i in range(length): translate.translate_from_input(val_outputs[i], subtokenizer) def _create_callbacks(self, cur_log_dir, init_steps, params): sfunc = optimizer.LearningRateFn(params["learning_rate"], params["hidden_size"], params["learning_rate_warmup_steps"]) scheduler_callback = optimizer.LearningRateScheduler(sfunc, init_steps) callbacks = misc.get_callbacks(params["steps_between_evals"]) callbacks.append(scheduler_callback) if params["enable_checkpointing"]: ckpt_full_path = os.path.join(cur_log_dir, "cp-{epoch:04d}.ckpt") callbacks.append( tf.keras.callbacks.ModelCheckpoint( ckpt_full_path, save_weights_only=True)) return callbacks def _load_weights_if_possible(self, model, init_weight_path=None): if init_weight_path: logging.info("Load weights: {}".format(init_weight_path)) if self.use_tpu: checkpoint = tf.train.Checkpoint( model=model, optimizer=self._create_optimizer()) checkpoint.restore(init_weight_path) else: model.load_weights(init_weight_path) else: logging.info("Weights not loaded from path:{}".format(init_weight_path)) def _create_optimizer(self): params = self.params lr_schedule = optimizer.LearningRateSchedule( params["learning_rate"], params["hidden_size"], params["learning_rate_warmup_steps"]) opt = tf.keras.optimizers.Adam( lr_schedule if self.use_tpu else params["learning_rate"], params["optimizer_adam_beta1"], params["optimizer_adam_beta2"], epsilon=params["optimizer_adam_epsilon"]) opt = performance.configure_optimizer( opt, use_float16=params["dtype"] == tf.float16, use_graph_rewrite=self.flags_obj.fp16_implementation == "graph_rewrite", loss_scale=flags_core.get_loss_scale( self.flags_obj, default_for_fp16="dynamic")) return opt def _ensure_dir(log_dir): if not tf.io.gfile.exists(log_dir): tf.io.gfile.makedirs(log_dir) def main(_): flags_obj = flags.FLAGS with logger.benchmark_context(flags_obj): task = TransformerTask(flags_obj) if flags_obj.tf_gpu_thread_mode: keras_utils.set_gpu_thread_mode_and_count( per_gpu_thread_count=flags_obj.per_gpu_thread_count, gpu_thread_mode=flags_obj.tf_gpu_thread_mode, num_gpus=flags_obj.num_gpus, datasets_num_private_threads=flags_obj.datasets_num_private_threads) if flags_obj.mode == "train": task.train() elif flags_obj.mode == "predict": task.predict() elif flags_obj.mode == "eval": task.eval() else: raise ValueError("Invalid mode {}".format(flags_obj.mode)) if __name__ == "__main__": logging.set_verbosity(logging.INFO) misc.define_transformer_flags() app.run(main)
true
true
f72cbea6b5b5fb4a9f0c9efd4d8092605bb087d6
18,884
py
Python
src/sentry/models/dsymfile.py
percipient/sentry
84c6f75ab40e12677c81d9210c3fe8ad66d7a0c3
[ "BSD-3-Clause" ]
null
null
null
src/sentry/models/dsymfile.py
percipient/sentry
84c6f75ab40e12677c81d9210c3fe8ad66d7a0c3
[ "BSD-3-Clause" ]
8
2019-12-28T23:49:55.000Z
2022-03-02T04:34:18.000Z
src/sentry/models/dsymfile.py
percipient/sentry
84c6f75ab40e12677c81d9210c3fe8ad66d7a0c3
[ "BSD-3-Clause" ]
null
null
null
""" sentry.models.dsymfile ~~~~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2010-2016 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from __future__ import absolute_import import os import shutil import hashlib import six import tempfile from requests.exceptions import RequestException from jsonfield import JSONField from itertools import chain from django.db import models, router, transaction, connection, IntegrityError from django.utils import timezone from django.utils.translation import ugettext_lazy as _ from symsynd.macho.arch import get_macho_uuids from sentry.db.models import FlexibleForeignKey, Model, BoundedBigIntegerField, \ sane_repr, BaseManager, BoundedPositiveIntegerField from sentry.models.file import File from sentry.utils.zip import safe_extract_zip from sentry.utils.db import is_sqlite from sentry.utils.native import parse_addr from sentry.constants import KNOWN_DSYM_TYPES from sentry.reprocessing import resolve_processing_issue class VersionDSymFile(Model): __core__ = False objects = BaseManager() dsym_file = FlexibleForeignKey('sentry.ProjectDSymFile', null=True) dsym_app = FlexibleForeignKey('sentry.DSymApp') version = models.CharField(max_length=32) build = models.CharField(max_length=32, null=True) date_added = models.DateTimeField(default=timezone.now) class Meta: app_label = 'sentry' db_table = 'sentry_versiondsymfile' unique_together = (('dsym_file', 'version', 'build'),) # TODO(dcramer): pull in enum library class DSymPlatform(object): GENERIC = 0 APPLE = 1 ANDROID = 2 DSYM_PLATFORMS = { 'generic': DSymPlatform.GENERIC, 'apple': DSymPlatform.APPLE, 'android': DSymPlatform.ANDROID, } def _auto_enrich_data(data, app_id, platform): # If we don't have an icon URL we can try to fetch one from iTunes if 'icon_url' not in data and platform == DSymPlatform.APPLE: from sentry.http import safe_urlopen try: rv = safe_urlopen('http://itunes.apple.com/lookup', params={ 'bundleId': app_id, }) except RequestException: pass else: if rv.ok: rv = rv.json() if rv.get('results'): data['icon_url'] = rv['results'][0]['artworkUrl512'] class DSymAppManager(BaseManager): def create_or_update_app(self, sync_id, app_id, project, data=None, platform=DSymPlatform.GENERIC): if data is None: data = {} _auto_enrich_data(data, app_id, platform) existing_app = DSymApp.objects.filter( app_id=app_id, project=project).first() if existing_app is not None: now = timezone.now() existing_app.update( sync_id=sync_id, data=data, last_synced=now, ) return existing_app return BaseManager.create(self, sync_id=sync_id, app_id=app_id, data=data, project=project, platform=platform ) class DSymApp(Model): __core__ = False objects = DSymAppManager() project = FlexibleForeignKey('sentry.Project') app_id = models.CharField(max_length=64) sync_id = models.CharField(max_length=64, null=True) data = JSONField() platform = BoundedPositiveIntegerField(default=0, choices=( (DSymPlatform.GENERIC, _('Generic')), (DSymPlatform.APPLE, _('Apple')), (DSymPlatform.ANDROID, _('Android')), )) last_synced = models.DateTimeField(default=timezone.now) date_added = models.DateTimeField(default=timezone.now) class Meta: app_label = 'sentry' db_table = 'sentry_dsymapp' unique_together = (('project', 'platform', 'app_id'),) class DSymSDKManager(BaseManager): def enumerate_sdks(self, sdk=None, version=None): """Return a grouped list of SDKs.""" filter = '' args = [] if version is not None: for col, val in zip(['major', 'minor', 'patchlevel'], version.split('.')): if not val.isdigit(): return [] filter += ' and k.version_%s = %d' % ( col, int(val) ) if sdk is not None: filter += ' and k.sdk_name = %s' args.append(sdk) cur = connection.cursor() cur.execute(''' select distinct k.*, count(*) as bundle_count, o.cpu_name from sentry_dsymsdk k, sentry_dsymbundle b, sentry_dsymobject o where b.sdk_id = k.id and b.object_id = o.id %s group by k.id, k.sdk_name, o.cpu_name ''' % filter, args) rv = [] for row in cur.fetchall(): row = dict(zip([x[0] for x in cur.description], row)) ver = '%s.%s.%s' % ( row['version_major'], row['version_minor'], row['version_patchlevel'] ) rv.append({ 'sdk_name': row['sdk_name'], 'version': ver, 'build': row['version_build'], 'bundle_count': row['bundle_count'], 'cpu_name': row['cpu_name'], }) return sorted(rv, key=lambda x: (x['sdk_name'], x['version'], x['build'], x['cpu_name'])) class DSymSDK(Model): __core__ = False dsym_type = models.CharField(max_length=20, db_index=True) sdk_name = models.CharField(max_length=20) version_major = models.IntegerField() version_minor = models.IntegerField() version_patchlevel = models.IntegerField() version_build = models.CharField(max_length=40) objects = DSymSDKManager() class Meta: app_label = 'sentry' db_table = 'sentry_dsymsdk' index_together = [ ('version_major', 'version_minor', 'version_patchlevel', 'version_build'), ] class DSymObject(Model): __core__ = False cpu_name = models.CharField(max_length=40) object_path = models.TextField(db_index=True) uuid = models.CharField(max_length=36, db_index=True) vmaddr = BoundedBigIntegerField(null=True) vmsize = BoundedBigIntegerField(null=True) class Meta: app_label = 'sentry' db_table = 'sentry_dsymobject' class DSymBundle(Model): __core__ = False sdk = FlexibleForeignKey('sentry.DSymSDK') object = FlexibleForeignKey('sentry.DSymObject') class Meta: app_label = 'sentry' db_table = 'sentry_dsymbundle' class DSymSymbolManager(BaseManager): def bulk_insert(self, items): db = router.db_for_write(DSymSymbol) items = list(items) if not items: return # On SQLite we don't do this. Two reasons: one, it does not # seem significantly faster and you're an idiot if you import # huge amounts of system symbols into sqlite anyways. secondly # because of the low parameter limit if not is_sqlite(): try: with transaction.atomic(using=db): cur = connection.cursor() cur.execute(''' insert into sentry_dsymsymbol (object_id, address, symbol) values %s ''' % ', '.join(['(%s, %s, %s)'] * len(items)), list(chain(*items))) cur.close() return except IntegrityError: pass cur = connection.cursor() for item in items: cur.execute(''' insert into sentry_dsymsymbol (object_id, address, symbol) select %(object_id)s, %(address)s, %(symbol)s where not exists ( select 1 from sentry_dsymsymbol where object_id = %(object_id)s and address = %(address)s); ''', { 'object_id': item[0], 'address': item[1], 'symbol': item[2], }) cur.close() def lookup_symbol(self, instruction_addr, image_addr, uuid, cpu_name=None, object_path=None, sdk_info=None, image_vmaddr=None): """Finds a system symbol.""" # If we use the "none" dsym type we never return a symbol here. if sdk_info is not None and sdk_info['dsym_type'] == 'none': return instruction_addr = parse_addr(instruction_addr) image_addr = parse_addr(image_addr) addr_abs = None if image_vmaddr is not None: image_vmaddr = parse_addr(image_vmaddr) addr_abs = image_vmaddr + instruction_addr - image_addr addr_rel = instruction_addr - image_addr uuid = six.text_type(uuid).lower() cur = connection.cursor() try: # First try: exact match on uuid (addr_rel) cur.execute(''' select s.symbol from sentry_dsymsymbol s, sentry_dsymobject o where o.uuid = %s and s.object_id = o.id and s.address <= o.vmaddr + %s and s.address >= o.vmaddr order by address desc limit 1; ''', [uuid, addr_rel]) rv = cur.fetchone() if rv: return rv[0] # Second try: exact match on uuid (addr_abs) if addr_abs is not None: cur.execute(''' select s.symbol from sentry_dsymsymbol s, sentry_dsymobject o where o.uuid = %s and s.object_id = o.id and s.address <= %s and s.address >= %s order by address desc limit 1; ''', [uuid, addr_abs, image_vmaddr]) rv = cur.fetchone() if rv: return rv[0] # Third try: exact match on path and arch (addr_rel) if sdk_info is None or \ cpu_name is None or \ object_path is None: return cur.execute(''' select s.symbol from sentry_dsymsymbol s, sentry_dsymobject o, sentry_dsymsdk k, sentry_dsymbundle b where b.sdk_id = k.id and b.object_id = o.id and s.object_id = o.id and k.sdk_name = %s and k.dsym_type = %s and k.version_major = %s and k.version_minor = %s and k.version_patchlevel = %s and o.cpu_name = %s and o.object_path = %s and s.address <= o.vmaddr + %s and s.address >= o.vmaddr order by address desc limit 1; ''', [sdk_info['sdk_name'], sdk_info['dsym_type'], sdk_info['version_major'], sdk_info['version_minor'], sdk_info['version_patchlevel'], cpu_name, object_path, addr_rel]) rv = cur.fetchone() if rv: return rv[0] # Fourth try: exact match on path and arch (addr_abs) if addr_abs is not None: cur.execute(''' select s.symbol from sentry_dsymsymbol s, sentry_dsymobject o, sentry_dsymsdk k, sentry_dsymbundle b where b.sdk_id = k.id and b.object_id = o.id and s.object_id = o.id and k.sdk_name = %s and k.dsym_type = %s and k.version_major = %s and k.version_minor = %s and k.version_patchlevel = %s and o.cpu_name = %s and o.object_path = %s and s.address <= %s and s.address >= %s order by address desc limit 1; ''', [sdk_info['sdk_name'], sdk_info['dsym_type'], sdk_info['version_major'], sdk_info['version_minor'], sdk_info['version_patchlevel'], cpu_name, object_path, addr_abs, image_vmaddr]) rv = cur.fetchone() if rv: return rv[0] finally: cur.close() class DSymSymbol(Model): __core__ = False object = FlexibleForeignKey('sentry.DSymObject') address = BoundedBigIntegerField(db_index=True) symbol = models.TextField() objects = DSymSymbolManager() class Meta: app_label = 'sentry' db_table = 'sentry_dsymsymbol' unique_together = [ ('object', 'address'), ] class CommonDSymFile(Model): """ A single dsym file that is associated with a project. """ __core__ = False file = FlexibleForeignKey('sentry.File') object_name = models.TextField() cpu_name = models.CharField(max_length=40) __repr__ = sane_repr('object_name', 'cpu_name', 'uuid') class Meta: abstract = True app_label = 'sentry' @property def dsym_type(self): ct = self.file.headers.get('Content-Type').lower() return KNOWN_DSYM_TYPES.get(ct, 'unknown') class ProjectDSymFileManager(BaseManager): def find_missing(self, checksums, project): if not checksums: return[] checksums = [x.lower() for x in checksums] missing = set(checksums) found = ProjectDSymFile.objects.filter( file__checksum__in=checksums, project=project ).values('file__checksum') for values in found: missing.discard(values.values()[0]) return sorted(missing) def find_by_checksums(self, checksums, project): if not checksums: return [] checksums = [x.lower() for x in checksums] return ProjectDSymFile.objects.filter( file__checksum__in=checksums, project=project ) class ProjectDSymFile(CommonDSymFile): project = FlexibleForeignKey('sentry.Project', null=True) uuid = models.CharField(max_length=36) is_global = False objects = ProjectDSymFileManager() class Meta(CommonDSymFile.Meta): unique_together = (('project', 'uuid'),) db_table = 'sentry_projectdsymfile' class GlobalDSymFile(CommonDSymFile): uuid = models.CharField(max_length=36, unique=True) is_global = True class Meta(CommonDSymFile.Meta): db_table = 'sentry_globaldsymfile' def _create_macho_dsym_from_uuid(project, cpu_name, uuid, fileobj, object_name): """This creates a mach dsym file from the given uuid and open file object to a dsym file. This will not verify the uuid. Use `create_files_from_macho_zip` for doing everything. """ extra = {} if project is None: cls = GlobalDSymFile file_type = 'global.dsym' else: cls = ProjectDSymFile extra['project'] = project file_type = 'project.dsym' h = hashlib.sha1() while 1: chunk = fileobj.read(16384) if not chunk: break h.update(chunk) checksum = h.hexdigest() fileobj.seek(0, 0) try: rv = cls.objects.get(uuid=uuid, **extra) if rv.file.checksum == checksum: return rv except cls.DoesNotExist: pass else: # The checksum mismatches. In this case we delete the old object # and perform a re-upload. rv.delete() file = File.objects.create( name=uuid, type=file_type, headers={ 'Content-Type': 'application/x-mach-binary' }, ) file.putfile(fileobj) try: with transaction.atomic(): rv = cls.objects.create( file=file, uuid=uuid, cpu_name=cpu_name, object_name=object_name, **extra ) except IntegrityError: file.delete() rv = cls.objects.get(uuid=uuid, **extra) resolve_processing_issue( project=project, scope='native', object='dsym:%s' % uuid, ) return rv def create_files_from_macho_zip(fileobj, project=None): """Creates all missing dsym files from the given zip file. This returns a list of all files created. """ scratchpad = tempfile.mkdtemp() try: safe_extract_zip(fileobj, scratchpad) to_create = [] for dirpath, dirnames, filenames in os.walk(scratchpad): for fn in filenames: fn = os.path.join(dirpath, fn) try: uuids = get_macho_uuids(fn) except (IOError, ValueError): # Whatever was contained there, was probably not a # macho file. continue for cpu, uuid in uuids: to_create.append((cpu, uuid, fn)) rv = [] for cpu, uuid, filename in to_create: with open(filename, 'rb') as f: rv.append((_create_macho_dsym_from_uuid( project, cpu, uuid, f, os.path.basename(filename)))) return rv finally: shutil.rmtree(scratchpad) def find_dsym_file(project, image_uuid): """Finds a dsym file for the given uuid. Looks both within the project as well the global store. """ image_uuid = image_uuid.lower() try: return ProjectDSymFile.objects.filter( uuid=image_uuid, project=project ).select_related('file').get() except ProjectDSymFile.DoesNotExist: pass try: return GlobalDSymFile.objects.filter( uuid=image_uuid ).select_related('file').get() except GlobalDSymFile.DoesNotExist: return None
32.061121
81
0.54157
from __future__ import absolute_import import os import shutil import hashlib import six import tempfile from requests.exceptions import RequestException from jsonfield import JSONField from itertools import chain from django.db import models, router, transaction, connection, IntegrityError from django.utils import timezone from django.utils.translation import ugettext_lazy as _ from symsynd.macho.arch import get_macho_uuids from sentry.db.models import FlexibleForeignKey, Model, BoundedBigIntegerField, \ sane_repr, BaseManager, BoundedPositiveIntegerField from sentry.models.file import File from sentry.utils.zip import safe_extract_zip from sentry.utils.db import is_sqlite from sentry.utils.native import parse_addr from sentry.constants import KNOWN_DSYM_TYPES from sentry.reprocessing import resolve_processing_issue class VersionDSymFile(Model): __core__ = False objects = BaseManager() dsym_file = FlexibleForeignKey('sentry.ProjectDSymFile', null=True) dsym_app = FlexibleForeignKey('sentry.DSymApp') version = models.CharField(max_length=32) build = models.CharField(max_length=32, null=True) date_added = models.DateTimeField(default=timezone.now) class Meta: app_label = 'sentry' db_table = 'sentry_versiondsymfile' unique_together = (('dsym_file', 'version', 'build'),) class DSymPlatform(object): GENERIC = 0 APPLE = 1 ANDROID = 2 DSYM_PLATFORMS = { 'generic': DSymPlatform.GENERIC, 'apple': DSymPlatform.APPLE, 'android': DSymPlatform.ANDROID, } def _auto_enrich_data(data, app_id, platform): if 'icon_url' not in data and platform == DSymPlatform.APPLE: from sentry.http import safe_urlopen try: rv = safe_urlopen('http://itunes.apple.com/lookup', params={ 'bundleId': app_id, }) except RequestException: pass else: if rv.ok: rv = rv.json() if rv.get('results'): data['icon_url'] = rv['results'][0]['artworkUrl512'] class DSymAppManager(BaseManager): def create_or_update_app(self, sync_id, app_id, project, data=None, platform=DSymPlatform.GENERIC): if data is None: data = {} _auto_enrich_data(data, app_id, platform) existing_app = DSymApp.objects.filter( app_id=app_id, project=project).first() if existing_app is not None: now = timezone.now() existing_app.update( sync_id=sync_id, data=data, last_synced=now, ) return existing_app return BaseManager.create(self, sync_id=sync_id, app_id=app_id, data=data, project=project, platform=platform ) class DSymApp(Model): __core__ = False objects = DSymAppManager() project = FlexibleForeignKey('sentry.Project') app_id = models.CharField(max_length=64) sync_id = models.CharField(max_length=64, null=True) data = JSONField() platform = BoundedPositiveIntegerField(default=0, choices=( (DSymPlatform.GENERIC, _('Generic')), (DSymPlatform.APPLE, _('Apple')), (DSymPlatform.ANDROID, _('Android')), )) last_synced = models.DateTimeField(default=timezone.now) date_added = models.DateTimeField(default=timezone.now) class Meta: app_label = 'sentry' db_table = 'sentry_dsymapp' unique_together = (('project', 'platform', 'app_id'),) class DSymSDKManager(BaseManager): def enumerate_sdks(self, sdk=None, version=None): filter = '' args = [] if version is not None: for col, val in zip(['major', 'minor', 'patchlevel'], version.split('.')): if not val.isdigit(): return [] filter += ' and k.version_%s = %d' % ( col, int(val) ) if sdk is not None: filter += ' and k.sdk_name = %s' args.append(sdk) cur = connection.cursor() cur.execute(''' select distinct k.*, count(*) as bundle_count, o.cpu_name from sentry_dsymsdk k, sentry_dsymbundle b, sentry_dsymobject o where b.sdk_id = k.id and b.object_id = o.id %s group by k.id, k.sdk_name, o.cpu_name ''' % filter, args) rv = [] for row in cur.fetchall(): row = dict(zip([x[0] for x in cur.description], row)) ver = '%s.%s.%s' % ( row['version_major'], row['version_minor'], row['version_patchlevel'] ) rv.append({ 'sdk_name': row['sdk_name'], 'version': ver, 'build': row['version_build'], 'bundle_count': row['bundle_count'], 'cpu_name': row['cpu_name'], }) return sorted(rv, key=lambda x: (x['sdk_name'], x['version'], x['build'], x['cpu_name'])) class DSymSDK(Model): __core__ = False dsym_type = models.CharField(max_length=20, db_index=True) sdk_name = models.CharField(max_length=20) version_major = models.IntegerField() version_minor = models.IntegerField() version_patchlevel = models.IntegerField() version_build = models.CharField(max_length=40) objects = DSymSDKManager() class Meta: app_label = 'sentry' db_table = 'sentry_dsymsdk' index_together = [ ('version_major', 'version_minor', 'version_patchlevel', 'version_build'), ] class DSymObject(Model): __core__ = False cpu_name = models.CharField(max_length=40) object_path = models.TextField(db_index=True) uuid = models.CharField(max_length=36, db_index=True) vmaddr = BoundedBigIntegerField(null=True) vmsize = BoundedBigIntegerField(null=True) class Meta: app_label = 'sentry' db_table = 'sentry_dsymobject' class DSymBundle(Model): __core__ = False sdk = FlexibleForeignKey('sentry.DSymSDK') object = FlexibleForeignKey('sentry.DSymObject') class Meta: app_label = 'sentry' db_table = 'sentry_dsymbundle' class DSymSymbolManager(BaseManager): def bulk_insert(self, items): db = router.db_for_write(DSymSymbol) items = list(items) if not items: return # On SQLite we don't do this. Two reasons: one, it does not # huge amounts of system symbols into sqlite anyways. secondly # because of the low parameter limit if not is_sqlite(): try: with transaction.atomic(using=db): cur = connection.cursor() cur.execute(''' insert into sentry_dsymsymbol (object_id, address, symbol) values %s ''' % ', '.join(['(%s, %s, %s)'] * len(items)), list(chain(*items))) cur.close() return except IntegrityError: pass cur = connection.cursor() for item in items: cur.execute(''' insert into sentry_dsymsymbol (object_id, address, symbol) select %(object_id)s, %(address)s, %(symbol)s where not exists ( select 1 from sentry_dsymsymbol where object_id = %(object_id)s and address = %(address)s); ''', { 'object_id': item[0], 'address': item[1], 'symbol': item[2], }) cur.close() def lookup_symbol(self, instruction_addr, image_addr, uuid, cpu_name=None, object_path=None, sdk_info=None, image_vmaddr=None): # If we use the "none" dsym type we never return a symbol here. if sdk_info is not None and sdk_info['dsym_type'] == 'none': return instruction_addr = parse_addr(instruction_addr) image_addr = parse_addr(image_addr) addr_abs = None if image_vmaddr is not None: image_vmaddr = parse_addr(image_vmaddr) addr_abs = image_vmaddr + instruction_addr - image_addr addr_rel = instruction_addr - image_addr uuid = six.text_type(uuid).lower() cur = connection.cursor() try: # First try: exact match on uuid (addr_rel) cur.execute(''' select s.symbol from sentry_dsymsymbol s, sentry_dsymobject o where o.uuid = %s and s.object_id = o.id and s.address <= o.vmaddr + %s and s.address >= o.vmaddr order by address desc limit 1; ''', [uuid, addr_rel]) rv = cur.fetchone() if rv: return rv[0] # Second try: exact match on uuid (addr_abs) if addr_abs is not None: cur.execute(''' select s.symbol from sentry_dsymsymbol s, sentry_dsymobject o where o.uuid = %s and s.object_id = o.id and s.address <= %s and s.address >= %s order by address desc limit 1; ''', [uuid, addr_abs, image_vmaddr]) rv = cur.fetchone() if rv: return rv[0] # Third try: exact match on path and arch (addr_rel) if sdk_info is None or \ cpu_name is None or \ object_path is None: return cur.execute(''' select s.symbol from sentry_dsymsymbol s, sentry_dsymobject o, sentry_dsymsdk k, sentry_dsymbundle b where b.sdk_id = k.id and b.object_id = o.id and s.object_id = o.id and k.sdk_name = %s and k.dsym_type = %s and k.version_major = %s and k.version_minor = %s and k.version_patchlevel = %s and o.cpu_name = %s and o.object_path = %s and s.address <= o.vmaddr + %s and s.address >= o.vmaddr order by address desc limit 1; ''', [sdk_info['sdk_name'], sdk_info['dsym_type'], sdk_info['version_major'], sdk_info['version_minor'], sdk_info['version_patchlevel'], cpu_name, object_path, addr_rel]) rv = cur.fetchone() if rv: return rv[0] # Fourth try: exact match on path and arch (addr_abs) if addr_abs is not None: cur.execute(''' select s.symbol from sentry_dsymsymbol s, sentry_dsymobject o, sentry_dsymsdk k, sentry_dsymbundle b where b.sdk_id = k.id and b.object_id = o.id and s.object_id = o.id and k.sdk_name = %s and k.dsym_type = %s and k.version_major = %s and k.version_minor = %s and k.version_patchlevel = %s and o.cpu_name = %s and o.object_path = %s and s.address <= %s and s.address >= %s order by address desc limit 1; ''', [sdk_info['sdk_name'], sdk_info['dsym_type'], sdk_info['version_major'], sdk_info['version_minor'], sdk_info['version_patchlevel'], cpu_name, object_path, addr_abs, image_vmaddr]) rv = cur.fetchone() if rv: return rv[0] finally: cur.close() class DSymSymbol(Model): __core__ = False object = FlexibleForeignKey('sentry.DSymObject') address = BoundedBigIntegerField(db_index=True) symbol = models.TextField() objects = DSymSymbolManager() class Meta: app_label = 'sentry' db_table = 'sentry_dsymsymbol' unique_together = [ ('object', 'address'), ] class CommonDSymFile(Model): __core__ = False file = FlexibleForeignKey('sentry.File') object_name = models.TextField() cpu_name = models.CharField(max_length=40) __repr__ = sane_repr('object_name', 'cpu_name', 'uuid') class Meta: abstract = True app_label = 'sentry' @property def dsym_type(self): ct = self.file.headers.get('Content-Type').lower() return KNOWN_DSYM_TYPES.get(ct, 'unknown') class ProjectDSymFileManager(BaseManager): def find_missing(self, checksums, project): if not checksums: return[] checksums = [x.lower() for x in checksums] missing = set(checksums) found = ProjectDSymFile.objects.filter( file__checksum__in=checksums, project=project ).values('file__checksum') for values in found: missing.discard(values.values()[0]) return sorted(missing) def find_by_checksums(self, checksums, project): if not checksums: return [] checksums = [x.lower() for x in checksums] return ProjectDSymFile.objects.filter( file__checksum__in=checksums, project=project ) class ProjectDSymFile(CommonDSymFile): project = FlexibleForeignKey('sentry.Project', null=True) uuid = models.CharField(max_length=36) is_global = False objects = ProjectDSymFileManager() class Meta(CommonDSymFile.Meta): unique_together = (('project', 'uuid'),) db_table = 'sentry_projectdsymfile' class GlobalDSymFile(CommonDSymFile): uuid = models.CharField(max_length=36, unique=True) is_global = True class Meta(CommonDSymFile.Meta): db_table = 'sentry_globaldsymfile' def _create_macho_dsym_from_uuid(project, cpu_name, uuid, fileobj, object_name): extra = {} if project is None: cls = GlobalDSymFile file_type = 'global.dsym' else: cls = ProjectDSymFile extra['project'] = project file_type = 'project.dsym' h = hashlib.sha1() while 1: chunk = fileobj.read(16384) if not chunk: break h.update(chunk) checksum = h.hexdigest() fileobj.seek(0, 0) try: rv = cls.objects.get(uuid=uuid, **extra) if rv.file.checksum == checksum: return rv except cls.DoesNotExist: pass else: # The checksum mismatches. In this case we delete the old object # and perform a re-upload. rv.delete() file = File.objects.create( name=uuid, type=file_type, headers={ 'Content-Type': 'application/x-mach-binary' }, ) file.putfile(fileobj) try: with transaction.atomic(): rv = cls.objects.create( file=file, uuid=uuid, cpu_name=cpu_name, object_name=object_name, **extra ) except IntegrityError: file.delete() rv = cls.objects.get(uuid=uuid, **extra) resolve_processing_issue( project=project, scope='native', object='dsym:%s' % uuid, ) return rv def create_files_from_macho_zip(fileobj, project=None): scratchpad = tempfile.mkdtemp() try: safe_extract_zip(fileobj, scratchpad) to_create = [] for dirpath, dirnames, filenames in os.walk(scratchpad): for fn in filenames: fn = os.path.join(dirpath, fn) try: uuids = get_macho_uuids(fn) except (IOError, ValueError): # Whatever was contained there, was probably not a # macho file. continue for cpu, uuid in uuids: to_create.append((cpu, uuid, fn)) rv = [] for cpu, uuid, filename in to_create: with open(filename, 'rb') as f: rv.append((_create_macho_dsym_from_uuid( project, cpu, uuid, f, os.path.basename(filename)))) return rv finally: shutil.rmtree(scratchpad) def find_dsym_file(project, image_uuid): image_uuid = image_uuid.lower() try: return ProjectDSymFile.objects.filter( uuid=image_uuid, project=project ).select_related('file').get() except ProjectDSymFile.DoesNotExist: pass try: return GlobalDSymFile.objects.filter( uuid=image_uuid ).select_related('file').get() except GlobalDSymFile.DoesNotExist: return None
true
true
f72cbf17e64a21584865047b98978bd2193a31f9
53,060
py
Python
graphics/basic_plot_functions.py
JCSDA/mpas-jedi
e0780d1fd295912ee4cfb758854c52b6764d4ab9
[ "Apache-2.0" ]
2
2021-09-25T01:20:10.000Z
2021-12-17T18:44:53.000Z
graphics/basic_plot_functions.py
JCSDA/mpas-jedi
e0780d1fd295912ee4cfb758854c52b6764d4ab9
[ "Apache-2.0" ]
null
null
null
graphics/basic_plot_functions.py
JCSDA/mpas-jedi
e0780d1fd295912ee4cfb758854c52b6764d4ab9
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/env python3 from copy import deepcopy import cartopy.crs as ccrs import datetime as dt import logging from pandas.plotting import register_matplotlib_converters register_matplotlib_converters() import matplotlib matplotlib.use('AGG') import matplotlib.axes as maxes import matplotlib.cm as cm import matplotlib.colors as colors from matplotlib.colors import BoundaryNorm import matplotlib.pyplot as plt import matplotlib.ticker as mticker from mpl_toolkits.axes_grid1 import make_axes_locatable import numpy as np import plot_utils as pu import var_utils as vu import os _logger = logging.getLogger(__name__) cmGray = plt.cm.get_cmap("gist_gray") cmRainbow = plt.cm.get_cmap("gist_rainbow") cmSpectral = plt.cm.get_cmap("nipy_spectral") cmHeat = plt.cm.get_cmap("gist_heat") cmOcean = plt.cm.get_cmap("ocean") cmNCAR = plt.cm.get_cmap("gist_ncar") WhiteBlack1 = cmGray(np.linspace(1.0,0.0,17)) # white to black (-90 to -74 C) BlackRed = cmHeat(np.linspace(0.0,0.5,10)) #black to red (-74 to -65 C) ROYG = cmSpectral(np.linspace(0.9,0.43,27)) # red, orange, yellow, green, blue (-65 to -39 C) #GreenBlue = cmNCAR(np.linspace(0.05,0.1,8)) # green to blue (-39 to -32 C) #BlueCyan = cmRainbow(np.linspace(0.8,0.6,13)) # blue to cyan (-32 to -20 C) GreenBlueCyan = cmNCAR(np.linspace(0.05,0.2,20)) # green to blue (-39 to -20 C) #WhiteBlack2 = cmGray(np.linspace(0.9,0.0,51)) # white to black (-20 to 30 C) MVW = cmNCAR(np.linspace(0.8,0.98,21)) # magenta to violet to white (-20 to 0 C) WhiteBlack2 = cmGray(np.linspace(0.9,0.0,31)) # white to black (0 to 30 C) #btcolors = np.concatenate((WhiteBlack1, BlackRed, ROYG, GreenBlue, BlueCyan, WhiteBlack2)) #btcolors = np.concatenate((WhiteBlack1, BlackRed, ROYG, GreenBlueCyan, WhiteBlack2)) btcolors = np.concatenate((WhiteBlack1, BlackRed, ROYG, GreenBlueCyan, MVW, WhiteBlack2)) btCMap = colors.ListedColormap(btcolors) #This script includes basic plotting functions. distriZooms = {} #Full Earth distriZooms['default'] = { 'cLon': None, 'minLon': -180, 'maxLon': 180, 'minLat': -90, 'maxLat': 90, } distriZooms['abi'] = { 'cLon': -75.2, 'minLon': None, 'maxLon': None, 'minLat': None, 'maxLat': None, } distriZooms['ahi'] = { 'cLon': 140.7, 'minLon': None, 'maxLon': None, 'minLat': None, 'maxLat': None, } def plotDistri(lats,lons,values, \ ObsType,VarName,var_unit,out_name,nstation,levbin, \ dmin=None,dmax=None,dotsize=6,color="rainbow"): #================================================================ #INPUTS: # lats - latitude # lons - longitude # values - values will be plotted # ObsType - observation type # VarName - variable name # var_unit - variable units # out_name - will be included in output file name. It can be experiment name. # nstation - station numbers for sondes. # levbin - plot all levels together (levbin=all); or plot every level. # dmin, dmax - min/max values of colorbars, optional # dotsize - dot size, optional # color - color scheme, optional #================================================================ # For some plots that need to change longitude from [-180,180] to [0,360] # tmp = np.logical_not(lons > 0) # lons[tmp] = lons[tmp] + 360 #set map======================================================================= cLon = distriZooms['default']['cLon'] minLon = distriZooms['default']['minLon'] maxLon = distriZooms['default']['maxLon'] minLat = distriZooms['default']['minLat'] maxLat = distriZooms['default']['maxLat'] for key, val in distriZooms.items(): if key in ObsType: cLon = val['cLon'] minLon = val['minLon'] maxLon = val['maxLon'] minLat = val['minLat'] maxLat = val['maxLat'] if cLon is not None: fig = plt.figure(figsize=(5,5)) ax = fig.add_subplot(projection=ccrs.Orthographic(cLon)) else: fig = plt.figure(figsize=(8,8)) ax = fig.add_subplot(projection=ccrs.PlateCarree()) ax.set_global() #draw points onto map ========================================================= if color == "BT": if ("abi" in ObsType or "ahi" in ObsType): cm = btCMap if dmin is None: dmin = 183 if dmax is None: dmax = 303 else: cm = plt.cm.get_cmap("gist_ncar") if dmin is None: dmin = 190 if dmax is None: dmax = 270 else: cm = plt.cm.get_cmap(color) finite = np.isfinite(values) if ((("abi" in ObsType or "ahi" in ObsType) and finite.sum() > 4e4) or "model" in ObsType): # option 1: smoothed contours (note: color bar is not quite right) # sc=m.contourf(lons[finite], lats[finite], values[finite], # cm.N, cmap = cm, vmin = dmin, vmax = dmax, # latlon = True, tri = True, extend='both') # option 2: pixel contours # first sort by longitude to avoid bug for cyclic projections in basemap lonsPlot = lons[finite] lonsPlot[lonsPlot > 180.0] -= 360.0 # fixes latitude swap bug for cyclic projections latsPlot = lats[finite] valuesPlot = values[finite] lonSort = np.argsort(lonsPlot) p = plt.pcolor(lonsPlot[lonSort], latsPlot[lonSort], valuesPlot[lonSort], transform = ccrs.PlateCarree(), cmap = cm, vmin = dmin, vmax = dmax, latlon = True, tri = True) else: p=ax.scatter(lons[finite], lats[finite], c=values[finite], transform = ccrs.PlateCarree(), cmap= cm, s = dotsize) ax.gridlines(draw_labels=True, xlocs=np.arange(-180,180,60),linestyle='--') ax.coastlines() divider = make_axes_locatable(ax) cax = divider.append_axes("bottom",size="5%", pad=0.3,axes_class=plt.Axes) #fig.add_axes(cax) plt.colorbar(p,cax=cax,orientation='horizontal') #,cax=cax,ax=ax,orientation='horizontal') #set title =================================================================== if nstation == 0 or ObsType == 'satwind': plt.text(0.5, 1.15, '%s %s %s nlocs:%s' \ %(ObsType,VarName,var_unit,len(values[~np.isnan(values)])), \ horizontalalignment='center', \ fontsize=12, transform = ax.transAxes) else: if ObsType[:6] == 'gnssro': plt.text(0.5, 1.15, '%s %s %s nlocs:%s nprofile:%s' \ %(ObsType,VarName,var_unit,len(values[~np.isnan(values)]),nstation), \ horizontalalignment='center', \ fontsize=12, transform = ax.transAxes) elif ObsType == 'aircraft': plt.text(0.5, 1.15, '%s %s %s nlocs:%s nflight:%s' \ %(ObsType,VarName,var_unit,len(values[~np.isnan(values)]),nstation), \ horizontalalignment='center', \ fontsize=12, transform = ax.transAxes) else: plt.text(0.5, 1.15, '%s %s %s nlocs:%s nstation:%s' \ %(ObsType,VarName,var_unit,len(values[~np.isnan(values)]),nstation), \ horizontalalignment='center', \ fontsize=12, transform = ax.transAxes) plt.savefig('distri_%s_%s_%s.png'%(VarName,out_name,levbin),dpi=200,bbox_inches='tight') plt.close() def scatterMapFields( lonVals, latVals, fields, filename, minLon = -180., maxLon = 180., minLat = -90., maxLat = 90., cLon = None, projection = 'default', dmin = None, dmax = None, markers = {}, sizes = {}, cmap = 'gist_ncar', cbarType = None, c = {}, logVLim = 1.e-12, ): # setup map cLons = np.asarray([]) lonVals_180 = {} for name in lonVals.keys(): cLon = None # 0 < longitude <= 360 lonVals_360 = deepcopy(lonVals[name]) while np.max(lonVals_360) >= 360.0: lonVals_360[lonVals_360 >= 360.0] -= 360.0 while np.min(lonVals_360) < 0.0: lonVals_360[lonVals_360 < 0.0] += 360.0 # -180 < longitude <= 180 lonVals_180[name] = deepcopy(lonVals_360) lonVals_180[name][lonVals_180[name] > 180.0] -= 360.0 for lon in [lonVals_360, lonVals_180[name]]: if np.max(lon) - np.min(lon) <= 180.0: cLon = 0.5*(np.max(lon) + np.min(lon)) cLons = np.append(cLons, cLon) anycLonNone = np.any([c is None for c in cLons]) if anycLonNone: # plot entire Earth fig = plt.figure(figsize=(5,5)) ax = fig.add_subplot(projection=ccrs.Mollweide(0.0)) else: # plot single projected side of Earth cLon = cLons[0] if cLon > 180.0: cLon-=360.0 fig = plt.figure(figsize=(5,5)) ax = fig.add_subplot(projection=ccrs.Orthographic(cLon)) assert (cbarType is None or cbarType in ['Log', 'SymLog']), \ 'scatterMapFields: invalid cbarType: '+cbarType for name, field in fields.items(): f = c=c.get(name, field) finite = np.isfinite(f) lons = lonVals_180[name][finite] lats = latVals[name][finite] f = f[finite] ## transform to pcolormesh and cartopy conventions # longitude monotonically increasing lonSort = np.argsort(lons) lons = lons[lonSort] lats = lats[lonSort] f = f[lonSort] if dmin is None: vmin = f.min() else: vmin = dmin if dmax is None: vmax = f.max() else: vmax = dmax if cbarType is None: norm = None elif cbarType == 'Log': if vmin <= logVLim: vmin = logVLim f[f < vmin] = vmin norm=colors.LogNorm(vmin=vmin, vmax=vmax) elif cbarType == 'SymLog': norm=colors.SymLogNorm(vmin=vmin, vmax=vmax, linthresh=1.e-4*vmax, linscale=1.0, base=10) sc = ax.scatter(lons, lats, c=f, s = sizes.get(name, 1), cmap = cmap, norm = norm, marker = markers.get(name, '.'), linewidth = 0, transform=ccrs.PlateCarree(), ) # show full projection extent ax.set_global() # add coastlines ax.coastlines() divider = make_axes_locatable(ax) cax = divider.append_axes("bottom",size="5%", pad=0.3,axes_class=plt.Axes) cb = plt.colorbar(sc, cax=cax, orientation='horizontal') plt.savefig(filename, dpi=200, bbox_inches='tight') plt.close() def plotTimeserial2D(Stats,xlabeltime,ylevels,VarName): #================================================================ #INPUTS: # Stats - statistics # xlabeltime - time labels for x-axis # ylevels - vertical levels for y-axis # VarName - variable name #================================================================ zgrid = np.loadtxt("/glade/work/jban/pandac/fix_input/graphics/zgrid_v55.txt") fig, ax1 = plt.subplots() xarray = range(len(xlabeltime)) valuemin = np.amin(Stats) valuemax = np.amax(Stats) # yonggangyu introduce epsilon and xi for plotting absolutely zero field, # solving vmin, vcenter, vmax ascending order issue epsilon = 1.e-8 if (valuemin > 0 or valuemax < 0): color = 'rainbow' plt.contourf(xarray,ylevels,Stats,40,vmin=valuemin, vmax=valuemax,cmap=color) xi=-1 else: cmap = 'coolwarm' if ( -valuemin < epsilon and valuemax < epsilon ): xi=1 valuemin = -epsilon valuemax = epsilon elif ( -valuemin < epsilon and valuemax > epsilon ): xi=2 valuemin = -epsilon elif ( -valuemin > epsilon and valuemax < epsilon ): xi=3 valuemax = epsilon else: xi=4 #print('xi= '+str(xi)+' valuemin= ',str(valuemin)+' valuemax= ',str(valuemax)) norm = matplotlib.colors.DivergingNorm(vmin=valuemin, vcenter=0, vmax=valuemax) plt.contourf(xarray,ylevels,Stats,40,vmin=valuemin, vmax=valuemax,norm=norm,cmap=cmap) xarray = range(len(xlabeltime)) major_ticks = np.arange(0, 56, 5) ax1.set_yticks(major_ticks) ax1.set_ylim([0,54]) ax1.set_ylabel('Vertical level',fontsize=15) ax2 = ax1.twinx() ax2.set_yticks(major_ticks-1) ax2.set_yticklabels((zgrid[::5]).astype(int)) ax2.set_ylabel('Height (m)',fontsize=13) FCDay = ''.join(VarName.split("_")[1:][:-3]) if (FCDay == 'day0.0'): ax1.set_xlabel('Analysis Time',fontsize=15) ax1.set_xticks(xarray[::4]) ax1.set_xticklabels(xlabeltime[::4],rotation=90) elif (FCDay == 'day0.25'): ax1.set_xlabel( '6h Forecast',fontsize=15) ax1.set_xticks(xarray[::4]) ax1.set_xticklabels(xlabeltime[::4],rotation=90) else: ax1.set_xlabel( 'Lead Time',fontsize=15) plt.colorbar(extend='both',orientation="horizontal",pad=0.2) ax1.grid(True) region = ''.join(VarName.split("_")[2:][:-2]) var = ''.join(VarName.split("_")[3:][:-1]) stats = ''.join(VarName.split("_")[4:]) plt.title(stats+' variable:'+vu.varDictModel[var][1]+'('+ vu.varDictModel[var][0]+') '+region, fontsize = 12) plt.savefig(VarName+'_TS_2d.png',dpi=200,bbox_inches='tight') plt.close() maxLegendEntries = 12 ############################################################################### lenWarnSer = 0 nanWarnSer = 0 def plotSeries(fig, \ linesVals, xVals, \ linesLabel, \ title="", dataLabel="y", \ sciticks=False, logscale= False, signdef=False, \ indepLabel="x", invert_ind_axis=False, \ ny=1, nx=1, nplots=1, iplot=0, \ linesValsMinCI=None, linesValsMaxCI=None, \ dmin=np.NaN, dmax=np.NaN, \ lineAttribOffset=0, \ legend_inside=True, interiorLabels=True): # ARGUMENTS # fig - matplotlib figure object # linesVals - dependent variable (list of arrays) # xVals - independent variable on x-axis (array) # linesLabel - legend label for linesVals (list) # title - subplot title, optional # dataLabel - label for linesVals, optional # sciticks - whether linesVals needs scientific formatting for ticks, optional # logscale - y-axis is scaled logarithmically, optional, overrides sciticks # signdef - whether linesVals is positive/negative definite, optional # indepLabel - label for xVals, optional # invert_ind_axis - whether to invert x-axis orientation, optional # ny, nx - number of subplots in x/y direction, optional # nplots - total number of subplots, optional # iplot - this subplot index (starting at 0), optional # linesValsMinCI - minimum error bound for linesVals (list of arrays), optional # linesValsMaxCI - maximum error bound for linesVals (list of arrays), optional # Note: linesValsMinCI and linesValsMaxCI must be specified together # lineAttribOffset - offset for selecting line attributes, optional # dmin, dmax - min/max values of linesVals, optional # legend_inside - whether legend should be placed inside the subplot, optional ax = fig.add_subplot(ny, nx, iplot+1) #title ax.set_title(title,fontsize=5) #add lines plotVals = np.asarray([]) nLines = 0 for iline, lineVals in enumerate(linesVals): if np.all(np.isnan(lineVals)): global nanWarnSer if nanWarnSer==0: _logger.warning("skipping all-NaN data") _logger.warning(title+"; "+indepLabel+"; "+linesLabel[iline]) nanWarnSer=nanWarnSer+1 continue if len(lineVals)!=len(xVals): global lenWarnSer if lenWarnSer==0: _logger.warning("skipping data where len(x)!=len(y)") _logger.warning(title+"; "+indepLabel+"; "+linesLabel[iline]) lenWarnSer=lenWarnSer+1 continue # Plot line for each lineVals that has non-missing data pColor = pu.plotColor(len(linesVals),iline+lineAttribOffset) ax.plot(xVals, lineVals, \ color=pColor, \ label=linesLabel[iline], \ ls=pu.plotLineStyle(len(linesVals),iline+lineAttribOffset), \ linewidth=0.5) nLines += 1 plotVals = np.append(plotVals, lineVals) # Add shaded error regions if specified if linesValsMinCI is not None and \ linesValsMaxCI is not None: # test statistical significance versus zero if signdef: significant = np.empty(len(lineVals)) significant[:] = np.NaN else: significant = np.multiply(linesValsMinCI[iline], linesValsMaxCI[iline]) significant = np.array([x if np.isfinite(x) else -1.0 for x in significant]) lineArr = np.array(lineVals) xArr = np.array(xVals) negsiginds = np.array([i for i,x in enumerate(significant) if (x > 0.0 and lineArr[i] < 0.0)],dtype=int) if len(negsiginds) > 0: ax.plot(xArr[negsiginds], lineArr[negsiginds], \ color=pColor, \ ls='', \ marker='v', \ markersize=1.5) possiginds = np.array([i for i,x in enumerate(significant) if (x > 0.0 and lineArr[i] > 0.0)],dtype=int) if len(possiginds) > 0: ax.plot(xArr[possiginds], lineArr[possiginds], \ color=pColor, \ ls='', \ marker='^', \ markersize=1.5) ax.plot(xVals, linesValsMinCI[iline], \ color=pColor, \ alpha=0.4, \ ls='-', \ linewidth=0.5) ax.plot(xVals, linesValsMaxCI[iline], \ color=pColor, \ alpha=0.4, \ ls='-', \ linewidth=0.5) ax.fill_between(xVals, linesValsMinCI[iline], linesValsMaxCI[iline], \ color=pColor, \ edgecolor=pColor, \ linewidth=0.0, alpha = 0.1) ax.fill_between(xVals, linesValsMinCI[iline], linesValsMaxCI[iline], \ where=significant > 0.0, \ color=pColor, \ edgecolor=pColor, \ linewidth=0.2, alpha = 0.3) if nLines == 0: ax.tick_params(axis='x',labelbottom=False) ax.tick_params(axis='y',labelleft=False) return # add horizontal zero line for unbounded quantities if not signdef: ax.plot([xVals[0], xVals[-1]], [0., 0.], ls="--", c=".3", \ linewidth=0.7,markersize=0) # standardize x-limits mindval, maxdval = pu.get_clean_ax_limits(dmin,dmax,plotVals,signdef) #axes settings ax.xaxis.set_tick_params(labelsize=3) ax.yaxis.set_tick_params(labelsize=3) isLogScale = logscale if logscale: nonzero = np.logical_and(np.greater(np.abs(plotVals), 0.), np.isfinite(plotVals)) if nonzero.sum() > 0: vmin = np.nanmin(np.abs(plotVals[nonzero])) vmax = np.nanmax(np.abs(plotVals[nonzero])) if signdef: # log tick labels look bad for single decade if vmax / vmin > 10.0: ax.set_yscale('log') else: isLogScale = False else: ax.set_yscale('symlog') else: isLogScale = False if isLogScale and np.isfinite(maxdval) and maxdval > 0.: ax.set_ylim(None, maxdval) if np.abs(vmin) > 0.: ax.set_ylim(vmin, None) if not isLogScale: if sciticks: ax.ticklabel_format(style='sci', axis='y', scilimits=(0,0)) if (np.isfinite(mindval) and np.isfinite(maxdval)): ax.set_ylim(mindval,maxdval) if maxdval-mindval < 1.0 or \ maxdval-mindval > 100.0: ax.tick_params(axis='y',rotation=-35) ax.yaxis.get_offset_text().set_fontsize(3) #handle interior subplot ticks/labels ix = int(iplot)%int(nx) iy = int(iplot)/int(nx) if not interiorLabels \ and (iy < ny-2 or ( iy == ny-2 and (int(nplots)%int(nx)==0 or ix <= (int(nplots)%int(nx) - 1)) )): ax.tick_params(axis='x',labelbottom=False) if interiorLabels or ix == 0: ax.set_xlabel(indepLabel,fontsize=4) if interiorLabels or iy == ny-1: ax.set_ylabel(dataLabel,fontsize=4) #legend if nLines <= maxLegendEntries: if legend_inside: #INSIDE AXES lh = ax.legend(loc='best',fontsize=3,frameon=True,\ framealpha=0.4,ncol=1) lh.get_frame().set_linewidth(0.0) elif ix==nx-1 or iplot==nplots-1: #OUTSIDE AXES ax.legend(loc='upper left',fontsize=3,frameon=False, \ bbox_to_anchor=(1.02, 1), borderaxespad=0) if invert_ind_axis: ax.invert_xaxis() ax.grid() return ############################################################################### lenWarnProf = 0 nanWarnProf = 0 def plotProfile(fig, \ linesVals, yVals, \ linesLabel, \ title="", dataLabel="x", \ sciticks=False, logscale=False, signdef=False, \ indepLabel="y", invert_ind_axis=False, \ ny=1, nx=1, nplots=1, iplot=0, \ linesValsMinCI=None, linesValsMaxCI=None, \ dmin=np.NaN, dmax=np.NaN, \ lineAttribOffset=0, \ legend_inside=True, interiorLabels=True): # ARGUMENTS # fig - matplotlib figure object # linesVals - dependent variable (list of arrays) # yVals - independent variable on y-axis (array) # linesLabel - legend label for linesVals (list) # title - subplot title, optional # dataLabel - label for linesVals, optional # sciticks - whether linesVals needs scientific formatting for ticks, optional # logscale - x-axis is scaled logarithmically, optional, overrides sciticks # signdef - whether linesVals is positive/negative definite, optional # indepLabel - label for yVals, optional # invert_ind_axis - whether to invert y-axis orientation, optional # ny, nx - number of subplots in x/y direction, optional # nplots - total number of subplots, optional # iplot - this subplot index (starting at 0), optional # linesValsMinCI - minimum error bound for linesVals (list of arrays), optional # linesValsMaxCI - maximum error bound for linesVals (list of arrays), optional # Note: linesValsMinCI and linesValsMaxCI must be specified together # lineAttribOffset - offset for selecting line attributes, optional # dmin, dmax - min/max values of linesVals, optional # legend_inside - whether legend should be placed inside the subplot, optional ax = fig.add_subplot(ny, nx, iplot+1) #title ax.set_title(title,fontsize=5) #add lines plotVals = np.asarray([]) nLines = 0 for iline, lineVals in enumerate(linesVals): if np.all(np.isnan(lineVals)): global nanWarnProf if nanWarnProf==0: _logger.warning("skipping all-NaN data") _logger.warning(title+"; "+dataLabel+"; "+linesLabel[iline]) nanWarnProf=nanWarnProf+1 continue if len(lineVals)!=len(yVals): global lenWarnProf if lenWarnProf==0: _logger.warning("skipping data where len(x)!=len(y)") _logger.warning(title+"; "+dataLabel+"; "+linesLabel[iline]) lenWarnProf=lenWarnProf+1 continue # Plot line for each lineVals that has non-missing data pColor = pu.plotColor(len(linesVals),iline+lineAttribOffset) ax.plot(lineVals, yVals, \ color=pColor, \ label=linesLabel[iline], \ ls=pu.plotLineStyle(len(linesVals),iline+lineAttribOffset), \ linewidth=0.5) nLines += 1 plotVals = np.append(plotVals,lineVals) # Add shaded error regions if specified if linesValsMinCI is not None and \ linesValsMaxCI is not None: # test statistical significance versus zero if signdef: significant = np.empty(len(lineVals)) significant[:] = np.NaN else: significant = np.multiply(linesValsMinCI[iline], linesValsMaxCI[iline]) significant = np.array([x if np.isfinite(x) else -1.0 for x in significant]) lineArr = np.array(lineVals) yArr = np.array(yVals) negsiginds = np.array([i for i,x in enumerate(significant) if (x > 0.0 and lineArr[i] < 0.0)],dtype=int) if len(negsiginds) > 0: ax.plot(lineArr[negsiginds], yArr[negsiginds], \ color=pColor, \ ls='', \ marker='<', \ markersize=1.5) possiginds = np.array([i for i,x in enumerate(significant) if (x > 0.0 and lineArr[i] > 0.0)],dtype=int) if len(possiginds) > 0: ax.plot(lineArr[possiginds], yArr[possiginds], \ color=pColor, \ ls='', \ marker='>', \ markersize=1.5) ax.plot(linesValsMinCI[iline], yVals, \ color=pColor, \ alpha=0.4, \ ls='-', \ linewidth=0.5) ax.plot(linesValsMaxCI[iline], yVals, \ color=pColor, \ alpha=0.4, \ ls='-', \ linewidth=0.5) ax.fill_betweenx(yVals, linesValsMinCI[iline], linesValsMaxCI[iline], \ color=pColor, \ edgecolor=pColor, \ linewidth=0.0, alpha = 0.1) ax.fill_betweenx(yVals, linesValsMinCI[iline], linesValsMaxCI[iline], \ where=significant > 0.0, \ color=pColor, \ edgecolor=pColor, \ linewidth=0.2, alpha = 0.3) if nLines == 0: ax.tick_params(axis='x',labelbottom=False) ax.tick_params(axis='y',labelleft=False) return # add vertical zero line for unbounded quantities if not signdef: ax.plot([0., 0.], [yVals[0], yVals[-1]], ls="--", c=".3", \ linewidth=0.7,markersize=0) # standardize x-limits mindval, maxdval = pu.get_clean_ax_limits(dmin,dmax,plotVals,signdef) #axes settings ax.xaxis.set_tick_params(labelsize=3) ax.yaxis.set_tick_params(labelsize=3) isLogScale = logscale if logscale: nonzero = np.logical_and(np.greater(np.abs(plotVals), 0.), np.isfinite(plotVals)) if nonzero.sum() > 0: vmin = np.nanmin(np.abs(plotVals[nonzero])) vmax = np.nanmax(np.abs(plotVals[nonzero])) if signdef: # log tick labels look bad for single decade if vmax / vmin > 10.0: ax.set_xscale('log') else: isLogScale = False else: ax.set_xscale('symlog') else: isLogScale = False if isLogScale and np.isfinite(maxdval) and maxdval > 0.: ax.set_xlim(None, maxdval) if np.abs(mindval) > 0.: ax.set_xlim(mindval, None) if not isLogScale: if sciticks: ax.ticklabel_format(style='sci', axis='x', scilimits=(0,0)) if (np.isfinite(mindval) and np.isfinite(maxdval)): ax.set_xlim(mindval,maxdval) if maxdval-mindval < 1.0 or \ maxdval-mindval > 100.0: ax.tick_params(axis='x',rotation=-35) ax.xaxis.get_offset_text().set_fontsize(3) #handle interior subplot ticks/labels ix = int(iplot)%int(nx) iy = int(iplot)/int(nx) if not interiorLabels \ and (iy < ny-2 or ( iy == ny-2 and (int(nplots)%int(nx)==0 or ix <= (int(nplots)%int(nx) - 1)) )): ax.tick_params(axis='x',labelbottom=False) if interiorLabels or ix == 0: ax.set_xlabel(dataLabel,fontsize=4) if interiorLabels or iy == ny-1: ax.set_ylabel(indepLabel,fontsize=4) #legend if nLines <= maxLegendEntries: if legend_inside: #INSIDE AXES lh = ax.legend(loc='best',fontsize=3,frameon=True,\ framealpha=0.4,ncol=1) lh.get_frame().set_linewidth(0.0) elif ix==nx-1 or iplot==nplots-1: #OUTSIDE AXES ax.legend(loc='upper left',fontsize=3,frameon=False, \ bbox_to_anchor=(1.02, 1), borderaxespad=0) if invert_ind_axis: ax.invert_yaxis() ax.grid() return ############################################################################### lenWarnTS=0 nanWarnTS=0 def plotTimeSeries(fig, \ xsDates, linesVals, \ linesLabel, \ title="", dataLabel="", \ sciticks=False, logscale = False, signdef=False, \ ny=1, nx=1, nplots=1, iplot=0, \ linesValsMinCI=None, linesValsMaxCI=None, \ dmin=np.NaN, dmax=np.NaN, \ lineAttribOffset=0, \ legend_inside=True, interiorLabels=True): # ARGUMENTS # fig - matplotlib figure object # xsDates - date x-values (list/array or list of lists/arrays # of float seconds, dt.timedelta, dt.datetime) # linesVals - dependent variable (list of arrays) # linesLabel - legend label for linesVals (list) # title - subplot title, optional # dataLabel - label for linesVals, optional # sciticks - whether linesVals needs scientific formatting for ticks, optional # logscale - y-axis is scaled logarithmically, optional, overrides sciticks # signdef - whether linesVals is positive/negative definite, optional # ny, nx - number of subplots in x/y direction, optional # nplots - total number of subplots, optional # iplot - this subplot index (starting at 0), optional # linesValsMinCI - minimum error bound for linesVals (list of arrays), optional # linesValsMaxCI - maximum error bound for linesVals (list of arrays), optional # Note: linesValsMinCI and linesValsMaxCI must be specified together # lineAttribOffset - offset for selecting line attributes, optional # dmin, dmax - min/max values of linesVals, optional # legend_inside - whether legend should be placed inside the subplot, optional ax = fig.add_subplot(ny, nx, iplot+1) #title ax.set_title(title,fontsize=5) #add lines plotVals = np.asarray([]) nLines = 0 jline = 0 for iline, lineVals in enumerate(linesVals): if np.all(np.isnan(lineVals)): global nanWarnTS if nanWarnTS==0: _logger.warning("skipping all-NaN data") _logger.warning(title+"; "+dataLabel+"; "+linesLabel[iline]) nanWarnTS=nanWarnTS+1 continue #float xVals if isinstance(xsDates[0],(list,np.ndarray)): xVals = pu.TDeltas2Seconds(xsDates[min([iline,len(xsDates)-1])]) else: xVals = pu.TDeltas2Seconds(xsDates) if len(lineVals)!=len(xVals): global lenWarnTS if lenWarnTS==0: _logger.warning("skipping data where len(x)!=len(y)") _logger.warning(title+"; "+dataLabel+"; "+linesLabel[iline]) lenWarnTS=lenWarnTS+1 continue if jline == 0: minX = xVals[0] maxX = xVals[-1] else: minX = min([xVals[0], minX]) maxX = max([xVals[-1], maxX]) jline += 1 # Plot line for each lineVals that has non-missing data pColor = pu.plotColor(len(linesVals),iline+lineAttribOffset) ax.plot(xVals, lineVals, \ label=linesLabel[iline], \ color=pColor, \ ls=pu.plotLineStyle(len(linesVals),iline+lineAttribOffset), \ linewidth=0.5) nLines += 1 plotVals = np.append(plotVals, lineVals) # Add shaded CI regions if specified if linesValsMinCI is not None and \ linesValsMaxCI is not None: # test statistical significance versus zero if signdef: significant = np.empty(len(lineVals)) significant[:] = np.NaN else: significant = np.multiply(linesValsMinCI[iline], linesValsMaxCI[iline]) significant = np.array([x if np.isfinite(x) else -1.0 for x in significant]) lineArr = np.array(lineVals) xArr = np.array(xVals) negsiginds = np.array([i for i,x in enumerate(significant) if (x > 0.0 and lineArr[i] < 0.0)],dtype=int) if len(negsiginds) > 0: ax.plot(xArr[negsiginds], lineArr[negsiginds], \ color=pColor, \ ls='', \ marker='v', \ markersize=1.5) possiginds = np.array([i for i,x in enumerate(significant) if (x > 0.0 and lineArr[i] > 0.0)],dtype=int) if len(possiginds) > 0: ax.plot(xArr[possiginds], lineArr[possiginds], \ color=pColor, \ ls='', \ marker='^', \ markersize=1.5) ax.plot(xVals, linesValsMinCI[iline], \ color=pColor, \ alpha=0.4, \ ls='-', \ linewidth=0.5) ax.plot(xVals, linesValsMaxCI[iline], \ color=pColor, \ alpha=0.4, \ ls='-', \ linewidth=0.5) ax.fill_between(xVals, linesValsMinCI[iline], linesValsMaxCI[iline], \ color=pColor, \ edgecolor=pColor, \ linewidth=0.0, alpha = 0.1) ax.fill_between(xVals, linesValsMinCI[iline], linesValsMaxCI[iline], \ where=significant > 0.0, \ color=pColor, \ edgecolor=pColor, \ linewidth=0.2, alpha = 0.3) if nLines == 0: ax.tick_params(axis='x',labelbottom=False) ax.tick_params(axis='y',labelleft=False) return # standardize y-limits mindval, maxdval = pu.get_clean_ax_limits(dmin,dmax,plotVals,signdef) # add horizontal zero line for unbounded quantities if not signdef: ax.plot([minX, maxX], [0., 0.], ls="--", c=".3", \ linewidth=0.7,markersize=0) #axes settings if isinstance(xsDates[0],(list,np.ndarray)): pu.format_x_for_dates(ax, xsDates[0]) else: pu.format_x_for_dates(ax, xsDates) ax.xaxis.set_tick_params(labelsize=3) ax.yaxis.set_tick_params(labelsize=3) isLogScale = logscale if logscale: nonzero = np.logical_and(np.greater(np.abs(plotVals), 0.), np.isfinite(plotVals)) if nonzero.sum() > 0: vmin = np.nanmin(np.abs(plotVals[nonzero])) vmax = np.nanmax(np.abs(plotVals[nonzero])) if signdef: # log tick labels look bad for single decade if vmax / vmin > 10.0: ax.set_yscale('log') else: isLogScale = False else: ax.set_yscale('symlog') else: isLogScale = False if isLogScale and np.isfinite(maxdval) and maxdval > 0.: ax.set_ylim(None, maxdval) if np.abs(vmin) > 0.: ax.set_ylim(vmin, None) if not isLogScale: if sciticks: ax.ticklabel_format(style='sci', axis='y', scilimits=(0,0)) if (np.isfinite(mindval) and np.isfinite(maxdval)): ax.set_ylim(mindval,maxdval) if maxdval-mindval < 1.0 or \ maxdval-mindval > 100.0: ax.tick_params(axis='y',rotation=-35) ax.yaxis.get_offset_text().set_fontsize(3) ax.grid() #handle interior subplot ticks/labels ix = int(iplot)%int(nx) iy = int(iplot)/int(nx) if not interiorLabels \ and (iy < ny-2 or ( iy == ny-2 and (int(nplots)%int(nx)==0 or ix <= (int(nplots)%int(nx) - 1)) )): ax.tick_params(axis='x',labelbottom=False) if interiorLabels or ix == 0: ax.set_ylabel(dataLabel,fontsize=4) #legend if nLines <= maxLegendEntries: if legend_inside: #INSIDE AXES nlcol = np.int(np.ceil(np.sqrt(nLines))) lh = ax.legend(loc='best',fontsize=3,frameon=True,\ framealpha=0.4,ncol=nlcol) lh.get_frame().set_linewidth(0.0) elif ix==nx-1 or iplot==nplots-1: #OUTSIDE AXES ax.legend(loc='upper left',fontsize=3,frameon=False, \ bbox_to_anchor=(1.02, 1), borderaxespad=0) return ############################################################################### def plotTimeSeries2D(fig, \ xDates, yVals, contourVals, \ title="", clabel="", \ sciticks=False, logscale=False, signdef=False, \ dataLabel="y", invert_ind_axis=False, \ ny=1, nx=1, nplots=1, iplot=0, \ dmin=np.NaN, dmax=np.NaN, interiorLabels=True): # ARGUMENTS # fig - matplotlib figure object # xDates - date x-values (array of float seconds, dt.timedelta, dt.datetime) # yVals - second independent variable # contourVals - dependent variable (2d array) # title - subplot title, optional # clabel - label for dependent variable, optional # sciticks - whether contourVals needs scientific formatting for ticks, optional # logscale - whether contours are spaced logarithmically, optional, overrides sciticks # signdef - whether contourVals is positive/negative definite, optional # dataLabel - label for yVals, optional # invert_ind_axis - whether to invert y-axis orientation, optional # ny, nx - number of subplots in x/y direction, optional # nplots - total number of subplots, optional # iplot - this subplot index (starting at 0), optional # dmin, dmax - min/max values of contourVals, optional ax = fig.add_subplot(ny, nx, iplot+1) if (np.isnan(contourVals)).all(): ax.tick_params(axis='x',labelbottom=False) ax.tick_params(axis='y',labelleft=False) return xVals = pu.TDeltas2Seconds(xDates) # standardize c-limits mindval, maxdval = pu.get_clean_ax_limits(dmin,dmax,contourVals,signdef) if signdef: cmapName = 'BuPu' nlevs = 18 # scientific contours cint = contourVals.astype(int) isInt = np.all((contourVals - cint) == 0) if isInt: minscid = np.nanmax(np.array([1., dmin])) else: minscid = maxdval*1.e-5 lognorm = colors.LogNorm(vmin=minscid, vmax=maxdval) else: cmapName = 'seismic' nlevs = 28 # scientific contours lognorm = colors.SymLogNorm(vmin=mindval, vmax=maxdval, linthresh=1.e-3*maxdval, linscale=1.3, base=10) # plot contour # option 1: smoothed contours #cp = ax.contourf(xVals, yVals, contourVals, nlevs, cmap=cmapName, extend='both', \ # vmin=mindval, vmax=maxdval) # option 2: pixel contours cmap = plt.get_cmap(cmapName) cmap.set_bad(color = 'k', alpha = 1.0) if logscale: norm = lognorm else: levels = mticker.MaxNLocator(nbins=nlevs).tick_values(mindval,maxdval) norm = BoundaryNorm(levels, ncolors=cmap.N, clip=True) xVals_pcolor, yVals_pcolor = transformXY_for_pcolor(xVals,yVals) cp = ax.pcolormesh(xVals_pcolor, yVals_pcolor, contourVals, cmap=cmap, norm=norm) #title ax.set_title(title,fontsize=5) #axes settings pu.format_x_for_dates(ax, xDates) ax.xaxis.set_tick_params(labelsize=3) ax.yaxis.set_tick_params(labelsize=3) #handle interior subplot ticks/labels ix = int(iplot)%int(nx) iy = int(iplot)/int(nx) if not interiorLabels \ and (iy < ny-2 or ( iy == ny-2 and (int(nplots)%int(nx)==0 or ix <= (int(nplots)%int(nx) - 1)) )): ax.tick_params(axis='x',labelbottom=False) if interiorLabels or ix == 0: ax.set_ylabel(dataLabel,fontsize=4) if interiorLabels or ix == nx-1: #colorbar m = plt.cm.ScalarMappable(cmap=cmap) m.set_array(contourVals) m.set_norm(norm) if (np.isfinite(mindval) and np.isfinite(maxdval) and not logscale): m.set_clim(mindval,maxdval) cb = plt.colorbar(m, ax=ax) #scientific formatting if sciticks and not logscale: cb.ax.ticklabel_format(style='sci', axis='y', scilimits=(0,0)) cb.ax.yaxis.get_offset_text().set_fontsize(3) cb.ax.tick_params(labelsize=3) cb.set_label(clabel,fontsize=5) if invert_ind_axis: ax.invert_yaxis() # optionally add a grid #ax.grid() return ############################################################################### def transformXY_for_pcolor(xs,ys): # adjust centered x and y values to edges to work with pcolormesh # note: works best for regularly spaced data xs_diff = xs[1] - xs[0] # extend xs by 2 # fill in first endpoint xs_extend = [xs[0]-xs_diff] # fill in internal values for x in xs: xs_extend.append(x) # fill in last endpoint xs_extend.append(xs_extend[-1]+(xs[-1]-xs[-2])) # calculate the midpoints xs_pcolormesh_midpoints = [] for ii, x in enumerate(xs_extend[:-1]): xs_pcolormesh_midpoints.append(x+0.5*(xs_extend[ii+1] - xs_extend[ii])) ys_diff = ys[1] - ys[0] # extend ys by 2 # fill in first endpoint ys_extend = [ys[0]-ys_diff] # fill in internal values for y in ys: ys_extend.append(y) # fill in last endpoint ys_extend.append(ys_extend[-1]+(ys[-1]-ys[-2])) # calculate the midpoints ys_pcolormesh_midpoints = [] for ii, y in enumerate(ys_extend[:-1]): ys_pcolormesh_midpoints.append(y+0.5*(ys_extend[ii+1] - ys_extend[ii])) return xs_pcolormesh_midpoints, ys_pcolormesh_midpoints ############################################################################### lenWarnPDF = 0 nanWarnPDF = 0 def plotPDF(fig, countsVals, xVals, countsLabel, title="", indepLabel="x", ny=1, nx=1, nplots=1, iplot=0, lineAttribOffset=1, legend_inside=True, interiorLabels=True): # ARGUMENTS # fig - matplotlib figure object # countsVals - list of arrays, each containing counts across xVals # xVals - independent variable on x-axis (array) # countsLabel - legend label for countsVals (list) # title - subplot title, optional # indepLabel - label for xVals, optional # ny, nx - number of subplots in x/y direction, optional # nplots - total number of subplots, optional # iplot - this subplot index (starting at 0), optional # lineAttribOffset - offset for selecting line attributes, optional # legend_inside - whether legend should be placed inside the subplot, optional ax = fig.add_subplot(ny, nx, iplot+1) #title ax.set_title(title,fontsize=5) #add counts plotVals = [] nPDFs = 0 for ihist, countVals in enumerate(countsVals): if np.all(np.isnan(countVals)): global nanWarnPDF if nanWarnPDF==0: _logger.warning("skipping all-NaN data") _logger.warning(title+"; "+indepLabel+"; "+countsLabel[ihist]) nanWarnPDF=nanWarnPDF+1 continue if len(countVals)!=len(xVals): global lenWarnPDF if lenWarnPDF==0: _logger.warning("skipping data where len(x)!=len(y)") _logger.warning(title+"; "+indepLabel+"; "+countsLabel[ihist]) lenWarnPDF=lenWarnPDF+1 continue # Plot line for each countVals that has non-missing data # assume constant dx between bins dx = xVals[1] - xVals[0] ax.plot(xVals, np.divide(countVals,np.sum(countVals)*dx), color=pu.plotColor(len(countsVals),ihist+lineAttribOffset), label=countsLabel[ihist], ls=pu.plotLineStyle(len(countsVals),ihist+lineAttribOffset), linewidth=0.5) nPDFs = nPDFs + 1 plotVals.append(countVals) if nPDFs == 0: ax.tick_params(axis='x',labelbottom=False) ax.tick_params(axis='y',labelleft=False) return # add a standard normal pdf from scipy.stats import norm ax.plot(xVals, norm.pdf(xVals), color='k', ls='-', linewidth=0.35, label='N(0,1)' ) #axes settings ax.xaxis.set_tick_params(labelsize=3) ax.yaxis.set_tick_params(labelsize=3) plt.yscale('log') ax.set_ylim(bottom=1.e-6) #handle interior subplot ticks/labels ix = int(iplot)%int(nx) iy = int(iplot)/int(nx) if not interiorLabels \ and (iy < ny-2 or ( iy == ny-2 and (int(nplots)%int(nx)==0 or ix <= (int(nplots)%int(nx) - 1)) )): ax.tick_params(axis='x',labelbottom=False) if interiorLabels or ix == 0: ax.set_xlabel(indepLabel,fontsize=4) ax.set_ylabel('PDF',fontsize=4) #legend if legend_inside: #INSIDE AXES lh = ax.legend(loc='best',fontsize=3,frameon=True,\ framealpha=0.4,ncol=1) lh.get_frame().set_linewidth(0.0) elif ix==nx-1 or iplot==nplots-1: #OUTSIDE AXES ax.legend(loc='upper left',fontsize=3,frameon=False, \ bbox_to_anchor=(1.02, 1), borderaxespad=0) ax.grid() return ############################################################################### lenWarnRamp = 0 nanWarnRamp = 0 def plotfitRampComposite(fig, xVals, countVals, meanVals, rmsVals, stdVals, title="", dataLabel="y", \ indepLabel="x", ny=1, nx=1, nplots=1, iplot=0, lineAttribOffset=1, legend_inside=True, interiorLabels=True): # ARGUMENTS # fig - matplotlib figure object # countVals - Count of quantity (array) # meanVals - Mean of quantity (array) # rmsVals - RMS of quantity (array) # stdVals - STD of quantity (array) # xVals - independent variable on x-axis (array) # title - subplot title, optional # dataLabel - label for y-axis, optional # indepLabel - label for xVals, optional # ny, nx - number of subplots in x/y direction, optional # nplots - total number of subplots, optional # iplot - this subplot index (starting at 0), optional # lineAttribOffset - offset for selecting line attributes, optional # legend_inside - whether legend should be placed inside the subplot, optional ax = fig.add_subplot(ny, nx, iplot+1) ix = int(iplot)%int(nx) iy = int(iplot)/int(nx) #title ax.set_title(title,fontsize=5) #add lines plotVals = [] nLines = 0 linesLabel = ['RMS','STD','Mean'] for iline, lineVals in enumerate([rmsVals,stdVals,meanVals]): if np.all(np.isnan(lineVals)): global nanWarnRamp if nanWarnRamp==0: _logger.warning("skipping all-NaN data") _logger.warning(title+"; "+indepLabel+"; "+linesLabel[iline]) nanWarnRamp=nanWarnRamp+1 continue if len(lineVals)!=len(xVals): global lenWarnRamp if lenWarnRamp==0: _logger.warning("skipping data where len(x)!=len(y)") _logger.warning(title+"; "+indepLabel+"; "+linesLabel[iline]) lenWarnRamp=lenWarnRamp+1 continue # Plot line for each lineVals that has non-missing data pColor = pu.plotColor(4,iline+lineAttribOffset) ax.plot(xVals, lineVals, color=pColor, label=linesLabel[iline], ls=pu.plotLineStyle(4,iline+lineAttribOffset), linewidth=0.6) nLines += 1 plotVals.append(lineVals) if nLines == 0: ax.tick_params(axis='x',labelbottom=False) ax.tick_params(axis='y',labelleft=False) return # Add fit for stdVals here using info from countVals ind0 = np.argmax(countVals) indexMaxX4Std = 0 for ii, std in enumerate(stdVals): if np.isfinite(std): indexMaxX4Std = ii indexMaxX = indexMaxX4Std maxCount = 0 for ii, count in enumerate(countVals): if count > maxCount: maxCount = count if count < 0.002*maxCount: indexMaxX = ii break if indexMaxX > indexMaxX4Std: ind1 = np.argmax(stdVals[0:indexMaxX4Std]) else: ind1 = np.argmax(stdVals[0:indexMaxX]) weights = [0.2]*(ind1-ind0+1) weights[0] = 1.0 p = np.polyfit(xVals[ind0:ind1+1],stdVals[ind0:ind1+1],1, w=weights) X0 = xVals[ind0] ERR0 = X0 * p[0] + p[1] # X1 = xVals[ind1] # ERR1 = X1 * p[0] + p[1] ERR1 = stdVals[ind1] X1 = (ERR1 - p[1]) / p[0] ERRfitDict = { 'bu':{ 'X': [round(X0,2), round(X1,2)], 'ERR': [round(ERR0,2), round(ERR1,2)], }, 'YAML':{ 'X0': [round(X0,2)], 'X1': [round(X1,2)], 'ERR0': [round(ERR0,2)], 'ERR1': [round(ERR1,2)], }, } fitX = np.asarray([0.0] + ERRfitDict['bu']['X'] + [xVals[indexMaxX4Std]]) fitERR = np.asarray([ERR0] + ERRfitDict['bu']['ERR'] + [ERR1]) plotVals.append(fitERR) pColor = pu.plotColor(4,1+lineAttribOffset) ax.plot(fitX, fitERR, color=pColor, label='Fit-STD', ls='-.', linewidth=1.2, marker='+', ms=1.5 ) #axes settings ax.xaxis.set_tick_params(labelsize=3) ax.yaxis.set_tick_params(labelsize=3) # standardize x-limits mindval, maxdval = pu.get_clean_ax_limits(plotVals=plotVals) if (np.isfinite(mindval) and np.isfinite(maxdval)): ax.set_ylim(mindval,maxdval) #handle interior subplot ticks/labels if not interiorLabels \ and (iy < ny-2 or ( iy == ny-2 and (int(nplots)%int(nx)==0 or ix <= (int(nplots)%int(nx) - 1)) )): ax.tick_params(axis='x',labelbottom=False) if interiorLabels or ix == 0: ax.set_xlabel(indepLabel,fontsize=4) if interiorLabels or iy == ny-1: ax.set_ylabel(dataLabel,fontsize=4) #legend if legend_inside: #INSIDE AXES lh = ax.legend(loc='best',fontsize=3,frameon=True,\ framealpha=0.4,ncol=1) lh.get_frame().set_linewidth(0.0) elif ix==nx-1 or iplot==nplots-1: #OUTSIDE AXES ax.legend(loc='upper left',fontsize=3,frameon=False, \ bbox_to_anchor=(1.02, 1), borderaxespad=0) ax.grid() # Add count on RHS y-axis ax2 = ax.twinx() color = 'black' if interiorLabels or ix == nx: ax2.set_ylabel('Count',fontsize=4,color=color) ax2.plot(xVals[:indexMaxX4Std], countVals[:indexMaxX4Std], color=color, label='Count', ls=':', linewidth=0.5) ax2.tick_params(axis='y', labelcolor=color) ax2.yaxis.set_tick_params(labelsize=3) plt.yscale('log') ax2.set_ylim(bottom=100.) return ERRfitDict
35.827144
115
0.561006
from copy import deepcopy import cartopy.crs as ccrs import datetime as dt import logging from pandas.plotting import register_matplotlib_converters register_matplotlib_converters() import matplotlib matplotlib.use('AGG') import matplotlib.axes as maxes import matplotlib.cm as cm import matplotlib.colors as colors from matplotlib.colors import BoundaryNorm import matplotlib.pyplot as plt import matplotlib.ticker as mticker from mpl_toolkits.axes_grid1 import make_axes_locatable import numpy as np import plot_utils as pu import var_utils as vu import os _logger = logging.getLogger(__name__) cmGray = plt.cm.get_cmap("gist_gray") cmRainbow = plt.cm.get_cmap("gist_rainbow") cmSpectral = plt.cm.get_cmap("nipy_spectral") cmHeat = plt.cm.get_cmap("gist_heat") cmOcean = plt.cm.get_cmap("ocean") cmNCAR = plt.cm.get_cmap("gist_ncar") WhiteBlack1 = cmGray(np.linspace(1.0,0.0,17)) BlackRed = cmHeat(np.linspace(0.0,0.5,10)) ROYG = cmSpectral(np.linspace(0.9,0.43,27)) )) WhiteBlack2 = cmGray(np.linspace(0.9,0.0,31)) btcolors = np.concatenate((WhiteBlack1, BlackRed, ROYG, GreenBlueCyan, MVW, WhiteBlack2)) btCMap = colors.ListedColormap(btcolors) distriZooms = {} distriZooms['default'] = { 'cLon': None, 'minLon': -180, 'maxLon': 180, 'minLat': -90, 'maxLat': 90, } distriZooms['abi'] = { 'cLon': -75.2, 'minLon': None, 'maxLon': None, 'minLat': None, 'maxLat': None, } distriZooms['ahi'] = { 'cLon': 140.7, 'minLon': None, 'maxLon': None, 'minLat': None, 'maxLat': None, } def plotDistri(lats,lons,values, \ ObsType,VarName,var_unit,out_name,nstation,levbin, \ dmin=None,dmax=None,dotsize=6,color="rainbow"): cLon = distriZooms['default']['cLon'] minLon = distriZooms['default']['minLon'] maxLon = distriZooms['default']['maxLon'] minLat = distriZooms['default']['minLat'] maxLat = distriZooms['default']['maxLat'] for key, val in distriZooms.items(): if key in ObsType: cLon = val['cLon'] minLon = val['minLon'] maxLon = val['maxLon'] minLat = val['minLat'] maxLat = val['maxLat'] if cLon is not None: fig = plt.figure(figsize=(5,5)) ax = fig.add_subplot(projection=ccrs.Orthographic(cLon)) else: fig = plt.figure(figsize=(8,8)) ax = fig.add_subplot(projection=ccrs.PlateCarree()) ax.set_global() if color == "BT": if ("abi" in ObsType or "ahi" in ObsType): cm = btCMap if dmin is None: dmin = 183 if dmax is None: dmax = 303 else: cm = plt.cm.get_cmap("gist_ncar") if dmin is None: dmin = 190 if dmax is None: dmax = 270 else: cm = plt.cm.get_cmap(color) finite = np.isfinite(values) if ((("abi" in ObsType or "ahi" in ObsType) and finite.sum() > 4e4) or "model" in ObsType): lonsPlot = lons[finite] lonsPlot[lonsPlot > 180.0] -= 360.0 latsPlot = lats[finite] valuesPlot = values[finite] lonSort = np.argsort(lonsPlot) p = plt.pcolor(lonsPlot[lonSort], latsPlot[lonSort], valuesPlot[lonSort], transform = ccrs.PlateCarree(), cmap = cm, vmin = dmin, vmax = dmax, latlon = True, tri = True) else: p=ax.scatter(lons[finite], lats[finite], c=values[finite], transform = ccrs.PlateCarree(), cmap= cm, s = dotsize) ax.gridlines(draw_labels=True, xlocs=np.arange(-180,180,60),linestyle='--') ax.coastlines() divider = make_axes_locatable(ax) cax = divider.append_axes("bottom",size="5%", pad=0.3,axes_class=plt.Axes) plt.colorbar(p,cax=cax,orientation='horizontal') if nstation == 0 or ObsType == 'satwind': plt.text(0.5, 1.15, '%s %s %s nlocs:%s' \ %(ObsType,VarName,var_unit,len(values[~np.isnan(values)])), \ horizontalalignment='center', \ fontsize=12, transform = ax.transAxes) else: if ObsType[:6] == 'gnssro': plt.text(0.5, 1.15, '%s %s %s nlocs:%s nprofile:%s' \ %(ObsType,VarName,var_unit,len(values[~np.isnan(values)]),nstation), \ horizontalalignment='center', \ fontsize=12, transform = ax.transAxes) elif ObsType == 'aircraft': plt.text(0.5, 1.15, '%s %s %s nlocs:%s nflight:%s' \ %(ObsType,VarName,var_unit,len(values[~np.isnan(values)]),nstation), \ horizontalalignment='center', \ fontsize=12, transform = ax.transAxes) else: plt.text(0.5, 1.15, '%s %s %s nlocs:%s nstation:%s' \ %(ObsType,VarName,var_unit,len(values[~np.isnan(values)]),nstation), \ horizontalalignment='center', \ fontsize=12, transform = ax.transAxes) plt.savefig('distri_%s_%s_%s.png'%(VarName,out_name,levbin),dpi=200,bbox_inches='tight') plt.close() def scatterMapFields( lonVals, latVals, fields, filename, minLon = -180., maxLon = 180., minLat = -90., maxLat = 90., cLon = None, projection = 'default', dmin = None, dmax = None, markers = {}, sizes = {}, cmap = 'gist_ncar', cbarType = None, c = {}, logVLim = 1.e-12, ): cLons = np.asarray([]) lonVals_180 = {} for name in lonVals.keys(): cLon = None lonVals_360 = deepcopy(lonVals[name]) while np.max(lonVals_360) >= 360.0: lonVals_360[lonVals_360 >= 360.0] -= 360.0 while np.min(lonVals_360) < 0.0: lonVals_360[lonVals_360 < 0.0] += 360.0 lonVals_180[name] = deepcopy(lonVals_360) lonVals_180[name][lonVals_180[name] > 180.0] -= 360.0 for lon in [lonVals_360, lonVals_180[name]]: if np.max(lon) - np.min(lon) <= 180.0: cLon = 0.5*(np.max(lon) + np.min(lon)) cLons = np.append(cLons, cLon) anycLonNone = np.any([c is None for c in cLons]) if anycLonNone: fig = plt.figure(figsize=(5,5)) ax = fig.add_subplot(projection=ccrs.Mollweide(0.0)) else: cLon = cLons[0] if cLon > 180.0: cLon-=360.0 fig = plt.figure(figsize=(5,5)) ax = fig.add_subplot(projection=ccrs.Orthographic(cLon)) assert (cbarType is None or cbarType in ['Log', 'SymLog']), \ 'scatterMapFields: invalid cbarType: '+cbarType for name, field in fields.items(): f = c=c.get(name, field) finite = np.isfinite(f) lons = lonVals_180[name][finite] lats = latVals[name][finite] f = f[finite] ons[lonSort] lats = lats[lonSort] f = f[lonSort] if dmin is None: vmin = f.min() else: vmin = dmin if dmax is None: vmax = f.max() else: vmax = dmax if cbarType is None: norm = None elif cbarType == 'Log': if vmin <= logVLim: vmin = logVLim f[f < vmin] = vmin norm=colors.LogNorm(vmin=vmin, vmax=vmax) elif cbarType == 'SymLog': norm=colors.SymLogNorm(vmin=vmin, vmax=vmax, linthresh=1.e-4*vmax, linscale=1.0, base=10) sc = ax.scatter(lons, lats, c=f, s = sizes.get(name, 1), cmap = cmap, norm = norm, marker = markers.get(name, '.'), linewidth = 0, transform=ccrs.PlateCarree(), ) ax.set_global() ax.coastlines() divider = make_axes_locatable(ax) cax = divider.append_axes("bottom",size="5%", pad=0.3,axes_class=plt.Axes) cb = plt.colorbar(sc, cax=cax, orientation='horizontal') plt.savefig(filename, dpi=200, bbox_inches='tight') plt.close() def plotTimeserial2D(Stats,xlabeltime,ylevels,VarName): zgrid = np.loadtxt("/glade/work/jban/pandac/fix_input/graphics/zgrid_v55.txt") fig, ax1 = plt.subplots() xarray = range(len(xlabeltime)) valuemin = np.amin(Stats) valuemax = np.amax(Stats) epsilon = 1.e-8 if (valuemin > 0 or valuemax < 0): color = 'rainbow' plt.contourf(xarray,ylevels,Stats,40,vmin=valuemin, vmax=valuemax,cmap=color) xi=-1 else: cmap = 'coolwarm' if ( -valuemin < epsilon and valuemax < epsilon ): xi=1 valuemin = -epsilon valuemax = epsilon elif ( -valuemin < epsilon and valuemax > epsilon ): xi=2 valuemin = -epsilon elif ( -valuemin > epsilon and valuemax < epsilon ): xi=3 valuemax = epsilon else: xi=4 norm = matplotlib.colors.DivergingNorm(vmin=valuemin, vcenter=0, vmax=valuemax) plt.contourf(xarray,ylevels,Stats,40,vmin=valuemin, vmax=valuemax,norm=norm,cmap=cmap) xarray = range(len(xlabeltime)) major_ticks = np.arange(0, 56, 5) ax1.set_yticks(major_ticks) ax1.set_ylim([0,54]) ax1.set_ylabel('Vertical level',fontsize=15) ax2 = ax1.twinx() ax2.set_yticks(major_ticks-1) ax2.set_yticklabels((zgrid[::5]).astype(int)) ax2.set_ylabel('Height (m)',fontsize=13) FCDay = ''.join(VarName.split("_")[1:][:-3]) if (FCDay == 'day0.0'): ax1.set_xlabel('Analysis Time',fontsize=15) ax1.set_xticks(xarray[::4]) ax1.set_xticklabels(xlabeltime[::4],rotation=90) elif (FCDay == 'day0.25'): ax1.set_xlabel( '6h Forecast',fontsize=15) ax1.set_xticks(xarray[::4]) ax1.set_xticklabels(xlabeltime[::4],rotation=90) else: ax1.set_xlabel( 'Lead Time',fontsize=15) plt.colorbar(extend='both',orientation="horizontal",pad=0.2) ax1.grid(True) region = ''.join(VarName.split("_")[2:][:-2]) var = ''.join(VarName.split("_")[3:][:-1]) stats = ''.join(VarName.split("_")[4:]) plt.title(stats+' variable:'+vu.varDictModel[var][1]+'('+ vu.varDictModel[var][0]+') '+region, fontsize = 12) plt.savefig(VarName+'_TS_2d.png',dpi=200,bbox_inches='tight') plt.close() maxLegendEntries = 12 color=pColor, \ alpha=0.4, \ ls='-', \ linewidth=0.5) ax.plot(xVals, linesValsMaxCI[iline], \ color=pColor, \ alpha=0.4, \ ls='-', \ linewidth=0.5) ax.fill_between(xVals, linesValsMinCI[iline], linesValsMaxCI[iline], \ color=pColor, \ edgecolor=pColor, \ linewidth=0.0, alpha = 0.1) ax.fill_between(xVals, linesValsMinCI[iline], linesValsMaxCI[iline], \ where=significant > 0.0, \ color=pColor, \ edgecolor=pColor, \ linewidth=0.2, alpha = 0.3) if nLines == 0: ax.tick_params(axis='x',labelbottom=False) ax.tick_params(axis='y',labelleft=False) return if not signdef: ax.plot([xVals[0], xVals[-1]], [0., 0.], ls="--", c=".3", \ linewidth=0.7,markersize=0) mindval, maxdval = pu.get_clean_ax_limits(dmin,dmax,plotVals,signdef) ax.xaxis.set_tick_params(labelsize=3) ax.yaxis.set_tick_params(labelsize=3) isLogScale = logscale if logscale: nonzero = np.logical_and(np.greater(np.abs(plotVals), 0.), np.isfinite(plotVals)) if nonzero.sum() > 0: vmin = np.nanmin(np.abs(plotVals[nonzero])) vmax = np.nanmax(np.abs(plotVals[nonzero])) if signdef: if vmax / vmin > 10.0: ax.set_yscale('log') else: isLogScale = False else: ax.set_yscale('symlog') else: isLogScale = False if isLogScale and np.isfinite(maxdval) and maxdval > 0.: ax.set_ylim(None, maxdval) if np.abs(vmin) > 0.: ax.set_ylim(vmin, None) if not isLogScale: if sciticks: ax.ticklabel_format(style='sci', axis='y', scilimits=(0,0)) if (np.isfinite(mindval) and np.isfinite(maxdval)): ax.set_ylim(mindval,maxdval) if maxdval-mindval < 1.0 or \ maxdval-mindval > 100.0: ax.tick_params(axis='y',rotation=-35) ax.yaxis.get_offset_text().set_fontsize(3) ix = int(iplot)%int(nx) iy = int(iplot)/int(nx) if not interiorLabels \ and (iy < ny-2 or ( iy == ny-2 and (int(nplots)%int(nx)==0 or ix <= (int(nplots)%int(nx) - 1)) )): ax.tick_params(axis='x',labelbottom=False) if interiorLabels or ix == 0: ax.set_xlabel(indepLabel,fontsize=4) if interiorLabels or iy == ny-1: ax.set_ylabel(dataLabel,fontsize=4) if nLines <= maxLegendEntries: if legend_inside: lh = ax.legend(loc='best',fontsize=3,frameon=True,\ framealpha=0.4,ncol=1) lh.get_frame().set_linewidth(0.0) elif ix==nx-1 or iplot==nplots-1: ax.legend(loc='upper left',fontsize=3,frameon=False, \ bbox_to_anchor=(1.02, 1), borderaxespad=0) if invert_ind_axis: ax.invert_xaxis() ax.grid() return als, \ color=pColor, \ alpha=0.4, \ ls='-', \ linewidth=0.5) ax.plot(linesValsMaxCI[iline], yVals, \ color=pColor, \ alpha=0.4, \ ls='-', \ linewidth=0.5) ax.fill_betweenx(yVals, linesValsMinCI[iline], linesValsMaxCI[iline], \ color=pColor, \ edgecolor=pColor, \ linewidth=0.0, alpha = 0.1) ax.fill_betweenx(yVals, linesValsMinCI[iline], linesValsMaxCI[iline], \ where=significant > 0.0, \ color=pColor, \ edgecolor=pColor, \ linewidth=0.2, alpha = 0.3) if nLines == 0: ax.tick_params(axis='x',labelbottom=False) ax.tick_params(axis='y',labelleft=False) return if not signdef: ax.plot([0., 0.], [yVals[0], yVals[-1]], ls="--", c=".3", \ linewidth=0.7,markersize=0) mindval, maxdval = pu.get_clean_ax_limits(dmin,dmax,plotVals,signdef) ax.xaxis.set_tick_params(labelsize=3) ax.yaxis.set_tick_params(labelsize=3) isLogScale = logscale if logscale: nonzero = np.logical_and(np.greater(np.abs(plotVals), 0.), np.isfinite(plotVals)) if nonzero.sum() > 0: vmin = np.nanmin(np.abs(plotVals[nonzero])) vmax = np.nanmax(np.abs(plotVals[nonzero])) if signdef: if vmax / vmin > 10.0: ax.set_xscale('log') else: isLogScale = False else: ax.set_xscale('symlog') else: isLogScale = False if isLogScale and np.isfinite(maxdval) and maxdval > 0.: ax.set_xlim(None, maxdval) if np.abs(mindval) > 0.: ax.set_xlim(mindval, None) if not isLogScale: if sciticks: ax.ticklabel_format(style='sci', axis='x', scilimits=(0,0)) if (np.isfinite(mindval) and np.isfinite(maxdval)): ax.set_xlim(mindval,maxdval) if maxdval-mindval < 1.0 or \ maxdval-mindval > 100.0: ax.tick_params(axis='x',rotation=-35) ax.xaxis.get_offset_text().set_fontsize(3) ix = int(iplot)%int(nx) iy = int(iplot)/int(nx) if not interiorLabels \ and (iy < ny-2 or ( iy == ny-2 and (int(nplots)%int(nx)==0 or ix <= (int(nplots)%int(nx) - 1)) )): ax.tick_params(axis='x',labelbottom=False) if interiorLabels or ix == 0: ax.set_xlabel(dataLabel,fontsize=4) if interiorLabels or iy == ny-1: ax.set_ylabel(indepLabel,fontsize=4) if nLines <= maxLegendEntries: if legend_inside: lh = ax.legend(loc='best',fontsize=3,frameon=True,\ framealpha=0.4,ncol=1) lh.get_frame().set_linewidth(0.0) elif ix==nx-1 or iplot==nplots-1: ax.legend(loc='upper left',fontsize=3,frameon=False, \ bbox_to_anchor=(1.02, 1), borderaxespad=0) if invert_ind_axis: ax.invert_yaxis() ax.grid() return if (x > 0.0 and lineArr[i] > 0.0)],dtype=int) if len(possiginds) > 0: ax.plot(xArr[possiginds], lineArr[possiginds], \ color=pColor, \ ls='', \ marker='^', \ markersize=1.5) ax.plot(xVals, linesValsMinCI[iline], \ color=pColor, \ alpha=0.4, \ ls='-', \ linewidth=0.5) ax.plot(xVals, linesValsMaxCI[iline], \ color=pColor, \ alpha=0.4, \ ls='-', \ linewidth=0.5) ax.fill_between(xVals, linesValsMinCI[iline], linesValsMaxCI[iline], \ color=pColor, \ edgecolor=pColor, \ linewidth=0.0, alpha = 0.1) ax.fill_between(xVals, linesValsMinCI[iline], linesValsMaxCI[iline], \ where=significant > 0.0, \ color=pColor, \ edgecolor=pColor, \ linewidth=0.2, alpha = 0.3) if nLines == 0: ax.tick_params(axis='x',labelbottom=False) ax.tick_params(axis='y',labelleft=False) return mindval, maxdval = pu.get_clean_ax_limits(dmin,dmax,plotVals,signdef) if not signdef: ax.plot([minX, maxX], [0., 0.], ls="--", c=".3", \ linewidth=0.7,markersize=0) if isinstance(xsDates[0],(list,np.ndarray)): pu.format_x_for_dates(ax, xsDates[0]) else: pu.format_x_for_dates(ax, xsDates) ax.xaxis.set_tick_params(labelsize=3) ax.yaxis.set_tick_params(labelsize=3) isLogScale = logscale if logscale: nonzero = np.logical_and(np.greater(np.abs(plotVals), 0.), np.isfinite(plotVals)) if nonzero.sum() > 0: vmin = np.nanmin(np.abs(plotVals[nonzero])) vmax = np.nanmax(np.abs(plotVals[nonzero])) if signdef: if vmax / vmin > 10.0: ax.set_yscale('log') else: isLogScale = False else: ax.set_yscale('symlog') else: isLogScale = False if isLogScale and np.isfinite(maxdval) and maxdval > 0.: ax.set_ylim(None, maxdval) if np.abs(vmin) > 0.: ax.set_ylim(vmin, None) if not isLogScale: if sciticks: ax.ticklabel_format(style='sci', axis='y', scilimits=(0,0)) if (np.isfinite(mindval) and np.isfinite(maxdval)): ax.set_ylim(mindval,maxdval) if maxdval-mindval < 1.0 or \ maxdval-mindval > 100.0: ax.tick_params(axis='y',rotation=-35) ax.yaxis.get_offset_text().set_fontsize(3) ax.grid() ix = int(iplot)%int(nx) iy = int(iplot)/int(nx) if not interiorLabels \ and (iy < ny-2 or ( iy == ny-2 and (int(nplots)%int(nx)==0 or ix <= (int(nplots)%int(nx) - 1)) )): ax.tick_params(axis='x',labelbottom=False) if interiorLabels or ix == 0: ax.set_ylabel(dataLabel,fontsize=4) if nLines <= maxLegendEntries: if legend_inside: nlcol = np.int(np.ceil(np.sqrt(nLines))) lh = ax.legend(loc='best',fontsize=3,frameon=True,\ framealpha=0.4,ncol=nlcol) lh.get_frame().set_linewidth(0.0) elif ix==nx-1 or iplot==nplots-1: ax.legend(loc='upper left',fontsize=3,frameon=False, \ bbox_to_anchor=(1.02, 1), borderaxespad=0) return
true
true
f72cbfd0caae91239053996913ba8621fe6047da
636
py
Python
RestaurantReview/manage.py
sehyun-seankim/Django_project_restaurant_review
5d2eb90486f8064aec16538a71c667d830d3db37
[ "MIT" ]
null
null
null
RestaurantReview/manage.py
sehyun-seankim/Django_project_restaurant_review
5d2eb90486f8064aec16538a71c667d830d3db37
[ "MIT" ]
null
null
null
RestaurantReview/manage.py
sehyun-seankim/Django_project_restaurant_review
5d2eb90486f8064aec16538a71c667d830d3db37
[ "MIT" ]
null
null
null
#!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys def main(): os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'RestaurantReview.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if __name__ == '__main__': main()
28.909091
80
0.687107
import os import sys def main(): os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'RestaurantReview.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if __name__ == '__main__': main()
true
true
f72cbfdf7f7c4f11bbe1601b54f70466e1e3e688
5,321
py
Python
slackclient/_response.py
lovexi/CodingMonkey-Bot-Python-version
52561d2b15a78119769099d304a98f80da53a010
[ "MIT" ]
null
null
null
slackclient/_response.py
lovexi/CodingMonkey-Bot-Python-version
52561d2b15a78119769099d304a98f80da53a010
[ "MIT" ]
null
null
null
slackclient/_response.py
lovexi/CodingMonkey-Bot-Python-version
52561d2b15a78119769099d304a98f80da53a010
[ "MIT" ]
null
null
null
import json import random import math import os from crawling._twitter import twitter_crawling class Response(object): def __init__(self, token): self.name = "" self.token = token self.greetingList = ['Hello {}, welcome to the Equifax Hackathon channel! Have fun :). You can type help for more details!' , 'Nice to see you here, {} ! What can I do for you (please type help!)' , 'I am willing to do anything for you {} ! Type help so I can help you!'] self.help_msg = {"text": 'Don\'t Worry {} ! I will show you how to communicate with me :).', "attachments":[{"pretext": "Command line:", "color": "#36a64f", "text": "hi: Say hello to me, so that I know you are here!"}, {"color": "#36a64f", "text": "print message: I will grab all detailed ID message for you, such as channel id or user id :)"}, {"color": "#e2ffb6", "text": "help: I can show you all commands I can understand :)"}, {"color": "#415677", "text": "show name or nameID: I can know that your target ID"}, {"color": "#b27485", "text": "select dataLocation: I can know where I can grab data for you"} ]} self.select_msg = {"text": "Where do you want to grab personal information for {} ?", "attachments": [{"pretext": "You can choose:", "color": "#36a64f", "text": "Facebook + limits"}, {"color": "#36a64f", "text": "Twitter + limits"}, {"color": "#415677", "text": "Craigslist"} ]} def response(self, data, channel, sc, user): type = data["type"] user_info = sc.api_read("users.info", token = self.token, user = user) username = user_info["user"]["name"] if type == "hello": sc.rtm_send_message(channel, self.greetingList[int(math.floor(random.random()*3))].format(username)) if "user" in data.keys() and data["user"] == user: if (type == "message"): text = data["text"].lower() if (text.startswith("hi")): sc.rtm_send_message(channel, "I am CodingMonkey Bot. Nice to meet you here {0}!".format(username)) if (text.startswith("print")): sc.rtm_send_message(channel, data[text[5:].strip()]) if (text.startswith("help")): sc.api_call("chat.postMessage", token = self.token, channel = channel, username = "codingmonkey", text = self.help_msg["text"].format(username), attachments = self.help_msg["attachments"]) if (text.startswith("show")): command_msg = str(text).split(' ') self.name = command_msg[1] sc.api_call("chat.postMessage", token = self.token, channel = channel, username = "codingmonkey", text = self.select_msg["text"].format(username), attachments = self.select_msg["attachments"]) if (text.startswith("select")): command_msg = str(text).split(' ') if (command_msg[1].lower() == "twitter"): twi = twitter_crawling() limits = 5 if len(command_msg) == 3: limits = int(command_msg[2]) twitter_info = json.dumps(twi.spiderInfo(self.name, limits)) sc.api_call("chat.postMessage", token = self.token, channel = channel, username = "codingmonkey", text = "Here are the results in Twitter:", attachments = twitter_info) elif (command_msg[1].lower() == "facebook"): root = os.getcwd() relative_path = "slackclient/data/facebookY.json" abs_path = os.path.join(root, relative_path) with open(abs_path) as facebook_file: facebook_info = json.load(facebook_file) facebook_info = json.dumps(facebook_info) sc.api_call("chat.postMessage", token = self.token, channel = channel, username = "codingmonkey", text = "Here are the results in Facebook:", attachments = facebook_info) elif (command_msg[1].lower() == "craigslist"): root = os.getcwd() relative_path = "slackclient/data/craigslist.json" abs_path = os.path.join(root, relative_path) with open(abs_path) as craigslist_file: craigslist_info = json.load(craigslist_file) craigslist_info = json.dumps(craigslist_info) craigslist_info = craigslist_info.replace("'", "%100") sc.api_call("chat.postMessage", token = self.token, channel = channel, username = "codingmonkey", text = "Here are the results in Craigslist:", attachments = craigslist_info)
58.472527
153
0.516256
import json import random import math import os from crawling._twitter import twitter_crawling class Response(object): def __init__(self, token): self.name = "" self.token = token self.greetingList = ['Hello {}, welcome to the Equifax Hackathon channel! Have fun :). You can type help for more details!' , 'Nice to see you here, {} ! What can I do for you (please type help!)' , 'I am willing to do anything for you {} ! Type help so I can help you!'] self.help_msg = {"text": 'Don\'t Worry {} ! I will show you how to communicate with me :).', "attachments":[{"pretext": "Command line:", "color": "#36a64f", "text": "hi: Say hello to me, so that I know you are here!"}, {"color": "#36a64f", "text": "print message: I will grab all detailed ID message for you, such as channel id or user id :)"}, {"color": "#e2ffb6", "text": "help: I can show you all commands I can understand :)"}, {"color": "#415677", "text": "show name or nameID: I can know that your target ID"}, {"color": "#b27485", "text": "select dataLocation: I can know where I can grab data for you"} ]} self.select_msg = {"text": "Where do you want to grab personal information for {} ?", "attachments": [{"pretext": "You can choose:", "color": "#36a64f", "text": "Facebook + limits"}, {"color": "#36a64f", "text": "Twitter + limits"}, {"color": "#415677", "text": "Craigslist"} ]} def response(self, data, channel, sc, user): type = data["type"] user_info = sc.api_read("users.info", token = self.token, user = user) username = user_info["user"]["name"] if type == "hello": sc.rtm_send_message(channel, self.greetingList[int(math.floor(random.random()*3))].format(username)) if "user" in data.keys() and data["user"] == user: if (type == "message"): text = data["text"].lower() if (text.startswith("hi")): sc.rtm_send_message(channel, "I am CodingMonkey Bot. Nice to meet you here {0}!".format(username)) if (text.startswith("print")): sc.rtm_send_message(channel, data[text[5:].strip()]) if (text.startswith("help")): sc.api_call("chat.postMessage", token = self.token, channel = channel, username = "codingmonkey", text = self.help_msg["text"].format(username), attachments = self.help_msg["attachments"]) if (text.startswith("show")): command_msg = str(text).split(' ') self.name = command_msg[1] sc.api_call("chat.postMessage", token = self.token, channel = channel, username = "codingmonkey", text = self.select_msg["text"].format(username), attachments = self.select_msg["attachments"]) if (text.startswith("select")): command_msg = str(text).split(' ') if (command_msg[1].lower() == "twitter"): twi = twitter_crawling() limits = 5 if len(command_msg) == 3: limits = int(command_msg[2]) twitter_info = json.dumps(twi.spiderInfo(self.name, limits)) sc.api_call("chat.postMessage", token = self.token, channel = channel, username = "codingmonkey", text = "Here are the results in Twitter:", attachments = twitter_info) elif (command_msg[1].lower() == "facebook"): root = os.getcwd() relative_path = "slackclient/data/facebookY.json" abs_path = os.path.join(root, relative_path) with open(abs_path) as facebook_file: facebook_info = json.load(facebook_file) facebook_info = json.dumps(facebook_info) sc.api_call("chat.postMessage", token = self.token, channel = channel, username = "codingmonkey", text = "Here are the results in Facebook:", attachments = facebook_info) elif (command_msg[1].lower() == "craigslist"): root = os.getcwd() relative_path = "slackclient/data/craigslist.json" abs_path = os.path.join(root, relative_path) with open(abs_path) as craigslist_file: craigslist_info = json.load(craigslist_file) craigslist_info = json.dumps(craigslist_info) craigslist_info = craigslist_info.replace("'", "%100") sc.api_call("chat.postMessage", token = self.token, channel = channel, username = "codingmonkey", text = "Here are the results in Craigslist:", attachments = craigslist_info)
true
true
f72cc038fe01f625fd75044fc25d9c661707b934
241
py
Python
fabfile/__init__.py
lem-usp/Bio507
67b8f8f677e6c1f39ad257d456f0cc0cac289022
[ "MIT" ]
null
null
null
fabfile/__init__.py
lem-usp/Bio507
67b8f8f677e6c1f39ad257d456f0cc0cac289022
[ "MIT" ]
null
null
null
fabfile/__init__.py
lem-usp/Bio507
67b8f8f677e6c1f39ad257d456f0cc0cac289022
[ "MIT" ]
null
null
null
from fabric.state import output from .development import * # # Fabric configuration # output['debug'] = False # see full command list def help(): ''' Fabfile documentation ''' local('python -c "import fabfile; help(fabfile)"')
16.066667
54
0.680498
from fabric.state import output from .development import * output['debug'] = False def help(): local('python -c "import fabfile; help(fabfile)"')
true
true
f72cc0e34bd07cf91c3cd084ab5e50132bdbe531
5,036
py
Python
sahara/plugins/vanilla/hadoop2/validation.py
hortonworksqe/sahara
b8edeaf2b6a475728bf9fd2ddc3a860dc6c23270
[ "Apache-2.0" ]
1
2016-04-13T17:07:05.000Z
2016-04-13T17:07:05.000Z
sahara/plugins/vanilla/hadoop2/validation.py
hortonworksqe/sahara
b8edeaf2b6a475728bf9fd2ddc3a860dc6c23270
[ "Apache-2.0" ]
null
null
null
sahara/plugins/vanilla/hadoop2/validation.py
hortonworksqe/sahara
b8edeaf2b6a475728bf9fd2ddc3a860dc6c23270
[ "Apache-2.0" ]
null
null
null
# Copyright (c) 2014 Mirantis Inc. # # 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 sahara.plugins.general import exceptions as ex from sahara.plugins.general import utils as u from sahara.plugins.vanilla.hadoop2 import config_helper as cu from sahara.plugins.vanilla import utils as vu from sahara.utils import general as gu def validate_cluster_creating(pctx, cluster): nn_count = _get_inst_count(cluster, 'namenode') if nn_count != 1: raise ex.InvalidComponentCountException('namenode', 1, nn_count) snn_count = _get_inst_count(cluster, 'secondarynamenode') if snn_count not in [0, 1]: raise ex.InvalidComponentCountException('secondarynamenode', '0 or 1', snn_count) rm_count = _get_inst_count(cluster, 'resourcemanager') if rm_count not in [0, 1]: raise ex.InvalidComponentCountException('resourcemanager', '0 or 1', rm_count) hs_count = _get_inst_count(cluster, 'historyserver') if hs_count not in [0, 1]: raise ex.InvalidComponentCountException('historyserver', '0 or 1', hs_count) nm_count = _get_inst_count(cluster, 'nodemanager') if rm_count == 0: if nm_count > 0: raise ex.RequiredServiceMissingException('resourcemanager', required_by='nodemanager') oo_count = _get_inst_count(cluster, 'oozie') dn_count = _get_inst_count(cluster, 'datanode') if oo_count not in [0, 1]: raise ex.InvalidComponentCountException('oozie', '0 or 1', oo_count) if oo_count == 1: if dn_count < 1: raise ex.RequiredServiceMissingException('datanode', required_by='oozie') if nm_count < 1: raise ex.RequiredServiceMissingException('nodemanager', required_by='oozie') if hs_count != 1: raise ex.RequiredServiceMissingException('historyserver', required_by='oozie') rep_factor = cu.get_config_value(pctx, 'HDFS', 'dfs.replication', cluster) if dn_count < rep_factor: raise ex.InvalidComponentCountException( 'datanode', rep_factor, dn_count, 'Number of datanodes must be not' ' less than dfs.replication.') def validate_additional_ng_scaling(cluster, additional): rm = vu.get_resourcemanager(cluster) scalable_processes = _get_scalable_processes() for ng_id in additional: ng = gu.get_by_id(cluster.node_groups, ng_id) if not set(ng.node_processes).issubset(scalable_processes): msg = "Vanilla plugin cannot scale nodegroup with processes: %s" raise ex.NodeGroupCannotBeScaled(ng.name, msg % ' '.join(ng.node_processes)) if not rm and 'nodemanager' in ng.node_processes: msg = ("Vanilla plugin cannot scale node group with processes " "which have no master-processes run in cluster") raise ex.NodeGroupCannotBeScaled(ng.name, msg) def validate_existing_ng_scaling(pctx, cluster, existing): scalable_processes = _get_scalable_processes() dn_to_delete = 0 for ng in cluster.node_groups: if ng.id in existing: if ng.count > existing[ng.id] and "datanode" in ng.node_processes: dn_to_delete += ng.count - existing[ng.id] if not set(ng.node_processes).issubset(scalable_processes): msg = ("Vanilla plugin cannot scale nodegroup " "with processes: %s") raise ex.NodeGroupCannotBeScaled( ng.name, msg % ' '.join(ng.node_processes)) dn_amount = len(vu.get_datanodes(cluster)) rep_factor = cu.get_config_value(pctx, 'HDFS', 'dfs.replication', cluster) if dn_to_delete > 0 and dn_amount - dn_to_delete < rep_factor: msg = ("Vanilla plugin cannot shrink cluster because it would be not " "enough nodes for replicas (replication factor is %s)") raise ex.ClusterCannotBeScaled( cluster.name, msg % rep_factor) def _get_scalable_processes(): return ['datanode', 'nodemanager'] def _get_inst_count(cluster, process): return sum([ng.count for ng in u.get_node_groups(cluster, process)])
41.619835
79
0.633241
from sahara.plugins.general import exceptions as ex from sahara.plugins.general import utils as u from sahara.plugins.vanilla.hadoop2 import config_helper as cu from sahara.plugins.vanilla import utils as vu from sahara.utils import general as gu def validate_cluster_creating(pctx, cluster): nn_count = _get_inst_count(cluster, 'namenode') if nn_count != 1: raise ex.InvalidComponentCountException('namenode', 1, nn_count) snn_count = _get_inst_count(cluster, 'secondarynamenode') if snn_count not in [0, 1]: raise ex.InvalidComponentCountException('secondarynamenode', '0 or 1', snn_count) rm_count = _get_inst_count(cluster, 'resourcemanager') if rm_count not in [0, 1]: raise ex.InvalidComponentCountException('resourcemanager', '0 or 1', rm_count) hs_count = _get_inst_count(cluster, 'historyserver') if hs_count not in [0, 1]: raise ex.InvalidComponentCountException('historyserver', '0 or 1', hs_count) nm_count = _get_inst_count(cluster, 'nodemanager') if rm_count == 0: if nm_count > 0: raise ex.RequiredServiceMissingException('resourcemanager', required_by='nodemanager') oo_count = _get_inst_count(cluster, 'oozie') dn_count = _get_inst_count(cluster, 'datanode') if oo_count not in [0, 1]: raise ex.InvalidComponentCountException('oozie', '0 or 1', oo_count) if oo_count == 1: if dn_count < 1: raise ex.RequiredServiceMissingException('datanode', required_by='oozie') if nm_count < 1: raise ex.RequiredServiceMissingException('nodemanager', required_by='oozie') if hs_count != 1: raise ex.RequiredServiceMissingException('historyserver', required_by='oozie') rep_factor = cu.get_config_value(pctx, 'HDFS', 'dfs.replication', cluster) if dn_count < rep_factor: raise ex.InvalidComponentCountException( 'datanode', rep_factor, dn_count, 'Number of datanodes must be not' ' less than dfs.replication.') def validate_additional_ng_scaling(cluster, additional): rm = vu.get_resourcemanager(cluster) scalable_processes = _get_scalable_processes() for ng_id in additional: ng = gu.get_by_id(cluster.node_groups, ng_id) if not set(ng.node_processes).issubset(scalable_processes): msg = "Vanilla plugin cannot scale nodegroup with processes: %s" raise ex.NodeGroupCannotBeScaled(ng.name, msg % ' '.join(ng.node_processes)) if not rm and 'nodemanager' in ng.node_processes: msg = ("Vanilla plugin cannot scale node group with processes " "which have no master-processes run in cluster") raise ex.NodeGroupCannotBeScaled(ng.name, msg) def validate_existing_ng_scaling(pctx, cluster, existing): scalable_processes = _get_scalable_processes() dn_to_delete = 0 for ng in cluster.node_groups: if ng.id in existing: if ng.count > existing[ng.id] and "datanode" in ng.node_processes: dn_to_delete += ng.count - existing[ng.id] if not set(ng.node_processes).issubset(scalable_processes): msg = ("Vanilla plugin cannot scale nodegroup " "with processes: %s") raise ex.NodeGroupCannotBeScaled( ng.name, msg % ' '.join(ng.node_processes)) dn_amount = len(vu.get_datanodes(cluster)) rep_factor = cu.get_config_value(pctx, 'HDFS', 'dfs.replication', cluster) if dn_to_delete > 0 and dn_amount - dn_to_delete < rep_factor: msg = ("Vanilla plugin cannot shrink cluster because it would be not " "enough nodes for replicas (replication factor is %s)") raise ex.ClusterCannotBeScaled( cluster.name, msg % rep_factor) def _get_scalable_processes(): return ['datanode', 'nodemanager'] def _get_inst_count(cluster, process): return sum([ng.count for ng in u.get_node_groups(cluster, process)])
true
true
f72cc0fbea74a83a8775b2c4a4948f97cf3aff29
5,959
py
Python
DeepReinforcementLearning/funcs.py
Christoper-Harvey/1st-Capstone
93630a4d5f4a2d939c8b5f74f11b5b33052e3f72
[ "MIT" ]
1
2019-06-13T13:11:52.000Z
2019-06-13T13:11:52.000Z
DeepReinforcementLearning/funcs.py
Christoper-Harvey/1st-Capstone
93630a4d5f4a2d939c8b5f74f11b5b33052e3f72
[ "MIT" ]
null
null
null
DeepReinforcementLearning/funcs.py
Christoper-Harvey/1st-Capstone
93630a4d5f4a2d939c8b5f74f11b5b33052e3f72
[ "MIT" ]
2
2019-04-30T19:14:11.000Z
2019-06-13T13:11:57.000Z
import numpy as np import random import loggers as lg from game import Game, GameState from model import Residual_CNN from agent import Agent, User import config def playMatchesBetweenVersions(env, run_version, player1version, player2version, EPISODES, logger, turns_until_tau0, goes_first = 0): if player1version == -1: player1 = User('player1', env.state_size, env.action_size) else: player1_NN = Residual_CNN(config.REG_CONST, config.LEARNING_RATE, env.input_shape, env.action_size, config.HIDDEN_CNN_LAYERS) if player1version > 0: player1_network = player1_NN.read(env.name, run_version, player1version) player1_NN.model.set_weights(player1_network.get_weights()) player1 = Agent('player1', env.state_size, env.action_size, config.p1_MCTS_SIMS, config.CPUCT, player1_NN) if player2version == -1: player2 = User('player2', env.state_size, env.action_size) else: player2_NN = Residual_CNN(config.REG_CONST, config.LEARNING_RATE, env.input_shape, env.action_size, config.HIDDEN_CNN_LAYERS) if player2version > 0: player2_network = player2_NN.read(env.name, run_version, player2version) player2_NN.model.set_weights(player2_network.get_weights()) player2 = Agent('player2', env.state_size, env.action_size, config.p2_MCTS_SIMS, config.CPUCT, player2_NN) scores, memory, points, sp_scores = playMatches(player1, player2, EPISODES, logger, turns_until_tau0, None, goes_first) return (scores, memory, points, sp_scores) def playMatches(player1, player2, EPISODES, logger, turns_until_tau0, memory = None, goes_first = 0): env = Game() scores = {player1.name:0, "drawn": 0, player2.name:0} sp_scores = {'sp':0, "drawn": 0, 'nsp':0} points = {player1.name:[], player2.name:[]} for e in range(EPISODES): logger.info('====================') logger.info('EPISODE %d OF %d', e+1, EPISODES) logger.info('====================') print (str(e+1) + ' ', end='') state = env.reset() done = 0 turn = 0 player1.mcts = None player2.mcts = None if goes_first == 0: player1Starts = random.randint(0,1) * 2 - 1 else: player1Starts = goes_first if player1Starts == 1: players = {1:{"agent": player1, "name":player1.name} , -1: {"agent": player2, "name":player2.name} } logger.info(player1.name + ' plays as X') else: players = {1:{"agent": player2, "name":player2.name} , -1: {"agent": player1, "name":player1.name} } logger.info(player2.name + ' plays as X') logger.info('--------------') env.gameState.render(logger) while done == 0: turn = turn + 1 #### Run the MCTS algo and return an action if turn < turns_until_tau0: action, pi, MCTS_value, NN_value = players[state.playerTurn]['agent'].act(state, 1) else: action, pi, MCTS_value, NN_value = players[state.playerTurn]['agent'].act(state, 0) if memory != None: ####Commit the move to memory memory.commit_stmemory(env.identities, state, pi) logger.info('action: %d', action) for r in range(env.grid_shape[0]): logger.info(['----' if x == 0 else '{0:.2f}'.format(np.round(x,2)) for x in pi[env.grid_shape[1]*r : (env.grid_shape[1]*r + env.grid_shape[1])]]) logger.info('MCTS perceived value for %s: %f', state.pieces[str(state.playerTurn)] ,np.round(MCTS_value,2)) logger.info('NN perceived value for %s: %f', state.pieces[str(state.playerTurn)] ,np.round(NN_value,2)) logger.info('====================') ### Do the action state, value, done, _ = env.step(action) #the value of the newState from the POV of the new playerTurn i.e. -1 if the previous player played a winning move env.gameState.render(logger) if done == 1: if memory != None: #### If the game is finished, assign the values correctly to the game moves for move in memory.stmemory: if move['playerTurn'] == state.playerTurn: move['value'] = value else: move['value'] = -value memory.commit_ltmemory() if value == 1: logger.info('%s WINS!', players[state.playerTurn]['name']) scores[players[state.playerTurn]['name']] = scores[players[state.playerTurn]['name']] + 1 if state.playerTurn == 1: sp_scores['sp'] = sp_scores['sp'] + 1 else: sp_scores['nsp'] = sp_scores['nsp'] + 1 elif value == -1: logger.info('%s WINS!', players[-state.playerTurn]['name']) scores[players[-state.playerTurn]['name']] = scores[players[-state.playerTurn]['name']] + 1 if state.playerTurn == 1: sp_scores['nsp'] = sp_scores['nsp'] + 1 else: sp_scores['sp'] = sp_scores['sp'] + 1 else: logger.info('DRAW...') scores['drawn'] = scores['drawn'] + 1 sp_scores['drawn'] = sp_scores['drawn'] + 1 pts = state.score points[players[state.playerTurn]['name']].append(pts[0]) points[players[-state.playerTurn]['name']].append(pts[1]) return (scores, memory, points, sp_scores)
41.096552
167
0.545058
import numpy as np import random import loggers as lg from game import Game, GameState from model import Residual_CNN from agent import Agent, User import config def playMatchesBetweenVersions(env, run_version, player1version, player2version, EPISODES, logger, turns_until_tau0, goes_first = 0): if player1version == -1: player1 = User('player1', env.state_size, env.action_size) else: player1_NN = Residual_CNN(config.REG_CONST, config.LEARNING_RATE, env.input_shape, env.action_size, config.HIDDEN_CNN_LAYERS) if player1version > 0: player1_network = player1_NN.read(env.name, run_version, player1version) player1_NN.model.set_weights(player1_network.get_weights()) player1 = Agent('player1', env.state_size, env.action_size, config.p1_MCTS_SIMS, config.CPUCT, player1_NN) if player2version == -1: player2 = User('player2', env.state_size, env.action_size) else: player2_NN = Residual_CNN(config.REG_CONST, config.LEARNING_RATE, env.input_shape, env.action_size, config.HIDDEN_CNN_LAYERS) if player2version > 0: player2_network = player2_NN.read(env.name, run_version, player2version) player2_NN.model.set_weights(player2_network.get_weights()) player2 = Agent('player2', env.state_size, env.action_size, config.p2_MCTS_SIMS, config.CPUCT, player2_NN) scores, memory, points, sp_scores = playMatches(player1, player2, EPISODES, logger, turns_until_tau0, None, goes_first) return (scores, memory, points, sp_scores) def playMatches(player1, player2, EPISODES, logger, turns_until_tau0, memory = None, goes_first = 0): env = Game() scores = {player1.name:0, "drawn": 0, player2.name:0} sp_scores = {'sp':0, "drawn": 0, 'nsp':0} points = {player1.name:[], player2.name:[]} for e in range(EPISODES): logger.info('====================') logger.info('EPISODE %d OF %d', e+1, EPISODES) logger.info('====================') print (str(e+1) + ' ', end='') state = env.reset() done = 0 turn = 0 player1.mcts = None player2.mcts = None if goes_first == 0: player1Starts = random.randint(0,1) * 2 - 1 else: player1Starts = goes_first if player1Starts == 1: players = {1:{"agent": player1, "name":player1.name} , -1: {"agent": player2, "name":player2.name} } logger.info(player1.name + ' plays as X') else: players = {1:{"agent": player2, "name":player2.name} , -1: {"agent": player1, "name":player1.name} } logger.info(player2.name + ' plays as X') logger.info('--------------') env.gameState.render(logger) while done == 0: turn = turn + 1 t'].act(state, 1) else: action, pi, MCTS_value, NN_value = players[state.playerTurn]['agent'].act(state, 0) if memory != None: logger.info('action: %d', action) for r in range(env.grid_shape[0]): logger.info(['----' if x == 0 else '{0:.2f}'.format(np.round(x,2)) for x in pi[env.grid_shape[1]*r : (env.grid_shape[1]*r + env.grid_shape[1])]]) logger.info('MCTS perceived value for %s: %f', state.pieces[str(state.playerTurn)] ,np.round(MCTS_value,2)) logger.info('NN perceived value for %s: %f', state.pieces[str(state.playerTurn)] ,np.round(NN_value,2)) logger.info('====================') , _ = env.step(action) env.gameState.render(logger) if done == 1: if memory != None: move['value'] = -value memory.commit_ltmemory() if value == 1: logger.info('%s WINS!', players[state.playerTurn]['name']) scores[players[state.playerTurn]['name']] = scores[players[state.playerTurn]['name']] + 1 if state.playerTurn == 1: sp_scores['sp'] = sp_scores['sp'] + 1 else: sp_scores['nsp'] = sp_scores['nsp'] + 1 elif value == -1: logger.info('%s WINS!', players[-state.playerTurn]['name']) scores[players[-state.playerTurn]['name']] = scores[players[-state.playerTurn]['name']] + 1 if state.playerTurn == 1: sp_scores['nsp'] = sp_scores['nsp'] + 1 else: sp_scores['sp'] = sp_scores['sp'] + 1 else: logger.info('DRAW...') scores['drawn'] = scores['drawn'] + 1 sp_scores['drawn'] = sp_scores['drawn'] + 1 pts = state.score points[players[state.playerTurn]['name']].append(pts[0]) points[players[-state.playerTurn]['name']].append(pts[1]) return (scores, memory, points, sp_scores)
true
true
f72cc221951afaa2a1888c4d748a5068c84f56dc
3,916
py
Python
topasgraphsim/src/functions/dp.py
sebasj13/topas-create-graphs
5ccdbcbbe39461917cc015aa59805e518421431c
[ "MIT" ]
1
2021-12-20T10:56:40.000Z
2021-12-20T10:56:40.000Z
topasgraphsim/src/functions/dp.py
sebasj13/topas-create-graphs
5ccdbcbbe39461917cc015aa59805e518421431c
[ "MIT" ]
null
null
null
topasgraphsim/src/functions/dp.py
sebasj13/topas-create-graphs
5ccdbcbbe39461917cc015aa59805e518421431c
[ "MIT" ]
1
2021-12-26T06:29:22.000Z
2021-12-26T06:29:22.000Z
import numpy as np import scipy.integrate as integrate import scipy.interpolate as interpolate def calculate_parameters(axis, dose, cax=False): """ A function to calculate the relevant descriptive parameters of dose profiles. """ interpolated_axis = np.linspace(axis[0], axis[-1], len(axis) * 100) akima_dose_interpolator = interpolate.Akima1DInterpolator(axis, dose) interpolated_dose = np.flip(akima_dose_interpolator.__call__(interpolated_axis)) D0 = ( interpolated_dose[int(len(interpolated_dose) / 2)] + interpolated_dose[int(len(interpolated_dose) / 2) - 1] ) / 2 XL20 = interpolated_axis[: int(len(interpolated_axis) / 2)][ ( np.abs( interpolated_dose[: int(len(interpolated_axis) / 2)] - 0.2 * max(dose) ) ).argmin() ] XL50 = interpolated_axis[: int(len(interpolated_axis) / 2)][ ( np.abs( interpolated_dose[: int(len(interpolated_axis) / 2)] - 0.5 * max(dose) ) ).argmin() ] XL80 = interpolated_axis[: int(len(interpolated_axis) / 2)][ ( np.abs( interpolated_dose[: int(len(interpolated_axis) / 2)] - 0.8 * max(dose) ) ).argmin() ] XR20 = interpolated_axis[int(len(interpolated_axis) / 2) :][ ( np.abs( interpolated_dose[ int(len(interpolated_axis) / 2) : len(interpolated_axis) ] - 0.2 * max(dose) ) ).argmin() ] XR50 = interpolated_axis[int(len(interpolated_axis) / 2) :][ ( np.abs( interpolated_dose[ int(len(interpolated_axis) / 2) : len(interpolated_axis) ] - 0.5 * max(dose) ) ).argmin() ] XR80 = interpolated_axis[int(len(interpolated_axis) / 2) :][ ( np.abs( interpolated_dose[ int(len(interpolated_axis) / 2) : len(interpolated_axis) ] - 0.8 * max(dose) ) ).argmin() ] HWB = round(abs(XR50 - XL50), 3) CAXdev = round(XL50 + 0.5 * HWB, 3) Dose80 = [value for value in dose if value >= 0.8 * max(dose)] if cax == True: return CAXdev flat_krieger = round( max([value for value in dose if value >= 0.95 * max(dose)]) - min([value for value in dose if value >= 0.95 * max(dose)]) / D0, 5, ) flat_stddev = round(np.std(Dose80), 3) if len(Dose80) % 2 != 0: Dose80 = ( Dose80[0 : int(len(Dose80) / 2)] + Dose80[int(len(Dose80) / 2) + 1 : len(Dose80)] ) S = round( max( [Dose80[i - 1] / Dose80[len(Dose80) - i] for i in range(1, len(Dose80) + 1)] ), 3, ) Lpenumbra = round(abs(XL80 - XL20 + CAXdev), 3) Rpenumbra = round(abs(XR80 - XR20 + CAXdev), 3) XL20index = np.where(interpolated_axis == XL20)[0][0] XL80index = np.where(interpolated_axis == XL80)[0][0] XR20index = np.where(interpolated_axis == XR20)[0][0] XR80index = np.where(interpolated_axis == XR80)[0][0] Lintegral = round( abs( integrate.simps( interpolated_dose[XL20index:XL80index], interpolated_axis[XL20index:XL80index], ) ), 3, ) Rintegral = round( abs( integrate.simps( interpolated_dose[XR80index:XR20index], interpolated_axis[XR80index:XR20index], ) ), 3, ) if CAXdev > 150: raise Exception return [ HWB, CAXdev, flat_krieger, flat_stddev, S, Lpenumbra, Rpenumbra, Lintegral, Rintegral, ]
27.77305
88
0.516854
import numpy as np import scipy.integrate as integrate import scipy.interpolate as interpolate def calculate_parameters(axis, dose, cax=False): interpolated_axis = np.linspace(axis[0], axis[-1], len(axis) * 100) akima_dose_interpolator = interpolate.Akima1DInterpolator(axis, dose) interpolated_dose = np.flip(akima_dose_interpolator.__call__(interpolated_axis)) D0 = ( interpolated_dose[int(len(interpolated_dose) / 2)] + interpolated_dose[int(len(interpolated_dose) / 2) - 1] ) / 2 XL20 = interpolated_axis[: int(len(interpolated_axis) / 2)][ ( np.abs( interpolated_dose[: int(len(interpolated_axis) / 2)] - 0.2 * max(dose) ) ).argmin() ] XL50 = interpolated_axis[: int(len(interpolated_axis) / 2)][ ( np.abs( interpolated_dose[: int(len(interpolated_axis) / 2)] - 0.5 * max(dose) ) ).argmin() ] XL80 = interpolated_axis[: int(len(interpolated_axis) / 2)][ ( np.abs( interpolated_dose[: int(len(interpolated_axis) / 2)] - 0.8 * max(dose) ) ).argmin() ] XR20 = interpolated_axis[int(len(interpolated_axis) / 2) :][ ( np.abs( interpolated_dose[ int(len(interpolated_axis) / 2) : len(interpolated_axis) ] - 0.2 * max(dose) ) ).argmin() ] XR50 = interpolated_axis[int(len(interpolated_axis) / 2) :][ ( np.abs( interpolated_dose[ int(len(interpolated_axis) / 2) : len(interpolated_axis) ] - 0.5 * max(dose) ) ).argmin() ] XR80 = interpolated_axis[int(len(interpolated_axis) / 2) :][ ( np.abs( interpolated_dose[ int(len(interpolated_axis) / 2) : len(interpolated_axis) ] - 0.8 * max(dose) ) ).argmin() ] HWB = round(abs(XR50 - XL50), 3) CAXdev = round(XL50 + 0.5 * HWB, 3) Dose80 = [value for value in dose if value >= 0.8 * max(dose)] if cax == True: return CAXdev flat_krieger = round( max([value for value in dose if value >= 0.95 * max(dose)]) - min([value for value in dose if value >= 0.95 * max(dose)]) / D0, 5, ) flat_stddev = round(np.std(Dose80), 3) if len(Dose80) % 2 != 0: Dose80 = ( Dose80[0 : int(len(Dose80) / 2)] + Dose80[int(len(Dose80) / 2) + 1 : len(Dose80)] ) S = round( max( [Dose80[i - 1] / Dose80[len(Dose80) - i] for i in range(1, len(Dose80) + 1)] ), 3, ) Lpenumbra = round(abs(XL80 - XL20 + CAXdev), 3) Rpenumbra = round(abs(XR80 - XR20 + CAXdev), 3) XL20index = np.where(interpolated_axis == XL20)[0][0] XL80index = np.where(interpolated_axis == XL80)[0][0] XR20index = np.where(interpolated_axis == XR20)[0][0] XR80index = np.where(interpolated_axis == XR80)[0][0] Lintegral = round( abs( integrate.simps( interpolated_dose[XL20index:XL80index], interpolated_axis[XL20index:XL80index], ) ), 3, ) Rintegral = round( abs( integrate.simps( interpolated_dose[XR80index:XR20index], interpolated_axis[XR80index:XR20index], ) ), 3, ) if CAXdev > 150: raise Exception return [ HWB, CAXdev, flat_krieger, flat_stddev, S, Lpenumbra, Rpenumbra, Lintegral, Rintegral, ]
true
true
f72cc242a75bff056fc4182f50f291db178b0519
5,780
py
Python
sonarqube/community/user_groups.py
0x646e78/python-sonarqube-api
c641ab4dd180b4184f2663bd28277aa796b36417
[ "MIT" ]
null
null
null
sonarqube/community/user_groups.py
0x646e78/python-sonarqube-api
c641ab4dd180b4184f2663bd28277aa796b36417
[ "MIT" ]
null
null
null
sonarqube/community/user_groups.py
0x646e78/python-sonarqube-api
c641ab4dd180b4184f2663bd28277aa796b36417
[ "MIT" ]
null
null
null
#!/usr/bin/env python # -*- coding:utf-8 -*- # @Author: Jialiang Shi from sonarqube.utils.rest_client import RestClient from sonarqube.utils.config import ( API_USER_GROUPS_SEARCH_ENDPOINT, API_USER_GROUPS_CREATE_ENDPOINT, API_USER_GROUPS_DELETE_ENDPOINT, API_USER_GROUPS_UPDATE_ENDPOINT, API_USER_GROUPS_USERS_ENDPOINT, API_USER_GROUPS_ADD_USER_ENDPOINT, API_USER_GROUPS_REMOVE_USER_ENDPOINT ) class SonarQubeUserGroups(RestClient): """ SonarQube user_groups Operations """ def __init__(self, **kwargs): """ :param kwargs: """ super(SonarQubeUserGroups, self).__init__(**kwargs) def __getitem__(self, name): result = list(self.search_user_groups(q=name)) for group in result: if group['name'] == name: return group def search_user_groups(self, fields=None, q=None): """ Search for user groups. :param fields: Comma-separated list of the fields to be returned in response. All the fields are returned by default. Possible values are for: * name * description * membersCount :param q: Limit search to names that contain the supplied string. :return: """ params = {} if fields: params.update({"f": fields}) page_num = 1 page_size = 1 total = 2 if q: params['q'] = q while page_num * page_size < total: resp = self.get(API_USER_GROUPS_SEARCH_ENDPOINT, params=params) response = resp.json() page_num = response['paging']['pageIndex'] page_size = response['paging']['pageSize'] total = response['paging']['total'] params['p'] = page_num + 1 for group in response['groups']: yield group def create_group(self, group_name, description=None): """ Create a group. :param group_name: Name for the new group. A group name cannot be larger than 255 characters and must be unique. The value 'anyone' (whatever the case) is reserved and cannot be used. :param description: Description for the new group. A group description cannot be larger than 200 characters. :return: request response """ params = { 'name': group_name } if description: params.update({'description': description}) return self.post(API_USER_GROUPS_CREATE_ENDPOINT, params=params) def delete_group(self, group_name): """ Delete a group. The default groups cannot be deleted. :param group_name: :return: """ params = { 'name': group_name } self.post(API_USER_GROUPS_DELETE_ENDPOINT, params=params) def update_group(self, group_id, group_name=None, description=None): """ Update a group. :param group_id: Identifier of the group. :param group_name: New optional name for the group. A group name cannot be larger than 255 characters and must be unique. Value 'anyone' (whatever the case) is reserved and cannot be used. If value is empty or not defined, then name is not changed. :param description: New optional description for the group. A group description cannot be larger than 200 characters. If value is not defined, then description is not changed. :return: """ params = {'id': group_id} if group_name: params.update({'name': group_name}) if description: params.update({'description': description}) self.post(API_USER_GROUPS_UPDATE_ENDPOINT, params=params) def add_user_to_group(self, group_name, user_login): """ Add a user to a group. :param group_name: Group name :param user_login: User login :return: """ params = { 'login': user_login, 'name': group_name } self.post(API_USER_GROUPS_ADD_USER_ENDPOINT, params=params) def remove_user_from_group(self, group_name, user_login): """ Remove a user from a group. :param group_name: Group name :param user_login: User login :return: """ params = { 'login': user_login, 'name': group_name } self.post(API_USER_GROUPS_REMOVE_USER_ENDPOINT, params=params) def search_users_belong_to_group(self, group_name, q=None, selected="selected"): """ Search for users with membership information with respect to a group. :param group_name: Group name :param q: Limit search to names or logins that contain the supplied string. :param selected: Depending on the value, show only selected items (selected=selected), deselected items (selected=deselected), or all items with their selection status (selected=all).Possible values are for: * all * deselected * selected default value is selected. :return: """ params = { 'name': group_name, 'selected': selected } page_num = 1 page_size = 1 total = 2 if q: params.update({'q': q}) while page_num * page_size < total: resp = self.get(API_USER_GROUPS_USERS_ENDPOINT, params=params) response = resp.json() page_num = response['p'] page_size = response['ps'] total = response['total'] params['p'] = page_num + 1 for user in response['users']: yield user
30.582011
120
0.59654
from sonarqube.utils.rest_client import RestClient from sonarqube.utils.config import ( API_USER_GROUPS_SEARCH_ENDPOINT, API_USER_GROUPS_CREATE_ENDPOINT, API_USER_GROUPS_DELETE_ENDPOINT, API_USER_GROUPS_UPDATE_ENDPOINT, API_USER_GROUPS_USERS_ENDPOINT, API_USER_GROUPS_ADD_USER_ENDPOINT, API_USER_GROUPS_REMOVE_USER_ENDPOINT ) class SonarQubeUserGroups(RestClient): def __init__(self, **kwargs): super(SonarQubeUserGroups, self).__init__(**kwargs) def __getitem__(self, name): result = list(self.search_user_groups(q=name)) for group in result: if group['name'] == name: return group def search_user_groups(self, fields=None, q=None): params = {} if fields: params.update({"f": fields}) page_num = 1 page_size = 1 total = 2 if q: params['q'] = q while page_num * page_size < total: resp = self.get(API_USER_GROUPS_SEARCH_ENDPOINT, params=params) response = resp.json() page_num = response['paging']['pageIndex'] page_size = response['paging']['pageSize'] total = response['paging']['total'] params['p'] = page_num + 1 for group in response['groups']: yield group def create_group(self, group_name, description=None): params = { 'name': group_name } if description: params.update({'description': description}) return self.post(API_USER_GROUPS_CREATE_ENDPOINT, params=params) def delete_group(self, group_name): params = { 'name': group_name } self.post(API_USER_GROUPS_DELETE_ENDPOINT, params=params) def update_group(self, group_id, group_name=None, description=None): params = {'id': group_id} if group_name: params.update({'name': group_name}) if description: params.update({'description': description}) self.post(API_USER_GROUPS_UPDATE_ENDPOINT, params=params) def add_user_to_group(self, group_name, user_login): params = { 'login': user_login, 'name': group_name } self.post(API_USER_GROUPS_ADD_USER_ENDPOINT, params=params) def remove_user_from_group(self, group_name, user_login): params = { 'login': user_login, 'name': group_name } self.post(API_USER_GROUPS_REMOVE_USER_ENDPOINT, params=params) def search_users_belong_to_group(self, group_name, q=None, selected="selected"): params = { 'name': group_name, 'selected': selected } page_num = 1 page_size = 1 total = 2 if q: params.update({'q': q}) while page_num * page_size < total: resp = self.get(API_USER_GROUPS_USERS_ENDPOINT, params=params) response = resp.json() page_num = response['p'] page_size = response['ps'] total = response['total'] params['p'] = page_num + 1 for user in response['users']: yield user
true
true
f72cc2a756c43756ba71fb67aa4ae3e1efa74f2f
5,550
py
Python
userbot/modules/locks.py
RiSecID/Auto
d06ef712666a35ddbf0c123dbb86705096cbbb56
[ "Naumen", "Condor-1.1", "MS-PL" ]
1
2020-04-10T13:11:46.000Z
2020-04-10T13:11:46.000Z
userbot/modules/locks.py
RiSecID/Auto
d06ef712666a35ddbf0c123dbb86705096cbbb56
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
userbot/modules/locks.py
RiSecID/Auto
d06ef712666a35ddbf0c123dbb86705096cbbb56
[ "Naumen", "Condor-1.1", "MS-PL" ]
1
2020-12-02T14:59:04.000Z
2020-12-02T14:59:04.000Z
# Copyright (C) 2019 The Raphielscape Company LLC. # # Licensed under the Raphielscape Public License, Version 1.c (the "License"); # you may not use this file except in compliance with the License. from telethon.tl.functions.messages import EditChatDefaultBannedRightsRequest from telethon.tl.types import ChatBannedRights from userbot import CMD_HELP from userbot.events import register @register(outgoing=True, pattern=r"^.lock ?(.*)") async def locks(event): input_str = event.pattern_match.group(1).lower() peer_id = event.chat_id msg = None media = None sticker = None gif = None gamee = None ainline = None gpoll = None adduser = None cpin = None changeinfo = None if input_str == "msg": msg = True what = "messages" elif input_str == "media": media = True what = "media" elif input_str == "sticker": sticker = True what = "stickers" elif input_str == "gif": gif = True what = "GIFs" elif input_str == "game": gamee = True what = "games" elif input_str == "inline": ainline = True what = "inline bots" elif input_str == "poll": gpoll = True what = "polls" elif input_str == "invite": adduser = True what = "invites" elif input_str == "pin": cpin = True what = "pins" elif input_str == "info": changeinfo = True what = "chat info" elif input_str == "all": msg = True media = True sticker = True gif = True gamee = True ainline = True gpoll = True adduser = True cpin = True changeinfo = True what = "everything" else: if not input_str: return await event.edit("`I can't lock nothing !!`") else: return await event.edit(f"`Invalid lock type:` {input_str}") lock_rights = ChatBannedRights( until_date=None, send_messages=msg, send_media=media, send_stickers=sticker, send_gifs=gif, send_games=gamee, send_inline=ainline, send_polls=gpoll, invite_users=adduser, pin_messages=cpin, change_info=changeinfo, ) try: await event.client( EditChatDefaultBannedRightsRequest(peer=peer_id, banned_rights=lock_rights)) await event.edit(f"`Locked {what} for this chat !!`") except BaseException as e: return await event.edit( f"`Do I have proper rights for that ??`\n**Error:** {str(e)}") @register(outgoing=True, pattern=r"^.unlock ?(.*)") async def rem_locks(event): input_str = event.pattern_match.group(1).lower() peer_id = event.chat_id msg = None media = None sticker = None gif = None gamee = None ainline = None gpoll = None adduser = None cpin = None changeinfo = None if input_str == "msg": msg = False what = "messages" elif input_str == "media": media = False what = "media" elif input_str == "sticker": sticker = False what = "stickers" elif input_str == "gif": gif = False what = "GIFs" elif input_str == "game": gamee = False what = "games" elif input_str == "inline": ainline = False what = "inline bots" elif input_str == "poll": gpoll = False what = "polls" elif input_str == "invite": adduser = False what = "invites" elif input_str == "pin": cpin = False what = "pins" elif input_str == "info": changeinfo = False what = "chat info" elif input_str == "all": msg = False media = False sticker = False gif = False gamee = False ainline = False gpoll = False adduser = False cpin = False changeinfo = False what = "everything" else: if not input_str: return await event.edit("`I can't unlock nothing !!`") else: return await event.edit(f"`Invalid unlock type:` {input_str}") unlock_rights = ChatBannedRights( until_date=None, send_messages=msg, send_media=media, send_stickers=sticker, send_gifs=gif, send_games=gamee, send_inline=ainline, send_polls=gpoll, invite_users=adduser, pin_messages=cpin, change_info=changeinfo, ) try: await event.client( EditChatDefaultBannedRightsRequest(peer=peer_id, banned_rights=unlock_rights)) await event.edit(f"`Unlocked {what} for this chat !!`") except BaseException as e: return await event.edit( f"`Do I have proper rights for that ??`\n**Error:** {str(e)}") CMD_HELP.update({ "locks": ">`.lock <all (or) type(s)>` or >`.unlock <all (or) type(s)>`" "\nUsage: Allows you to lock/unlock some common message types in the chat." "\n[NOTE: Requires proper admin rights in the chat !!]" "\n\nAvailable message types to lock/unlock are: " "\n`all, msg, media, sticker, gif, game, inline, poll, invite, pin, info`" })
29.057592
80
0.544505
from telethon.tl.functions.messages import EditChatDefaultBannedRightsRequest from telethon.tl.types import ChatBannedRights from userbot import CMD_HELP from userbot.events import register @register(outgoing=True, pattern=r"^.lock ?(.*)") async def locks(event): input_str = event.pattern_match.group(1).lower() peer_id = event.chat_id msg = None media = None sticker = None gif = None gamee = None ainline = None gpoll = None adduser = None cpin = None changeinfo = None if input_str == "msg": msg = True what = "messages" elif input_str == "media": media = True what = "media" elif input_str == "sticker": sticker = True what = "stickers" elif input_str == "gif": gif = True what = "GIFs" elif input_str == "game": gamee = True what = "games" elif input_str == "inline": ainline = True what = "inline bots" elif input_str == "poll": gpoll = True what = "polls" elif input_str == "invite": adduser = True what = "invites" elif input_str == "pin": cpin = True what = "pins" elif input_str == "info": changeinfo = True what = "chat info" elif input_str == "all": msg = True media = True sticker = True gif = True gamee = True ainline = True gpoll = True adduser = True cpin = True changeinfo = True what = "everything" else: if not input_str: return await event.edit("`I can't lock nothing !!`") else: return await event.edit(f"`Invalid lock type:` {input_str}") lock_rights = ChatBannedRights( until_date=None, send_messages=msg, send_media=media, send_stickers=sticker, send_gifs=gif, send_games=gamee, send_inline=ainline, send_polls=gpoll, invite_users=adduser, pin_messages=cpin, change_info=changeinfo, ) try: await event.client( EditChatDefaultBannedRightsRequest(peer=peer_id, banned_rights=lock_rights)) await event.edit(f"`Locked {what} for this chat !!`") except BaseException as e: return await event.edit( f"`Do I have proper rights for that ??`\n**Error:** {str(e)}") @register(outgoing=True, pattern=r"^.unlock ?(.*)") async def rem_locks(event): input_str = event.pattern_match.group(1).lower() peer_id = event.chat_id msg = None media = None sticker = None gif = None gamee = None ainline = None gpoll = None adduser = None cpin = None changeinfo = None if input_str == "msg": msg = False what = "messages" elif input_str == "media": media = False what = "media" elif input_str == "sticker": sticker = False what = "stickers" elif input_str == "gif": gif = False what = "GIFs" elif input_str == "game": gamee = False what = "games" elif input_str == "inline": ainline = False what = "inline bots" elif input_str == "poll": gpoll = False what = "polls" elif input_str == "invite": adduser = False what = "invites" elif input_str == "pin": cpin = False what = "pins" elif input_str == "info": changeinfo = False what = "chat info" elif input_str == "all": msg = False media = False sticker = False gif = False gamee = False ainline = False gpoll = False adduser = False cpin = False changeinfo = False what = "everything" else: if not input_str: return await event.edit("`I can't unlock nothing !!`") else: return await event.edit(f"`Invalid unlock type:` {input_str}") unlock_rights = ChatBannedRights( until_date=None, send_messages=msg, send_media=media, send_stickers=sticker, send_gifs=gif, send_games=gamee, send_inline=ainline, send_polls=gpoll, invite_users=adduser, pin_messages=cpin, change_info=changeinfo, ) try: await event.client( EditChatDefaultBannedRightsRequest(peer=peer_id, banned_rights=unlock_rights)) await event.edit(f"`Unlocked {what} for this chat !!`") except BaseException as e: return await event.edit( f"`Do I have proper rights for that ??`\n**Error:** {str(e)}") CMD_HELP.update({ "locks": ">`.lock <all (or) type(s)>` or >`.unlock <all (or) type(s)>`" "\nUsage: Allows you to lock/unlock some common message types in the chat." "\n[NOTE: Requires proper admin rights in the chat !!]" "\n\nAvailable message types to lock/unlock are: " "\n`all, msg, media, sticker, gif, game, inline, poll, invite, pin, info`" })
true
true
f72cc345255307326cc2305d9c1b218b5b5aeb6d
4,044
py
Python
qa/rpc-tests/merkle_blocks.py
cryptoandcoffee/DCUMN
85b873a90b3a2df6870d7ea74ea5087945e238bb
[ "MIT" ]
null
null
null
qa/rpc-tests/merkle_blocks.py
cryptoandcoffee/DCUMN
85b873a90b3a2df6870d7ea74ea5087945e238bb
[ "MIT" ]
null
null
null
qa/rpc-tests/merkle_blocks.py
cryptoandcoffee/DCUMN
85b873a90b3a2df6870d7ea74ea5087945e238bb
[ "MIT" ]
null
null
null
#!/usr/bin/env python2 # Copyright (c) 2014-2015 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # # Test merkleblock fetch/validation # from test_framework.test_framework import DCUTestFramework from test_framework.util import * class MerkleBlockTest(DCUTestFramework): def setup_chain(self): print("Initializing test directory "+self.options.tmpdir) initialize_chain_clean(self.options.tmpdir, 4) def setup_network(self): self.nodes = [] # Nodes 0/1 are "wallet" nodes self.nodes.append(start_node(0, self.options.tmpdir, ["-debug"])) self.nodes.append(start_node(1, self.options.tmpdir, ["-debug"])) # Nodes 2/3 are used for testing self.nodes.append(start_node(2, self.options.tmpdir, ["-debug"])) self.nodes.append(start_node(3, self.options.tmpdir, ["-debug", "-txindex"])) connect_nodes(self.nodes[0], 1) connect_nodes(self.nodes[0], 2) connect_nodes(self.nodes[0], 3) self.is_network_split = False self.sync_all() def run_test(self): print "Mining blocks..." self.nodes[0].generate(105) self.sync_all() chain_height = self.nodes[1].getblockcount() assert_equal(chain_height, 105) assert_equal(self.nodes[1].getbalance(), 0) assert_equal(self.nodes[2].getbalance(), 0) node0utxos = self.nodes[0].listunspent(1) tx1 = self.nodes[0].createrawtransaction([node0utxos.pop()], {self.nodes[1].getnewaddress(): 500}) txid1 = self.nodes[0].sendrawtransaction(self.nodes[0].signrawtransaction(tx1)["hex"]) tx2 = self.nodes[0].createrawtransaction([node0utxos.pop()], {self.nodes[1].getnewaddress(): 500}) txid2 = self.nodes[0].sendrawtransaction(self.nodes[0].signrawtransaction(tx2)["hex"]) assert_raises(JSONRPCException, self.nodes[0].gettxoutproof, [txid1]) self.nodes[0].generate(1) blockhash = self.nodes[0].getblockhash(chain_height + 1) self.sync_all() txlist = [] blocktxn = self.nodes[0].getblock(blockhash, True)["tx"] txlist.append(blocktxn[1]) txlist.append(blocktxn[2]) assert_equal(self.nodes[2].verifytxoutproof(self.nodes[2].gettxoutproof([txid1])), [txid1]) assert_equal(self.nodes[2].verifytxoutproof(self.nodes[2].gettxoutproof([txid1, txid2])), txlist) assert_equal(self.nodes[2].verifytxoutproof(self.nodes[2].gettxoutproof([txid1, txid2], blockhash)), txlist) txin_spent = self.nodes[1].listunspent(1).pop() tx3 = self.nodes[1].createrawtransaction([txin_spent], {self.nodes[0].getnewaddress(): 500}) self.nodes[0].sendrawtransaction(self.nodes[1].signrawtransaction(tx3)["hex"]) self.nodes[0].generate(1) self.sync_all() txid_spent = txin_spent["txid"] txid_unspent = txid1 if txin_spent["txid"] != txid1 else txid2 # We can't find the block from a fully-spent tx # Doesn't apply to DCU Core - we have txindex always on # assert_raises(JSONRPCException, self.nodes[2].gettxoutproof, [txid_spent]) # ...but we can if we specify the block assert_equal(self.nodes[2].verifytxoutproof(self.nodes[2].gettxoutproof([txid_spent], blockhash)), [txid_spent]) # ...or if the first tx is not fully-spent assert_equal(self.nodes[2].verifytxoutproof(self.nodes[2].gettxoutproof([txid_unspent])), [txid_unspent]) try: assert_equal(self.nodes[2].verifytxoutproof(self.nodes[2].gettxoutproof([txid1, txid2])), txlist) except JSONRPCException: assert_equal(self.nodes[2].verifytxoutproof(self.nodes[2].gettxoutproof([txid2, txid1])), txlist) # ...or if we have a -txindex assert_equal(self.nodes[2].verifytxoutproof(self.nodes[3].gettxoutproof([txid_spent])), [txid_spent]) if __name__ == '__main__': MerkleBlockTest().main()
45.438202
120
0.670623
from test_framework.test_framework import DCUTestFramework from test_framework.util import * class MerkleBlockTest(DCUTestFramework): def setup_chain(self): print("Initializing test directory "+self.options.tmpdir) initialize_chain_clean(self.options.tmpdir, 4) def setup_network(self): self.nodes = [] self.nodes.append(start_node(0, self.options.tmpdir, ["-debug"])) self.nodes.append(start_node(1, self.options.tmpdir, ["-debug"])) self.nodes.append(start_node(2, self.options.tmpdir, ["-debug"])) self.nodes.append(start_node(3, self.options.tmpdir, ["-debug", "-txindex"])) connect_nodes(self.nodes[0], 1) connect_nodes(self.nodes[0], 2) connect_nodes(self.nodes[0], 3) self.is_network_split = False self.sync_all() def run_test(self): print "Mining blocks..." self.nodes[0].generate(105) self.sync_all() chain_height = self.nodes[1].getblockcount() assert_equal(chain_height, 105) assert_equal(self.nodes[1].getbalance(), 0) assert_equal(self.nodes[2].getbalance(), 0) node0utxos = self.nodes[0].listunspent(1) tx1 = self.nodes[0].createrawtransaction([node0utxos.pop()], {self.nodes[1].getnewaddress(): 500}) txid1 = self.nodes[0].sendrawtransaction(self.nodes[0].signrawtransaction(tx1)["hex"]) tx2 = self.nodes[0].createrawtransaction([node0utxos.pop()], {self.nodes[1].getnewaddress(): 500}) txid2 = self.nodes[0].sendrawtransaction(self.nodes[0].signrawtransaction(tx2)["hex"]) assert_raises(JSONRPCException, self.nodes[0].gettxoutproof, [txid1]) self.nodes[0].generate(1) blockhash = self.nodes[0].getblockhash(chain_height + 1) self.sync_all() txlist = [] blocktxn = self.nodes[0].getblock(blockhash, True)["tx"] txlist.append(blocktxn[1]) txlist.append(blocktxn[2]) assert_equal(self.nodes[2].verifytxoutproof(self.nodes[2].gettxoutproof([txid1])), [txid1]) assert_equal(self.nodes[2].verifytxoutproof(self.nodes[2].gettxoutproof([txid1, txid2])), txlist) assert_equal(self.nodes[2].verifytxoutproof(self.nodes[2].gettxoutproof([txid1, txid2], blockhash)), txlist) txin_spent = self.nodes[1].listunspent(1).pop() tx3 = self.nodes[1].createrawtransaction([txin_spent], {self.nodes[0].getnewaddress(): 500}) self.nodes[0].sendrawtransaction(self.nodes[1].signrawtransaction(tx3)["hex"]) self.nodes[0].generate(1) self.sync_all() txid_spent = txin_spent["txid"] txid_unspent = txid1 if txin_spent["txid"] != txid1 else txid2 # Doesn't apply to DCU Core - we have txindex always on assert_equal(self.nodes[2].verifytxoutproof(self.nodes[2].gettxoutproof([txid_spent], blockhash)), [txid_spent]) assert_equal(self.nodes[2].verifytxoutproof(self.nodes[2].gettxoutproof([txid_unspent])), [txid_unspent]) try: assert_equal(self.nodes[2].verifytxoutproof(self.nodes[2].gettxoutproof([txid1, txid2])), txlist) except JSONRPCException: assert_equal(self.nodes[2].verifytxoutproof(self.nodes[2].gettxoutproof([txid2, txid1])), txlist) assert_equal(self.nodes[2].verifytxoutproof(self.nodes[3].gettxoutproof([txid_spent])), [txid_spent]) if __name__ == '__main__': MerkleBlockTest().main()
false
true
f72cc5c07d47e87c78a7d4236d54674e5f436c66
230
py
Python
pycones/sponsorship/managers.py
python-spain/PyConES2015
af78ad7f1d7df747a2f5428be87a5b061457dd24
[ "MIT" ]
null
null
null
pycones/sponsorship/managers.py
python-spain/PyConES2015
af78ad7f1d7df747a2f5428be87a5b061457dd24
[ "MIT" ]
null
null
null
pycones/sponsorship/managers.py
python-spain/PyConES2015
af78ad7f1d7df747a2f5428be87a5b061457dd24
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models class SponsorManager(models.Manager): def active(self): return self.get_query_set().filter(active=True).order_by("level")
23
73
0.726087
from __future__ import unicode_literals from django.db import models class SponsorManager(models.Manager): def active(self): return self.get_query_set().filter(active=True).order_by("level")
true
true
f72cc5f2ca3bea87b59576ba3da7939aab82e2af
116
py
Python
URI/1 - INICIANTE/Python/1759 - HoHoHo.py
william-james-pj/LogicaProgramacao
629f746e34da2e829dc7ea2e489ac36bb1b1fb13
[ "MIT" ]
1
2020-04-14T16:48:16.000Z
2020-04-14T16:48:16.000Z
URI/1 - INICIANTE/Python/1759 - HoHoHo.py
william-james-pj/LogicaProgramacao
629f746e34da2e829dc7ea2e489ac36bb1b1fb13
[ "MIT" ]
null
null
null
URI/1 - INICIANTE/Python/1759 - HoHoHo.py
william-james-pj/LogicaProgramacao
629f746e34da2e829dc7ea2e489ac36bb1b1fb13
[ "MIT" ]
null
null
null
n = int(input()) for y in range(0, n): if(y == n-1): print('Ho!') else: print('Ho', end=' ')
19.333333
28
0.413793
n = int(input()) for y in range(0, n): if(y == n-1): print('Ho!') else: print('Ho', end=' ')
true
true
f72cc73266bff2259d90cfeb4bc45a0cffcbecaf
834
py
Python
p22.py
kmark1625/Project-Euler
e80c4f2044fdbff93331117b8f02aa0becbb0706
[ "MIT" ]
null
null
null
p22.py
kmark1625/Project-Euler
e80c4f2044fdbff93331117b8f02aa0becbb0706
[ "MIT" ]
null
null
null
p22.py
kmark1625/Project-Euler
e80c4f2044fdbff93331117b8f02aa0becbb0706
[ "MIT" ]
null
null
null
def read_from_file(filename): txt = open(filename) string_of_names = txt.read() return string_of_names def string_of_names_to_array(string_of_names): return string_of_names.replace('"','').split(",") def get_alpha_value(string): sum = 0 for char in string: sum += (ord(char) - 64) return sum def main(): sum = 0 filename = "p022_names.txt" string_of_names = read_from_file(filename) array_of_names = string_of_names_to_array(string_of_names) array_of_names.sort() for i in range(0, len(array_of_names)): sum += (i+1) * get_alpha_value(array_of_names[i]) return sum def test_get_alpha_value(): assert get_alpha_value("COLIN") == 53 assert get_alpha_value("A") == 1 assert get_alpha_value("Z") == 26 def test(): test_get_alpha_value() if __name__ == '__main__': test() print main()
23.166667
60
0.708633
def read_from_file(filename): txt = open(filename) string_of_names = txt.read() return string_of_names def string_of_names_to_array(string_of_names): return string_of_names.replace('"','').split(",") def get_alpha_value(string): sum = 0 for char in string: sum += (ord(char) - 64) return sum def main(): sum = 0 filename = "p022_names.txt" string_of_names = read_from_file(filename) array_of_names = string_of_names_to_array(string_of_names) array_of_names.sort() for i in range(0, len(array_of_names)): sum += (i+1) * get_alpha_value(array_of_names[i]) return sum def test_get_alpha_value(): assert get_alpha_value("COLIN") == 53 assert get_alpha_value("A") == 1 assert get_alpha_value("Z") == 26 def test(): test_get_alpha_value() if __name__ == '__main__': test() print main()
false
true
f72cc8541c4c9a534a37b3d44f316d2620756960
973
py
Python
nengo/copter.py
simondlevy/gym-copter
7236769b7586b92026d4b47f12363258c84d9508
[ "MIT" ]
14
2019-11-03T05:17:46.000Z
2022-02-26T05:37:32.000Z
nengo/copter.py
simondlevy/gym-copter
7236769b7586b92026d4b47f12363258c84d9508
[ "MIT" ]
77
2020-05-17T01:56:29.000Z
2021-06-19T02:46:52.000Z
nengo/copter.py
simondlevy/gym-copter
7236769b7586b92026d4b47f12363258c84d9508
[ "MIT" ]
6
2020-01-01T07:22:15.000Z
2021-05-11T17:45:33.000Z
''' Quadcopter class for Nengo adaptive controller Copyright (C) 2021 Xuan Choo, Simon D. Levy MIT License ''' import nengo import gym import numpy as np from adaptive import run class Copter: def __init__(self, seed=None): self.env = gym.make('gym_copter:Hover1D-v0') self.reset(seed) def reset(self, seed): self.state = self.env.reset() def step(self, u): u = np.clip(u, 0, 1) self.env.render() z, dz, = self.state # Negate for NED => ENU z, dz = -z, -dz print('%f | %+3.3f %+3.3f' % (u, z, dz)) self.state, _reward, _done, _info = self.env.step((u,)) return z, dz def set_extra_force(self, force): self.extra_mass = force def generate_html(self, desired): ''' Copter is simulated externally ''' return None with nengo.Network(seed=3) as model: run(Copter, 'Copter', 'Position', 'Wind Force')
16.775862
63
0.572456
import nengo import gym import numpy as np from adaptive import run class Copter: def __init__(self, seed=None): self.env = gym.make('gym_copter:Hover1D-v0') self.reset(seed) def reset(self, seed): self.state = self.env.reset() def step(self, u): u = np.clip(u, 0, 1) self.env.render() z, dz, = self.state z, dz = -z, -dz print('%f | %+3.3f %+3.3f' % (u, z, dz)) self.state, _reward, _done, _info = self.env.step((u,)) return z, dz def set_extra_force(self, force): self.extra_mass = force def generate_html(self, desired): return None with nengo.Network(seed=3) as model: run(Copter, 'Copter', 'Position', 'Wind Force')
true
true
f72cc9142cb85a864de5beb77fe66a359cf63d16
18,754
py
Python
tools/sr_mapping/bfast_wrapper.py
ramezrawas/galaxy-1
c03748dd49c060a68d07bce56eae33e0ba154414
[ "CC-BY-3.0" ]
null
null
null
tools/sr_mapping/bfast_wrapper.py
ramezrawas/galaxy-1
c03748dd49c060a68d07bce56eae33e0ba154414
[ "CC-BY-3.0" ]
7
2016-12-07T22:19:37.000Z
2019-01-30T15:04:26.000Z
tools/sr_mapping/bfast_wrapper.py
ramezrawas/galaxy-1
c03748dd49c060a68d07bce56eae33e0ba154414
[ "CC-BY-3.0" ]
null
null
null
#!/usr/bin/env python """ Runs BFAST on single-end or paired-end data. TODO: more documentation TODO: - auto-detect gzip or bz2 - split options (?) - queue lengths (?) - assumes reference always has been indexed - main and secondary indexes - scoring matrix file ? - read group file ? usage: bfast_wrapper.py [options] -r, --ref=r: The reference genome to use or index -f, --fastq=f: The fastq file to use for the mapping -F, --output=u: The file to save the output (SAM format) -s, --fileSource=s: Whether to use a previously indexed reference sequence or one from history (indexed or history) -p, --params=p: Parameter setting to use (pre_set or full) -n, --numThreads=n: The number of threads to use -A, --space=A: The encoding space (0: base 1: color) -o, --offsets=o: The offsets for 'match' -l, --loadAllIndexes=l: Load all indexes into memory -k, --keySize=k: truncate key size in 'match' -K, --maxKeyMatches=K: the maximum number of matches to allow before a key is ignored -M, --maxNumMatches=M: the maximum number of matches to allow before the read is discarded -w, --whichStrand=w: the strands to consider (0: both 1: forward 2: reverse) -t, --timing=t: output timing information to stderr -u, --ungapped=u: performed ungapped local alignment -U, --unconstrained=U: performed local alignment without mask constraints -O, --offset=O: the number of bases before and after each hit to consider in local alignment -q, --avgMismatchQuality=q: average mismatch quality -a, --algorithm=a: post processing algorithm (0: no filtering, 1: all passing filters, 2: unique, 3: best scoring unique, 4: best score all) -P, --disallowPairing=P: do not choose alignments based on pairing -R, --reverse=R: paired end reads are given on reverse strands -z, --random=z: output a random best scoring alignment -D, --dbkey=D: Dbkey for reference genome -H, --suppressHeader=H: Suppress the sam header """ import optparse import os import shutil import subprocess import sys import tempfile def stop_err( msg ): sys.stderr.write( '%s\n' % msg ) sys.exit() def __main__(): parser = optparse.OptionParser() parser.add_option( '-r', '--ref', dest='ref', help='The reference genome to index and use' ) parser.add_option( '-f', '--fastq', dest='fastq', help='The fastq file to use for the mapping' ) parser.add_option( '-F', '--output', dest='output', help='The file to save the output (SAM format)' ) parser.add_option( '-A', '--space', dest='space', type="choice", default='0', choices=('0', '1'), help='The encoding space (0: base 1: color)' ) parser.add_option( '-H', '--suppressHeader', action="store_true", dest='suppressHeader', default=False, help='Suppress header' ) parser.add_option( '-n', '--numThreads', dest='numThreads', type="int", default="1", help='The number of threads to use' ) parser.add_option( '-t', '--timing', action="store_true", default=False, dest='timing', help='output timming information to stderr' ) parser.add_option( '-l', '--loadAllIndexes', action="store_true", default=False, dest='loadAllIndexes', help='Load all indexes into memory' ) parser.add_option( '-m', '--indexMask', dest='indexMask', help='String containing info on how to build custom indexes' ) parser.add_option( "-b", "--buildIndex", action="store_true", dest="buildIndex", default=False, help='String containing info on how to build custom indexes' ) parser.add_option( "--indexRepeatMasker", action="store_true", dest="indexRepeatMasker", default=False, help='Do not index lower case sequences. Such as those created by RepeatMasker' ) parser.add_option( '--indexContigOptions', dest='indexContigOptions', default="", help='The contig range options to use for the indexing' ) parser.add_option( '--indexExonsFileName', dest='indexExonsFileName', default="", help='The exons file to use for the indexing' ) parser.add_option( '-o', '--offsets', dest='offsets', default="", help='The offsets for \'match\'' ) parser.add_option( '-k', '--keySize', dest='keySize', type="int", default="-1", help='truncate key size in \'match\'' ) parser.add_option( '-K', '--maxKeyMatches', dest='maxKeyMatches', type="int", default="-1", help='the maximum number of matches to allow before a key is ignored' ) parser.add_option( '-M', '--maxNumMatches', dest='maxNumMatches', type="int", default="-1", help='the maximum number of matches to allow bfore the read is discarded' ) parser.add_option( '-w', '--whichStrand', dest='whichStrand', type="choice", default='0', choices=('0', '1', '2'), help='the strands to consider (0: both 1: forward 2: reverse)' ) parser.add_option( '--scoringMatrixFileName', dest='scoringMatrixFileName', help='Scoring Matrix file used to score the alignments' ) parser.add_option( '-u', '--ungapped', dest='ungapped', action="store_true", default=False, help='performed ungapped local alignment' ) parser.add_option( '-U', '--unconstrained', dest='unconstrained', action="store_true", default=False, help='performed local alignment without mask constraints' ) parser.add_option( '-O', '--offset', dest='offset', type="int", default="0", help='the number of bases before and after each hit to consider in local alignment' ) parser.add_option( '-q', '--avgMismatchQuality', type="int", default="-1", dest='avgMismatchQuality', help='average mismatch quality' ) parser.add_option( '-a', '--algorithm', dest='algorithm', default='0', type="choice", choices=('0', '1', '2', '3', '4'), help='post processing algorithm (0: no filtering, 1: all passing filters, 2: unique, 3: best scoring unique, 4: best score all' ) parser.add_option( '--unpaired', dest='unpaired', action="store_true", default=False, help='do not choose alignments based on pairing' ) parser.add_option( '--reverseStrand', dest='reverseStrand', action="store_true", default=False, help='paired end reads are given on reverse strands' ) parser.add_option( '--pairedEndInfer', dest='pairedEndInfer', action="store_true", default=False, help='break ties when one end of a paired end read by estimating the insert size distribution' ) parser.add_option( '--randomBest', dest='randomBest', action="store_true", default=False, help='output a random best scoring alignment' ) (options, args) = parser.parse_args() # output version # of tool try: tmp = tempfile.NamedTemporaryFile().name tmp_stdout = open( tmp, 'wb' ) proc = subprocess.Popen( args='bfast 2>&1', shell=True, stdout=tmp_stdout ) tmp_stdout.close() returncode = proc.wait() stdout = None for line in open( tmp_stdout.name, 'rb' ): if line.lower().find( 'version' ) >= 0: stdout = line.strip() break if stdout: sys.stdout.write( '%s\n' % stdout ) else: raise Exception except: sys.stdout.write( 'Could not determine BFAST version\n' ) buffsize = 1048576 # make temp directory for bfast, requires trailing slash tmp_dir = '%s/' % tempfile.mkdtemp() # 'generic' options used in all bfast commands here if options.timing: all_cmd_options = "-t" else: all_cmd_options = "" try: if options.buildIndex: reference_filepath = tempfile.NamedTemporaryFile( dir=tmp_dir, suffix='.fa' ).name # build bfast indexes os.symlink( options.ref, reference_filepath ) # bfast fast2brg try: nuc_space = [ "0" ] if options.space == "1": # color space localalign appears to require nuc space brg nuc_space.append( "1" ) for space in nuc_space: cmd = 'bfast fasta2brg -f "%s" -A "%s" %s' % ( reference_filepath, space, all_cmd_options ) tmp = tempfile.NamedTemporaryFile( dir=tmp_dir ).name tmp_stderr = open( tmp, 'wb' ) proc = subprocess.Popen( args=cmd, shell=True, cwd=tmp_dir, stderr=tmp_stderr.fileno() ) returncode = proc.wait() tmp_stderr.close() # get stderr, allowing for case where it's very large tmp_stderr = open( tmp, 'rb' ) stderr = '' try: while True: stderr += tmp_stderr.read( buffsize ) if not stderr or len( stderr ) % buffsize != 0: break except OverflowError: pass tmp_stderr.close() if returncode != 0: raise Exception(stderr) except Exception as e: raise Exception('Error in \'bfast fasta2brg\'.\n' + str( e )) # bfast index try: all_index_cmds = 'bfast index %s -f "%s" -A "%s" -n "%s"' % ( all_cmd_options, reference_filepath, options.space, options.numThreads ) if options.indexRepeatMasker: all_index_cmds += " -R" if options.indexContigOptions: index_contig_options = [ int(_) for _ in options.indexContigOptions.split( ',' ) ] if index_contig_options[0] >= 0: all_index_cmds += ' -s "%s"' % index_contig_options[0] if index_contig_options[1] >= 0: all_index_cmds += ' -S "%s"' % index_contig_options[1] if index_contig_options[2] >= 0: all_index_cmds += ' -e "%s"' % index_contig_options[2] if index_contig_options[3] >= 0: all_index_cmds += ' -E "%s"' % index_contig_options[3] elif options.indexExonsFileName: all_index_cmds += ' -x "%s"' % options.indexExonsFileName index_count = 1 for mask, hash_width in [ mask.split( ':' ) for mask in options.indexMask.split( ',' ) ]: cmd = '%s -m "%s" -w "%s" -i "%i"' % ( all_index_cmds, mask, hash_width, index_count ) tmp = tempfile.NamedTemporaryFile( dir=tmp_dir ).name tmp_stderr = open( tmp, 'wb' ) proc = subprocess.Popen( args=cmd, shell=True, cwd=tmp_dir, stderr=tmp_stderr.fileno() ) returncode = proc.wait() tmp_stderr.close() # get stderr, allowing for case where it's very large tmp_stderr = open( tmp, 'rb' ) stderr = '' try: while True: stderr += tmp_stderr.read( buffsize ) if not stderr or len( stderr ) % buffsize != 0: break except OverflowError: pass tmp_stderr.close() if returncode != 0: raise Exception(stderr) index_count += 1 except Exception as e: raise Exception('Error in \'bfast index\'.\n' + str( e )) else: reference_filepath = options.ref assert reference_filepath and os.path.exists( reference_filepath ), 'A valid genome reference was not provided.' # set up aligning and generate aligning command options # set up temp output files tmp_bmf = tempfile.NamedTemporaryFile( dir=tmp_dir ) tmp_bmf_name = tmp_bmf.name tmp_bmf.close() tmp_baf = tempfile.NamedTemporaryFile( dir=tmp_dir ) tmp_baf_name = tmp_baf.name tmp_baf.close() bfast_match_cmd = 'bfast match -f "%s" -r "%s" -n "%s" -A "%s" -T "%s" -w "%s" %s' % ( reference_filepath, options.fastq, options.numThreads, options.space, tmp_dir, options.whichStrand, all_cmd_options ) bfast_localalign_cmd = 'bfast localalign -f "%s" -m "%s" -n "%s" -A "%s" -o "%s" %s' % ( reference_filepath, tmp_bmf_name, options.numThreads, options.space, options.offset, all_cmd_options ) bfast_postprocess_cmd = 'bfast postprocess -O 1 -f "%s" -i "%s" -n "%s" -A "%s" -a "%s" %s' % ( reference_filepath, tmp_baf_name, options.numThreads, options.space, options.algorithm, all_cmd_options ) if options.offsets: bfast_match_cmd += ' -o "%s"' % options.offsets if options.keySize >= 0: bfast_match_cmd += ' -k "%s"' % options.keySize if options.maxKeyMatches >= 0: bfast_match_cmd += ' -K "%s"' % options.maxKeyMatches if options.maxNumMatches >= 0: bfast_match_cmd += ' -M "%s"' % options.maxNumMatches bfast_localalign_cmd += ' -M "%s"' % options.maxNumMatches if options.scoringMatrixFileName: bfast_localalign_cmd += ' -x "%s"' % options.scoringMatrixFileName bfast_postprocess_cmd += ' -x "%s"' % options.scoringMatrixFileName if options.ungapped: bfast_localalign_cmd += ' -u' if options.unconstrained: bfast_localalign_cmd += ' -U' if options.avgMismatchQuality >= 0: bfast_localalign_cmd += ' -q "%s"' % options.avgMismatchQuality bfast_postprocess_cmd += ' -q "%s"' % options.avgMismatchQuality if options.algorithm == 3: if options.pairedEndInfer: bfast_postprocess_cmd += ' -P' if options.randomBest: bfast_postprocess_cmd += ' -z' if options.unpaired: bfast_postprocess_cmd += ' -U' if options.reverseStrand: bfast_postprocess_cmd += ' -R' # instead of using temp files, should we stream through pipes? bfast_match_cmd += " > %s" % tmp_bmf_name bfast_localalign_cmd += " > %s" % tmp_baf_name bfast_postprocess_cmd += " > %s" % options.output # need to nest try-except in try-finally to handle 2.4 try: # bfast 'match' try: tmp = tempfile.NamedTemporaryFile( dir=tmp_dir ).name tmp_stderr = open( tmp, 'wb' ) proc = subprocess.Popen( args=bfast_match_cmd, shell=True, cwd=tmp_dir, stderr=tmp_stderr.fileno() ) returncode = proc.wait() tmp_stderr.close() # get stderr, allowing for case where it's very large tmp_stderr = open( tmp, 'rb' ) stderr = '' try: while True: stderr += tmp_stderr.read( buffsize ) if not stderr or len( stderr ) % buffsize != 0: break except OverflowError: pass tmp_stderr.close() if returncode != 0: raise Exception(stderr) except Exception as e: raise Exception('Error in \'bfast match\'. \n' + str( e )) # bfast 'localalign' try: tmp = tempfile.NamedTemporaryFile( dir=tmp_dir ).name tmp_stderr = open( tmp, 'wb' ) proc = subprocess.Popen( args=bfast_localalign_cmd, shell=True, cwd=tmp_dir, stderr=tmp_stderr.fileno() ) returncode = proc.wait() tmp_stderr.close() # get stderr, allowing for case where it's very large tmp_stderr = open( tmp, 'rb' ) stderr = '' try: while True: stderr += tmp_stderr.read( buffsize ) if not stderr or len( stderr ) % buffsize != 0: break except OverflowError: pass tmp_stderr.close() if returncode != 0: raise Exception(stderr) except Exception as e: raise Exception('Error in \'bfast localalign\'. \n' + str( e )) # bfast 'postprocess' try: tmp = tempfile.NamedTemporaryFile( dir=tmp_dir ).name tmp_stderr = open( tmp, 'wb' ) proc = subprocess.Popen( args=bfast_postprocess_cmd, shell=True, cwd=tmp_dir, stderr=tmp_stderr.fileno() ) returncode = proc.wait() tmp_stderr.close() # get stderr, allowing for case where it's very large tmp_stderr = open( tmp, 'rb' ) stderr = '' try: while True: stderr += tmp_stderr.read( buffsize ) if not stderr or len( stderr ) % buffsize != 0: break except OverflowError: pass tmp_stderr.close() if returncode != 0: raise Exception(stderr) except Exception as e: raise Exception('Error in \'bfast postprocess\'. \n' + str( e )) # remove header if necessary if options.suppressHeader: tmp_out = tempfile.NamedTemporaryFile( dir=tmp_dir) tmp_out_name = tmp_out.name tmp_out.close() try: shutil.move( options.output, tmp_out_name ) except Exception as e: raise Exception('Error moving output file before removing headers. \n' + str( e )) fout = open( options.output, 'w' ) for line in open( tmp_out.name, 'r' ): if len( line ) < 3 or line[0:3] not in [ '@HD', '@SQ', '@RG', '@PG', '@CO' ]: fout.write( line ) fout.close() # check that there are results in the output file if os.path.getsize( options.output ) > 0: if "0" == options.space: sys.stdout.write( 'BFAST run on Base Space data' ) else: sys.stdout.write( 'BFAST run on Color Space data' ) else: raise Exception('The output file is empty. You may simply have no matches, or there may be an error with your input file or settings.') except Exception as e: stop_err( 'The alignment failed.\n' + str( e ) ) finally: # clean up temp dir if os.path.exists( tmp_dir ): shutil.rmtree( tmp_dir ) if __name__ == "__main__": __main__()
53.430199
254
0.571878
import optparse import os import shutil import subprocess import sys import tempfile def stop_err( msg ): sys.stderr.write( '%s\n' % msg ) sys.exit() def __main__(): parser = optparse.OptionParser() parser.add_option( '-r', '--ref', dest='ref', help='The reference genome to index and use' ) parser.add_option( '-f', '--fastq', dest='fastq', help='The fastq file to use for the mapping' ) parser.add_option( '-F', '--output', dest='output', help='The file to save the output (SAM format)' ) parser.add_option( '-A', '--space', dest='space', type="choice", default='0', choices=('0', '1'), help='The encoding space (0: base 1: color)' ) parser.add_option( '-H', '--suppressHeader', action="store_true", dest='suppressHeader', default=False, help='Suppress header' ) parser.add_option( '-n', '--numThreads', dest='numThreads', type="int", default="1", help='The number of threads to use' ) parser.add_option( '-t', '--timing', action="store_true", default=False, dest='timing', help='output timming information to stderr' ) parser.add_option( '-l', '--loadAllIndexes', action="store_true", default=False, dest='loadAllIndexes', help='Load all indexes into memory' ) parser.add_option( '-m', '--indexMask', dest='indexMask', help='String containing info on how to build custom indexes' ) parser.add_option( "-b", "--buildIndex", action="store_true", dest="buildIndex", default=False, help='String containing info on how to build custom indexes' ) parser.add_option( "--indexRepeatMasker", action="store_true", dest="indexRepeatMasker", default=False, help='Do not index lower case sequences. Such as those created by RepeatMasker' ) parser.add_option( '--indexContigOptions', dest='indexContigOptions', default="", help='The contig range options to use for the indexing' ) parser.add_option( '--indexExonsFileName', dest='indexExonsFileName', default="", help='The exons file to use for the indexing' ) parser.add_option( '-o', '--offsets', dest='offsets', default="", help='The offsets for \'match\'' ) parser.add_option( '-k', '--keySize', dest='keySize', type="int", default="-1", help='truncate key size in \'match\'' ) parser.add_option( '-K', '--maxKeyMatches', dest='maxKeyMatches', type="int", default="-1", help='the maximum number of matches to allow before a key is ignored' ) parser.add_option( '-M', '--maxNumMatches', dest='maxNumMatches', type="int", default="-1", help='the maximum number of matches to allow bfore the read is discarded' ) parser.add_option( '-w', '--whichStrand', dest='whichStrand', type="choice", default='0', choices=('0', '1', '2'), help='the strands to consider (0: both 1: forward 2: reverse)' ) parser.add_option( '--scoringMatrixFileName', dest='scoringMatrixFileName', help='Scoring Matrix file used to score the alignments' ) parser.add_option( '-u', '--ungapped', dest='ungapped', action="store_true", default=False, help='performed ungapped local alignment' ) parser.add_option( '-U', '--unconstrained', dest='unconstrained', action="store_true", default=False, help='performed local alignment without mask constraints' ) parser.add_option( '-O', '--offset', dest='offset', type="int", default="0", help='the number of bases before and after each hit to consider in local alignment' ) parser.add_option( '-q', '--avgMismatchQuality', type="int", default="-1", dest='avgMismatchQuality', help='average mismatch quality' ) parser.add_option( '-a', '--algorithm', dest='algorithm', default='0', type="choice", choices=('0', '1', '2', '3', '4'), help='post processing algorithm (0: no filtering, 1: all passing filters, 2: unique, 3: best scoring unique, 4: best score all' ) parser.add_option( '--unpaired', dest='unpaired', action="store_true", default=False, help='do not choose alignments based on pairing' ) parser.add_option( '--reverseStrand', dest='reverseStrand', action="store_true", default=False, help='paired end reads are given on reverse strands' ) parser.add_option( '--pairedEndInfer', dest='pairedEndInfer', action="store_true", default=False, help='break ties when one end of a paired end read by estimating the insert size distribution' ) parser.add_option( '--randomBest', dest='randomBest', action="store_true", default=False, help='output a random best scoring alignment' ) (options, args) = parser.parse_args() tmp = tempfile.NamedTemporaryFile().name tmp_stdout = open( tmp, 'wb' ) proc = subprocess.Popen( args='bfast 2>&1', shell=True, stdout=tmp_stdout ) tmp_stdout.close() returncode = proc.wait() stdout = None for line in open( tmp_stdout.name, 'rb' ): if line.lower().find( 'version' ) >= 0: stdout = line.strip() break if stdout: sys.stdout.write( '%s\n' % stdout ) else: raise Exception except: sys.stdout.write( 'Could not determine BFAST version\n' ) buffsize = 1048576 tmp_dir = '%s/' % tempfile.mkdtemp() if options.timing: all_cmd_options = "-t" else: all_cmd_options = "" try: if options.buildIndex: reference_filepath = tempfile.NamedTemporaryFile( dir=tmp_dir, suffix='.fa' ).name os.symlink( options.ref, reference_filepath ) try: nuc_space = [ "0" ] if options.space == "1": nuc_space.append( "1" ) for space in nuc_space: cmd = 'bfast fasta2brg -f "%s" -A "%s" %s' % ( reference_filepath, space, all_cmd_options ) tmp = tempfile.NamedTemporaryFile( dir=tmp_dir ).name tmp_stderr = open( tmp, 'wb' ) proc = subprocess.Popen( args=cmd, shell=True, cwd=tmp_dir, stderr=tmp_stderr.fileno() ) returncode = proc.wait() tmp_stderr.close() tmp_stderr = open( tmp, 'rb' ) stderr = '' try: while True: stderr += tmp_stderr.read( buffsize ) if not stderr or len( stderr ) % buffsize != 0: break except OverflowError: pass tmp_stderr.close() if returncode != 0: raise Exception(stderr) except Exception as e: raise Exception('Error in \'bfast fasta2brg\'.\n' + str( e )) # bfast index try: all_index_cmds = 'bfast index %s -f "%s" -A "%s" -n "%s"' % ( all_cmd_options, reference_filepath, options.space, options.numThreads ) if options.indexRepeatMasker: all_index_cmds += " -R" if options.indexContigOptions: index_contig_options = [ int(_) for _ in options.indexContigOptions.split( ',' ) ] if index_contig_options[0] >= 0: all_index_cmds += ' -s "%s"' % index_contig_options[0] if index_contig_options[1] >= 0: all_index_cmds += ' -S "%s"' % index_contig_options[1] if index_contig_options[2] >= 0: all_index_cmds += ' -e "%s"' % index_contig_options[2] if index_contig_options[3] >= 0: all_index_cmds += ' -E "%s"' % index_contig_options[3] elif options.indexExonsFileName: all_index_cmds += ' -x "%s"' % options.indexExonsFileName index_count = 1 for mask, hash_width in [ mask.split( ':' ) for mask in options.indexMask.split( ',' ) ]: cmd = '%s -m "%s" -w "%s" -i "%i"' % ( all_index_cmds, mask, hash_width, index_count ) tmp = tempfile.NamedTemporaryFile( dir=tmp_dir ).name tmp_stderr = open( tmp, 'wb' ) proc = subprocess.Popen( args=cmd, shell=True, cwd=tmp_dir, stderr=tmp_stderr.fileno() ) returncode = proc.wait() tmp_stderr.close() # get stderr, allowing for case where it's very large tmp_stderr = open( tmp, 'rb' ) stderr = '' try: while True: stderr += tmp_stderr.read( buffsize ) if not stderr or len( stderr ) % buffsize != 0: break except OverflowError: pass tmp_stderr.close() if returncode != 0: raise Exception(stderr) index_count += 1 except Exception as e: raise Exception('Error in \'bfast index\'.\n' + str( e )) else: reference_filepath = options.ref assert reference_filepath and os.path.exists( reference_filepath ), 'A valid genome reference was not provided.' tmp_bmf = tempfile.NamedTemporaryFile( dir=tmp_dir ) tmp_bmf_name = tmp_bmf.name tmp_bmf.close() tmp_baf = tempfile.NamedTemporaryFile( dir=tmp_dir ) tmp_baf_name = tmp_baf.name tmp_baf.close() bfast_match_cmd = 'bfast match -f "%s" -r "%s" -n "%s" -A "%s" -T "%s" -w "%s" %s' % ( reference_filepath, options.fastq, options.numThreads, options.space, tmp_dir, options.whichStrand, all_cmd_options ) bfast_localalign_cmd = 'bfast localalign -f "%s" -m "%s" -n "%s" -A "%s" -o "%s" %s' % ( reference_filepath, tmp_bmf_name, options.numThreads, options.space, options.offset, all_cmd_options ) bfast_postprocess_cmd = 'bfast postprocess -O 1 -f "%s" -i "%s" -n "%s" -A "%s" -a "%s" %s' % ( reference_filepath, tmp_baf_name, options.numThreads, options.space, options.algorithm, all_cmd_options ) if options.offsets: bfast_match_cmd += ' -o "%s"' % options.offsets if options.keySize >= 0: bfast_match_cmd += ' -k "%s"' % options.keySize if options.maxKeyMatches >= 0: bfast_match_cmd += ' -K "%s"' % options.maxKeyMatches if options.maxNumMatches >= 0: bfast_match_cmd += ' -M "%s"' % options.maxNumMatches bfast_localalign_cmd += ' -M "%s"' % options.maxNumMatches if options.scoringMatrixFileName: bfast_localalign_cmd += ' -x "%s"' % options.scoringMatrixFileName bfast_postprocess_cmd += ' -x "%s"' % options.scoringMatrixFileName if options.ungapped: bfast_localalign_cmd += ' -u' if options.unconstrained: bfast_localalign_cmd += ' -U' if options.avgMismatchQuality >= 0: bfast_localalign_cmd += ' -q "%s"' % options.avgMismatchQuality bfast_postprocess_cmd += ' -q "%s"' % options.avgMismatchQuality if options.algorithm == 3: if options.pairedEndInfer: bfast_postprocess_cmd += ' -P' if options.randomBest: bfast_postprocess_cmd += ' -z' if options.unpaired: bfast_postprocess_cmd += ' -U' if options.reverseStrand: bfast_postprocess_cmd += ' -R' bfast_match_cmd += " > %s" % tmp_bmf_name bfast_localalign_cmd += " > %s" % tmp_baf_name bfast_postprocess_cmd += " > %s" % options.output try: try: tmp = tempfile.NamedTemporaryFile( dir=tmp_dir ).name tmp_stderr = open( tmp, 'wb' ) proc = subprocess.Popen( args=bfast_match_cmd, shell=True, cwd=tmp_dir, stderr=tmp_stderr.fileno() ) returncode = proc.wait() tmp_stderr.close() tmp_stderr = open( tmp, 'rb' ) stderr = '' try: while True: stderr += tmp_stderr.read( buffsize ) if not stderr or len( stderr ) % buffsize != 0: break except OverflowError: pass tmp_stderr.close() if returncode != 0: raise Exception(stderr) except Exception as e: raise Exception('Error in \'bfast match\'. \n' + str( e )) # bfast 'localalign' try: tmp = tempfile.NamedTemporaryFile( dir=tmp_dir ).name tmp_stderr = open( tmp, 'wb' ) proc = subprocess.Popen( args=bfast_localalign_cmd, shell=True, cwd=tmp_dir, stderr=tmp_stderr.fileno() ) returncode = proc.wait() tmp_stderr.close() # get stderr, allowing for case where it's very large tmp_stderr = open( tmp, 'rb' ) stderr = '' try: while True: stderr += tmp_stderr.read( buffsize ) if not stderr or len( stderr ) % buffsize != 0: break except OverflowError: pass tmp_stderr.close() if returncode != 0: raise Exception(stderr) except Exception as e: raise Exception('Error in \'bfast localalign\'. \n' + str( e )) try: tmp = tempfile.NamedTemporaryFile( dir=tmp_dir ).name tmp_stderr = open( tmp, 'wb' ) proc = subprocess.Popen( args=bfast_postprocess_cmd, shell=True, cwd=tmp_dir, stderr=tmp_stderr.fileno() ) returncode = proc.wait() tmp_stderr.close() tmp_stderr = open( tmp, 'rb' ) stderr = '' try: while True: stderr += tmp_stderr.read( buffsize ) if not stderr or len( stderr ) % buffsize != 0: break except OverflowError: pass tmp_stderr.close() if returncode != 0: raise Exception(stderr) except Exception as e: raise Exception('Error in \'bfast postprocess\'. \n' + str( e )) # remove header if necessary if options.suppressHeader: tmp_out = tempfile.NamedTemporaryFile( dir=tmp_dir) tmp_out_name = tmp_out.name tmp_out.close() try: shutil.move( options.output, tmp_out_name ) except Exception as e: raise Exception('Error moving output file before removing headers. \n' + str( e )) fout = open( options.output, 'w' ) for line in open( tmp_out.name, 'r' ): if len( line ) < 3 or line[0:3] not in [ '@HD', '@SQ', '@RG', '@PG', '@CO' ]: fout.write( line ) fout.close() # check that there are results in the output file if os.path.getsize( options.output ) > 0: if "0" == options.space: sys.stdout.write( 'BFAST run on Base Space data' ) else: sys.stdout.write( 'BFAST run on Color Space data' ) else: raise Exception('The output file is empty. You may simply have no matches, or there may be an error with your input file or settings.') except Exception as e: stop_err( 'The alignment failed.\n' + str( e ) ) finally: # clean up temp dir if os.path.exists( tmp_dir ): shutil.rmtree( tmp_dir ) if __name__ == "__main__": __main__()
true
true
f72cc9fd6006f3d37d591e4575e98e027bf672c1
11,546
py
Python
markovify/text.py
iconesalut/markovify
e82077e2733b7613a6a153194ab1b288a9170e4e
[ "MIT" ]
null
null
null
markovify/text.py
iconesalut/markovify
e82077e2733b7613a6a153194ab1b288a9170e4e
[ "MIT" ]
null
null
null
markovify/text.py
iconesalut/markovify
e82077e2733b7613a6a153194ab1b288a9170e4e
[ "MIT" ]
null
null
null
import re import json import random from .splitters import split_into_sentences from .chain import Chain, BEGIN, END from unidecode import unidecode DEFAULT_MAX_OVERLAP_RATIO = 0.7 DEFAULT_MAX_OVERLAP_TOTAL = 15 DEFAULT_TRIES = 10 class ParamError(Exception): pass class Text(object): reject_pat = re.compile(r"(^')|('$)|\s'|'\s|[\"(\(\)\[\])]") def __init__(self, input_text, state_size=2, chain=None, parsed_sentences=None, retain_original=True, well_formed=True, reject_reg=''): """ input_text: A string. state_size: An integer, indicating the number of words in the model's state. chain: A trained markovify.Chain instance for this text, if pre-processed. parsed_sentences: A list of lists, where each outer list is a "run" of the process (e.g. a single sentence), and each inner list contains the steps (e.g. words) in the run. If you want to simulate an infinite process, you can come very close by passing just one, very long run. retain_original: Indicates whether to keep the original corpus. well_formed: Indicates whether sentences should be well-formed, preventing unmatched quotes, parenthesis by default, or a custom regular expression can be provided. reject_reg: If well_formed is True, this can be provided to override the standard rejection pattern. """ self.well_formed = well_formed if well_formed and reject_reg != '': self.reject_pat = re.compile(reject_reg) can_make_sentences = parsed_sentences is not None or input_text is not None self.retain_original = retain_original and can_make_sentences self.state_size = state_size if self.retain_original: self.parsed_sentences = parsed_sentences or list(self.generate_corpus(input_text)) # Rejoined text lets us assess the novelty of generated sentences self.rejoined_text = self.sentence_join(map(self.word_join, self.parsed_sentences)) self.chain = chain or Chain(self.parsed_sentences, state_size) else: if not chain: parsed = parsed_sentences or self.generate_corpus(input_text) self.chain = chain or Chain(parsed, state_size) def compile(self, inplace = False): if inplace: self.chain.compile(inplace = True) return self cchain = self.chain.compile(inplace = False) psent = None if hasattr(self, 'parsed_sentences'): psent = self.parsed_sentences return Text(None, \ state_size = self.state_size, \ chain = cchain, \ parsed_sentences = psent, \ retain_original = self.retain_original, \ well_formed = self.well_formed, \ reject_reg = self.reject_pat) def to_dict(self): """ Returns the underlying data as a Python dict. """ return { "state_size": self.state_size, "chain": self.chain.to_json(), "parsed_sentences": self.parsed_sentences if self.retain_original else None } def to_json(self): """ Returns the underlying data as a JSON string. """ return json.dumps(self.to_dict()) @classmethod def from_dict(cls, obj, **kwargs): return cls( None, state_size=obj["state_size"], chain=Chain.from_json(obj["chain"]), parsed_sentences=obj.get("parsed_sentences") ) @classmethod def from_json(cls, json_str): return cls.from_dict(json.loads(json_str)) def sentence_split(self, text): """ Splits full-text string into a list of sentences. """ return split_into_sentences(text) def sentence_join(self, sentences): """ Re-joins a list of sentences into the full text. """ return " ".join(sentences) word_split_pattern = re.compile(r"\s+") def word_split(self, sentence): """ Splits a sentence into a list of words. """ return re.split(self.word_split_pattern, sentence) def word_join(self, words): """ Re-joins a list of words into a sentence. """ return " ".join(words) def test_sentence_input(self, sentence): """ A basic sentence filter. The default rejects sentences that contain the type of punctuation that would look strange on its own in a randomly-generated sentence. """ if len(sentence.strip()) == 0: return False # Decode unicode, mainly to normalize fancy quotation marks if sentence.__class__.__name__ == "str": # pragma: no cover decoded = sentence else: # pragma: no cover decoded = unidecode(sentence) # Sentence shouldn't contain problematic characters if self.well_formed and self.reject_pat.search(decoded): return False return True def generate_corpus(self, text): """ Given a text string, returns a list of lists; that is, a list of "sentences," each of which is a list of words. Before splitting into words, the sentences are filtered through `self.test_sentence_input` """ if isinstance(text, str): sentences = self.sentence_split(text) else: sentences = [] for line in text: sentences += self.sentence_split(line) passing = filter(self.test_sentence_input, sentences) runs = map(self.word_split, passing) return runs def test_sentence_output(self, words, max_overlap_ratio, max_overlap_total): """ Given a generated list of words, accept or reject it. This one rejects sentences that too closely match the original text, namely those that contain any identical sequence of words of X length, where X is the smaller number of (a) `max_overlap_ratio` (default: 0.7) of the total number of words, and (b) `max_overlap_total` (default: 15). """ # Reject large chunks of similarity overlap_ratio = int(round(max_overlap_ratio * len(words))) overlap_max = min(max_overlap_total, overlap_ratio) overlap_over = overlap_max + 1 gram_count = max((len(words) - overlap_max), 1) grams = [ words[i:i+overlap_over] for i in range(gram_count) ] for g in grams: gram_joined = self.word_join(g) if gram_joined in self.rejoined_text: return False return True def make_sentence(self, init_state=None, topic=[], minimum_topic_words=0, **kwargs): """ Attempts `tries` (default: 10) times to generate a valid sentence, based on the model and `test_sentence_output`. Passes `max_overlap_ratio` and `max_overlap_total` to `test_sentence_output`. If successful, returns the sentence as a string. If not, returns None. If `init_state` (a tuple of `self.chain.state_size` words) is not specified, this method chooses a sentence-start at random, in accordance with the model. If `test_output` is set as False then the `test_sentence_output` check will be skipped. If `max_words` is specified, the word count for the sentence will be evaluated against the provided limit. """ tries = kwargs.get('tries', DEFAULT_TRIES) mor = kwargs.get('max_overlap_ratio', DEFAULT_MAX_OVERLAP_RATIO) mot = kwargs.get('max_overlap_total', DEFAULT_MAX_OVERLAP_TOTAL) test_output = kwargs.get('test_output', True) max_words = kwargs.get('max_words', None) if init_state != None: prefix = list(init_state) for word in prefix: if word == BEGIN: prefix = prefix[1:] else: break else: prefix = [] for _ in range(tries): words = prefix + self.chain.walk(init_state, topic) if max_words != None and len(words) > max_words: continue if test_output and hasattr(self, "rejoined_text"): if self.test_sentence_output(words, mor, mot) and self.chain.topic_match >= minimum_topic_words: return self.word_join(words) elif self.chain.topic_match >= minimum_topic_words: return self.word_join(words) return None def make_short_sentence(self, max_chars, min_chars=0, **kwargs): """ Tries making a sentence of no more than `max_chars` characters and optionally no less than `min_chars` characters, passing **kwargs to `self.make_sentence`. """ tries = kwargs.get('tries', DEFAULT_TRIES) for _ in range(tries): sentence = self.make_sentence(**kwargs) if sentence and len(sentence) <= max_chars and len(sentence) >= min_chars: return sentence def make_sentence_with_start(self, beginning, strict=True, **kwargs): """ Tries making a sentence that begins with `beginning` string, which should be a string of one to `self.state` words known to exist in the corpus. If strict == True, then markovify will draw its initial inspiration only from sentences that start with the specified word/phrase. If strict == False, then markovify will draw its initial inspiration from any sentence containing the specified word/phrase. **kwargs are passed to `self.make_sentence` """ split = tuple(self.word_split(beginning)) word_count = len(split) if word_count == self.state_size: init_states = [ split ] elif word_count > 0 and word_count < self.state_size: if strict: init_states = [ (BEGIN,) * (self.state_size - word_count) + split ] else: init_states = [ key for key in self.chain.model.keys() # check for starting with begin as well ordered lists if tuple(filter(lambda x: x != BEGIN, key))[:word_count] == split ] random.shuffle(init_states) else: err_msg = "`make_sentence_with_start` for this model requires a string containing 1 to {0} words. Yours has {1}: {2}".format(self.state_size, word_count, str(split)) raise ParamError(err_msg) for init_state in init_states: output = self.make_sentence(init_state, **kwargs) if output is not None: return output return None @classmethod def from_chain(cls, chain_json, corpus=None, parsed_sentences=None): """ Init a Text class based on an existing chain JSON string or object If corpus is None, overlap checking won't work. """ chain = Chain.from_json(chain_json) return cls(corpus or None, parsed_sentences=parsed_sentences, state_size=chain.state_size, chain=chain) class NewlineText(Text): """ A (usable) example of subclassing markovify.Text. This one lets you markovify text where the sentences are separated by newlines instead of ". " """ def sentence_split(self, text): return re.split(r"\s*\n\s*", text)
39.406143
177
0.620908
import re import json import random from .splitters import split_into_sentences from .chain import Chain, BEGIN, END from unidecode import unidecode DEFAULT_MAX_OVERLAP_RATIO = 0.7 DEFAULT_MAX_OVERLAP_TOTAL = 15 DEFAULT_TRIES = 10 class ParamError(Exception): pass class Text(object): reject_pat = re.compile(r"(^')|('$)|\s'|'\s|[\"(\(\)\[\])]") def __init__(self, input_text, state_size=2, chain=None, parsed_sentences=None, retain_original=True, well_formed=True, reject_reg=''): self.well_formed = well_formed if well_formed and reject_reg != '': self.reject_pat = re.compile(reject_reg) can_make_sentences = parsed_sentences is not None or input_text is not None self.retain_original = retain_original and can_make_sentences self.state_size = state_size if self.retain_original: self.parsed_sentences = parsed_sentences or list(self.generate_corpus(input_text)) # Rejoined text lets us assess the novelty of generated sentences self.rejoined_text = self.sentence_join(map(self.word_join, self.parsed_sentences)) self.chain = chain or Chain(self.parsed_sentences, state_size) else: if not chain: parsed = parsed_sentences or self.generate_corpus(input_text) self.chain = chain or Chain(parsed, state_size) def compile(self, inplace = False): if inplace: self.chain.compile(inplace = True) return self cchain = self.chain.compile(inplace = False) psent = None if hasattr(self, 'parsed_sentences'): psent = self.parsed_sentences return Text(None, \ state_size = self.state_size, \ chain = cchain, \ parsed_sentences = psent, \ retain_original = self.retain_original, \ well_formed = self.well_formed, \ reject_reg = self.reject_pat) def to_dict(self): return { "state_size": self.state_size, "chain": self.chain.to_json(), "parsed_sentences": self.parsed_sentences if self.retain_original else None } def to_json(self): return json.dumps(self.to_dict()) @classmethod def from_dict(cls, obj, **kwargs): return cls( None, state_size=obj["state_size"], chain=Chain.from_json(obj["chain"]), parsed_sentences=obj.get("parsed_sentences") ) @classmethod def from_json(cls, json_str): return cls.from_dict(json.loads(json_str)) def sentence_split(self, text): return split_into_sentences(text) def sentence_join(self, sentences): return " ".join(sentences) word_split_pattern = re.compile(r"\s+") def word_split(self, sentence): return re.split(self.word_split_pattern, sentence) def word_join(self, words): return " ".join(words) def test_sentence_input(self, sentence): if len(sentence.strip()) == 0: return False # Decode unicode, mainly to normalize fancy quotation marks if sentence.__class__.__name__ == "str": # pragma: no cover decoded = sentence else: # pragma: no cover decoded = unidecode(sentence) # Sentence shouldn't contain problematic characters if self.well_formed and self.reject_pat.search(decoded): return False return True def generate_corpus(self, text): if isinstance(text, str): sentences = self.sentence_split(text) else: sentences = [] for line in text: sentences += self.sentence_split(line) passing = filter(self.test_sentence_input, sentences) runs = map(self.word_split, passing) return runs def test_sentence_output(self, words, max_overlap_ratio, max_overlap_total): # Reject large chunks of similarity overlap_ratio = int(round(max_overlap_ratio * len(words))) overlap_max = min(max_overlap_total, overlap_ratio) overlap_over = overlap_max + 1 gram_count = max((len(words) - overlap_max), 1) grams = [ words[i:i+overlap_over] for i in range(gram_count) ] for g in grams: gram_joined = self.word_join(g) if gram_joined in self.rejoined_text: return False return True def make_sentence(self, init_state=None, topic=[], minimum_topic_words=0, **kwargs): tries = kwargs.get('tries', DEFAULT_TRIES) mor = kwargs.get('max_overlap_ratio', DEFAULT_MAX_OVERLAP_RATIO) mot = kwargs.get('max_overlap_total', DEFAULT_MAX_OVERLAP_TOTAL) test_output = kwargs.get('test_output', True) max_words = kwargs.get('max_words', None) if init_state != None: prefix = list(init_state) for word in prefix: if word == BEGIN: prefix = prefix[1:] else: break else: prefix = [] for _ in range(tries): words = prefix + self.chain.walk(init_state, topic) if max_words != None and len(words) > max_words: continue if test_output and hasattr(self, "rejoined_text"): if self.test_sentence_output(words, mor, mot) and self.chain.topic_match >= minimum_topic_words: return self.word_join(words) elif self.chain.topic_match >= minimum_topic_words: return self.word_join(words) return None def make_short_sentence(self, max_chars, min_chars=0, **kwargs): tries = kwargs.get('tries', DEFAULT_TRIES) for _ in range(tries): sentence = self.make_sentence(**kwargs) if sentence and len(sentence) <= max_chars and len(sentence) >= min_chars: return sentence def make_sentence_with_start(self, beginning, strict=True, **kwargs): split = tuple(self.word_split(beginning)) word_count = len(split) if word_count == self.state_size: init_states = [ split ] elif word_count > 0 and word_count < self.state_size: if strict: init_states = [ (BEGIN,) * (self.state_size - word_count) + split ] else: init_states = [ key for key in self.chain.model.keys() # check for starting with begin as well ordered lists if tuple(filter(lambda x: x != BEGIN, key))[:word_count] == split ] random.shuffle(init_states) else: err_msg = "`make_sentence_with_start` for this model requires a string containing 1 to {0} words. Yours has {1}: {2}".format(self.state_size, word_count, str(split)) raise ParamError(err_msg) for init_state in init_states: output = self.make_sentence(init_state, **kwargs) if output is not None: return output return None @classmethod def from_chain(cls, chain_json, corpus=None, parsed_sentences=None): chain = Chain.from_json(chain_json) return cls(corpus or None, parsed_sentences=parsed_sentences, state_size=chain.state_size, chain=chain) class NewlineText(Text): def sentence_split(self, text): return re.split(r"\s*\n\s*", text)
true
true
f72ccad3cb20f24ab3326c7cf1774f63675af32d
2,175
py
Python
django_remote_submission/signals.py
YeemBoi/django-remote-submission
665daa0701b7da5ac653115712d0c0f0aae041c6
[ "ISC" ]
null
null
null
django_remote_submission/signals.py
YeemBoi/django-remote-submission
665daa0701b7da5ac653115712d0c0f0aae041c6
[ "ISC" ]
null
null
null
django_remote_submission/signals.py
YeemBoi/django-remote-submission
665daa0701b7da5ac653115712d0c0f0aae041c6
[ "ISC" ]
null
null
null
"""Attach signals to this app's models.""" # -*- coding: utf-8 -*- import json import logging import channels.layers from asgiref.sync import async_to_sync from django.db.models.signals import post_save from django.dispatch import receiver from .models import Job, Log logger = logging.getLogger(__name__) # pylint: disable=C0103 def send_message(event): ''' Call back function to send message to the browser ''' message = event['text'] channel_layer = channels.layers.get_channel_layer() # Send message to WebSocket async_to_sync(channel_layer.send)(text_data=json.dumps( message )) @receiver(post_save, sender=Job, dispatch_uid='update_job_status_listeners') def update_job_status_listeners(sender, instance, **kwargs): ''' Sends job status to the browser when a Job is modified ''' logger.debug("Job modified: {} :: status = {}.".format( instance, instance.status)) user = instance.owner group_name = 'job-user-{}'.format(user.username) message = { 'job_id': instance.id, 'title': instance.title, 'status': instance.status, 'modified': instance.modified.isoformat(), } channel_layer = channels.layers.get_channel_layer() async_to_sync(channel_layer.group_send)( group_name, { 'type': 'send_message', 'text': message } ) @receiver(post_save, sender=Log, dispatch_uid='update_job_log_listeners') def update_job_log_listeners(sender, instance, **kwargs): ''' Sends job status to the browser when a Log is modified ''' logger.debug("Log modified: {} :: content = {}.".format( instance, instance.content)) job_pk = instance.job.id group_name = 'job-log-{}'.format(job_pk) message = { 'log_id': instance.id, 'time': instance.time.isoformat(), 'content': instance.content, 'stream': instance.stream, } channel_layer = channels.layers.get_channel_layer() async_to_sync(channel_layer.group_send)( group_name, { 'type': 'send_message', 'text': message } )
24.715909
76
0.643218
import json import logging import channels.layers from asgiref.sync import async_to_sync from django.db.models.signals import post_save from django.dispatch import receiver from .models import Job, Log logger = logging.getLogger(__name__) def send_message(event): message = event['text'] channel_layer = channels.layers.get_channel_layer() async_to_sync(channel_layer.send)(text_data=json.dumps( message )) @receiver(post_save, sender=Job, dispatch_uid='update_job_status_listeners') def update_job_status_listeners(sender, instance, **kwargs): logger.debug("Job modified: {} :: status = {}.".format( instance, instance.status)) user = instance.owner group_name = 'job-user-{}'.format(user.username) message = { 'job_id': instance.id, 'title': instance.title, 'status': instance.status, 'modified': instance.modified.isoformat(), } channel_layer = channels.layers.get_channel_layer() async_to_sync(channel_layer.group_send)( group_name, { 'type': 'send_message', 'text': message } ) @receiver(post_save, sender=Log, dispatch_uid='update_job_log_listeners') def update_job_log_listeners(sender, instance, **kwargs): logger.debug("Log modified: {} :: content = {}.".format( instance, instance.content)) job_pk = instance.job.id group_name = 'job-log-{}'.format(job_pk) message = { 'log_id': instance.id, 'time': instance.time.isoformat(), 'content': instance.content, 'stream': instance.stream, } channel_layer = channels.layers.get_channel_layer() async_to_sync(channel_layer.group_send)( group_name, { 'type': 'send_message', 'text': message } )
true
true
f72ccbbf32e6e2e0c7f9b522c887b0a968d79192
15,631
py
Python
guild/external/setuptools/tests/test_wheel.py
msarahan/guildai
99bdd09683291dbc206b6dde1b327d47401d29eb
[ "Apache-2.0" ]
63
2016-11-01T13:06:46.000Z
2018-08-21T08:38:36.000Z
guild/external/setuptools/tests/test_wheel.py
msarahan/guildai
99bdd09683291dbc206b6dde1b327d47401d29eb
[ "Apache-2.0" ]
28
2016-11-02T01:41:23.000Z
2018-10-19T22:57:06.000Z
guild/external/setuptools/tests/test_wheel.py
msarahan/guildai
99bdd09683291dbc206b6dde1b327d47401d29eb
[ "Apache-2.0" ]
8
2017-01-15T14:58:43.000Z
2018-07-27T11:51:39.000Z
# -*- coding: utf-8 -*- """wheel tests """ from distutils.sysconfig import get_config_var from distutils.util import get_platform import contextlib import glob import inspect import os import shutil import subprocess import sys import zipfile import pytest from pkg_resources import Distribution, PathMetadata, PY_MAJOR from setuptools.extern.packaging.utils import canonicalize_name from setuptools.extern.packaging.tags import parse_tag from setuptools.wheel import Wheel from .contexts import tempdir from .files import build_files from .textwrap import DALS __metaclass__ = type WHEEL_INFO_TESTS = ( ('invalid.whl', ValueError), ('simplewheel-2.0-1-py2.py3-none-any.whl', { 'project_name': 'simplewheel', 'version': '2.0', 'build': '1', 'py_version': 'py2.py3', 'abi': 'none', 'platform': 'any', }), ('simple.dist-0.1-py2.py3-none-any.whl', { 'project_name': 'simple.dist', 'version': '0.1', 'build': None, 'py_version': 'py2.py3', 'abi': 'none', 'platform': 'any', }), ('example_pkg_a-1-py3-none-any.whl', { 'project_name': 'example_pkg_a', 'version': '1', 'build': None, 'py_version': 'py3', 'abi': 'none', 'platform': 'any', }), ('PyQt5-5.9-5.9.1-cp35.cp36.cp37-abi3-manylinux1_x86_64.whl', { 'project_name': 'PyQt5', 'version': '5.9', 'build': '5.9.1', 'py_version': 'cp35.cp36.cp37', 'abi': 'abi3', 'platform': 'manylinux1_x86_64', }), ) @pytest.mark.parametrize( ('filename', 'info'), WHEEL_INFO_TESTS, ids=[t[0] for t in WHEEL_INFO_TESTS] ) def test_wheel_info(filename, info): if inspect.isclass(info): with pytest.raises(info): Wheel(filename) return w = Wheel(filename) assert {k: getattr(w, k) for k in info.keys()} == info @contextlib.contextmanager def build_wheel(extra_file_defs=None, **kwargs): file_defs = { 'setup.py': (DALS( ''' # -*- coding: utf-8 -*- from setuptools import setup import setuptools setup(**%r) ''' ) % kwargs).encode('utf-8'), } if extra_file_defs: file_defs.update(extra_file_defs) with tempdir() as source_dir: build_files(file_defs, source_dir) subprocess.check_call((sys.executable, 'setup.py', '-q', 'bdist_wheel'), cwd=source_dir) yield glob.glob(os.path.join(source_dir, 'dist', '*.whl'))[0] def tree_set(root): contents = set() for dirpath, dirnames, filenames in os.walk(root): for filename in filenames: contents.add(os.path.join(os.path.relpath(dirpath, root), filename)) return contents def flatten_tree(tree): """Flatten nested dicts and lists into a full list of paths""" output = set() for node, contents in tree.items(): if isinstance(contents, dict): contents = flatten_tree(contents) for elem in contents: if isinstance(elem, dict): output |= {os.path.join(node, val) for val in flatten_tree(elem)} else: output.add(os.path.join(node, elem)) return output def format_install_tree(tree): return { x.format( py_version=PY_MAJOR, platform=get_platform(), shlib_ext=get_config_var('EXT_SUFFIX') or get_config_var('SO')) for x in tree} def _check_wheel_install(filename, install_dir, install_tree_includes, project_name, version, requires_txt): w = Wheel(filename) egg_path = os.path.join(install_dir, w.egg_name()) w.install_as_egg(egg_path) if install_tree_includes is not None: install_tree = format_install_tree(install_tree_includes) exp = tree_set(install_dir) assert install_tree.issubset(exp), (install_tree - exp) metadata = PathMetadata(egg_path, os.path.join(egg_path, 'EGG-INFO')) dist = Distribution.from_filename(egg_path, metadata=metadata) assert dist.project_name == project_name assert dist.version == version if requires_txt is None: assert not dist.has_metadata('requires.txt') else: assert requires_txt == dist.get_metadata('requires.txt').lstrip() class Record: def __init__(self, id, **kwargs): self._id = id self._fields = kwargs def __repr__(self): return '%s(**%r)' % (self._id, self._fields) WHEEL_INSTALL_TESTS = ( dict( id='basic', file_defs={ 'foo': { '__init__.py': '' } }, setup_kwargs=dict( packages=['foo'], ), install_tree=flatten_tree({ 'foo-1.0-py{py_version}.egg': { 'EGG-INFO': [ 'PKG-INFO', 'RECORD', 'WHEEL', 'top_level.txt' ], 'foo': ['__init__.py'] } }), ), dict( id='utf-8', setup_kwargs=dict( description='Description accentuée', ) ), dict( id='data', file_defs={ 'data.txt': DALS( ''' Some data... ''' ), }, setup_kwargs=dict( data_files=[('data_dir', ['data.txt'])], ), install_tree=flatten_tree({ 'foo-1.0-py{py_version}.egg': { 'EGG-INFO': [ 'PKG-INFO', 'RECORD', 'WHEEL', 'top_level.txt' ], 'data_dir': [ 'data.txt' ] } }), ), dict( id='extension', file_defs={ 'extension.c': DALS( ''' #include "Python.h" #if PY_MAJOR_VERSION >= 3 static struct PyModuleDef moduledef = { PyModuleDef_HEAD_INIT, "extension", NULL, 0, NULL, NULL, NULL, NULL, NULL }; #define INITERROR return NULL PyMODINIT_FUNC PyInit_extension(void) #else #define INITERROR return void initextension(void) #endif { #if PY_MAJOR_VERSION >= 3 PyObject *module = PyModule_Create(&moduledef); #else PyObject *module = Py_InitModule("extension", NULL); #endif if (module == NULL) INITERROR; #if PY_MAJOR_VERSION >= 3 return module; #endif } ''' ), }, setup_kwargs=dict( ext_modules=[ Record('setuptools.Extension', name='extension', sources=['extension.c']) ], ), install_tree=flatten_tree({ 'foo-1.0-py{py_version}-{platform}.egg': [ 'extension{shlib_ext}', {'EGG-INFO': [ 'PKG-INFO', 'RECORD', 'WHEEL', 'top_level.txt', ]}, ] }), ), dict( id='header', file_defs={ 'header.h': DALS( ''' ''' ), }, setup_kwargs=dict( headers=['header.h'], ), install_tree=flatten_tree({ 'foo-1.0-py{py_version}.egg': [ 'header.h', {'EGG-INFO': [ 'PKG-INFO', 'RECORD', 'WHEEL', 'top_level.txt', ]}, ] }), ), dict( id='script', file_defs={ 'script.py': DALS( ''' #/usr/bin/python print('hello world!') ''' ), 'script.sh': DALS( ''' #/bin/sh echo 'hello world!' ''' ), }, setup_kwargs=dict( scripts=['script.py', 'script.sh'], ), install_tree=flatten_tree({ 'foo-1.0-py{py_version}.egg': { 'EGG-INFO': [ 'PKG-INFO', 'RECORD', 'WHEEL', 'top_level.txt', {'scripts': [ 'script.py', 'script.sh' ]} ] } }) ), dict( id='requires1', install_requires='foobar==2.0', install_tree=flatten_tree({ 'foo-1.0-py{py_version}.egg': { 'EGG-INFO': [ 'PKG-INFO', 'RECORD', 'WHEEL', 'requires.txt', 'top_level.txt', ] } }), requires_txt=DALS( ''' foobar==2.0 ''' ), ), dict( id='requires2', install_requires=''' bar foo<=2.0; %r in sys_platform ''' % sys.platform, requires_txt=DALS( ''' bar foo<=2.0 ''' ), ), dict( id='requires3', install_requires=''' bar; %r != sys_platform ''' % sys.platform, ), dict( id='requires4', install_requires=''' foo ''', extras_require={ 'extra': 'foobar>3', }, requires_txt=DALS( ''' foo [extra] foobar>3 ''' ), ), dict( id='requires5', extras_require={ 'extra': 'foobar; %r != sys_platform' % sys.platform, }, requires_txt=DALS( ''' [extra] ''' ), ), dict( id='namespace_package', file_defs={ 'foo': { 'bar': { '__init__.py': '' }, }, }, setup_kwargs=dict( namespace_packages=['foo'], packages=['foo.bar'], ), install_tree=flatten_tree({ 'foo-1.0-py{py_version}.egg': [ 'foo-1.0-py{py_version}-nspkg.pth', {'EGG-INFO': [ 'PKG-INFO', 'RECORD', 'WHEEL', 'namespace_packages.txt', 'top_level.txt', ]}, {'foo': [ '__init__.py', {'bar': ['__init__.py']}, ]}, ] }), ), dict( id='empty_namespace_package', file_defs={ 'foobar': { '__init__.py': "__import__('pkg_resources').declare_namespace(__name__)", }, }, setup_kwargs=dict( namespace_packages=['foobar'], packages=['foobar'], ), install_tree=flatten_tree({ 'foo-1.0-py{py_version}.egg': [ 'foo-1.0-py{py_version}-nspkg.pth', {'EGG-INFO': [ 'PKG-INFO', 'RECORD', 'WHEEL', 'namespace_packages.txt', 'top_level.txt', ]}, {'foobar': [ '__init__.py', ]}, ] }), ), dict( id='data_in_package', file_defs={ 'foo': { '__init__.py': '', 'data_dir': { 'data.txt': DALS( ''' Some data... ''' ), } } }, setup_kwargs=dict( packages=['foo'], data_files=[('foo/data_dir', ['foo/data_dir/data.txt'])], ), install_tree=flatten_tree({ 'foo-1.0-py{py_version}.egg': { 'EGG-INFO': [ 'PKG-INFO', 'RECORD', 'WHEEL', 'top_level.txt', ], 'foo': [ '__init__.py', {'data_dir': [ 'data.txt', ]} ] } }), ), ) @pytest.mark.parametrize( 'params', WHEEL_INSTALL_TESTS, ids=list(params['id'] for params in WHEEL_INSTALL_TESTS), ) def test_wheel_install(params): project_name = params.get('name', 'foo') version = params.get('version', '1.0') install_requires = params.get('install_requires', []) extras_require = params.get('extras_require', {}) requires_txt = params.get('requires_txt', None) install_tree = params.get('install_tree') file_defs = params.get('file_defs', {}) setup_kwargs = params.get('setup_kwargs', {}) with build_wheel( name=project_name, version=version, install_requires=install_requires, extras_require=extras_require, extra_file_defs=file_defs, **setup_kwargs ) as filename, tempdir() as install_dir: _check_wheel_install(filename, install_dir, install_tree, project_name, version, requires_txt) def test_wheel_install_pep_503(): project_name = 'Foo_Bar' # PEP 503 canonicalized name is "foo-bar" version = '1.0' with build_wheel( name=project_name, version=version, ) as filename, tempdir() as install_dir: new_filename = filename.replace(project_name, canonicalize_name(project_name)) shutil.move(filename, new_filename) _check_wheel_install(new_filename, install_dir, None, canonicalize_name(project_name), version, None) def test_wheel_no_dist_dir(): project_name = 'nodistinfo' version = '1.0' wheel_name = '{0}-{1}-py2.py3-none-any.whl'.format(project_name, version) with tempdir() as source_dir: wheel_path = os.path.join(source_dir, wheel_name) # create an empty zip file zipfile.ZipFile(wheel_path, 'w').close() with tempdir() as install_dir: with pytest.raises(ValueError): _check_wheel_install(wheel_path, install_dir, None, project_name, version, None) def test_wheel_is_compatible(monkeypatch): def sys_tags(): for t in parse_tag('cp36-cp36m-manylinux1_x86_64'): yield t monkeypatch.setattr('setuptools.wheel.sys_tags', sys_tags) assert Wheel( 'onnxruntime-0.1.2-cp36-cp36m-manylinux1_x86_64.whl').is_compatible()
26.674061
78
0.448852
from distutils.sysconfig import get_config_var from distutils.util import get_platform import contextlib import glob import inspect import os import shutil import subprocess import sys import zipfile import pytest from pkg_resources import Distribution, PathMetadata, PY_MAJOR from setuptools.extern.packaging.utils import canonicalize_name from setuptools.extern.packaging.tags import parse_tag from setuptools.wheel import Wheel from .contexts import tempdir from .files import build_files from .textwrap import DALS __metaclass__ = type WHEEL_INFO_TESTS = ( ('invalid.whl', ValueError), ('simplewheel-2.0-1-py2.py3-none-any.whl', { 'project_name': 'simplewheel', 'version': '2.0', 'build': '1', 'py_version': 'py2.py3', 'abi': 'none', 'platform': 'any', }), ('simple.dist-0.1-py2.py3-none-any.whl', { 'project_name': 'simple.dist', 'version': '0.1', 'build': None, 'py_version': 'py2.py3', 'abi': 'none', 'platform': 'any', }), ('example_pkg_a-1-py3-none-any.whl', { 'project_name': 'example_pkg_a', 'version': '1', 'build': None, 'py_version': 'py3', 'abi': 'none', 'platform': 'any', }), ('PyQt5-5.9-5.9.1-cp35.cp36.cp37-abi3-manylinux1_x86_64.whl', { 'project_name': 'PyQt5', 'version': '5.9', 'build': '5.9.1', 'py_version': 'cp35.cp36.cp37', 'abi': 'abi3', 'platform': 'manylinux1_x86_64', }), ) @pytest.mark.parametrize( ('filename', 'info'), WHEEL_INFO_TESTS, ids=[t[0] for t in WHEEL_INFO_TESTS] ) def test_wheel_info(filename, info): if inspect.isclass(info): with pytest.raises(info): Wheel(filename) return w = Wheel(filename) assert {k: getattr(w, k) for k in info.keys()} == info @contextlib.contextmanager def build_wheel(extra_file_defs=None, **kwargs): file_defs = { 'setup.py': (DALS( ''' # -*- coding: utf-8 -*- from setuptools import setup import setuptools setup(**%r) ''' ) % kwargs).encode('utf-8'), } if extra_file_defs: file_defs.update(extra_file_defs) with tempdir() as source_dir: build_files(file_defs, source_dir) subprocess.check_call((sys.executable, 'setup.py', '-q', 'bdist_wheel'), cwd=source_dir) yield glob.glob(os.path.join(source_dir, 'dist', '*.whl'))[0] def tree_set(root): contents = set() for dirpath, dirnames, filenames in os.walk(root): for filename in filenames: contents.add(os.path.join(os.path.relpath(dirpath, root), filename)) return contents def flatten_tree(tree): output = set() for node, contents in tree.items(): if isinstance(contents, dict): contents = flatten_tree(contents) for elem in contents: if isinstance(elem, dict): output |= {os.path.join(node, val) for val in flatten_tree(elem)} else: output.add(os.path.join(node, elem)) return output def format_install_tree(tree): return { x.format( py_version=PY_MAJOR, platform=get_platform(), shlib_ext=get_config_var('EXT_SUFFIX') or get_config_var('SO')) for x in tree} def _check_wheel_install(filename, install_dir, install_tree_includes, project_name, version, requires_txt): w = Wheel(filename) egg_path = os.path.join(install_dir, w.egg_name()) w.install_as_egg(egg_path) if install_tree_includes is not None: install_tree = format_install_tree(install_tree_includes) exp = tree_set(install_dir) assert install_tree.issubset(exp), (install_tree - exp) metadata = PathMetadata(egg_path, os.path.join(egg_path, 'EGG-INFO')) dist = Distribution.from_filename(egg_path, metadata=metadata) assert dist.project_name == project_name assert dist.version == version if requires_txt is None: assert not dist.has_metadata('requires.txt') else: assert requires_txt == dist.get_metadata('requires.txt').lstrip() class Record: def __init__(self, id, **kwargs): self._id = id self._fields = kwargs def __repr__(self): return '%s(**%r)' % (self._id, self._fields) WHEEL_INSTALL_TESTS = ( dict( id='basic', file_defs={ 'foo': { '__init__.py': '' } }, setup_kwargs=dict( packages=['foo'], ), install_tree=flatten_tree({ 'foo-1.0-py{py_version}.egg': { 'EGG-INFO': [ 'PKG-INFO', 'RECORD', 'WHEEL', 'top_level.txt' ], 'foo': ['__init__.py'] } }), ), dict( id='utf-8', setup_kwargs=dict( description='Description accentuée', ) ), dict( id='data', file_defs={ 'data.txt': DALS( ''' Some data... ''' ), }, setup_kwargs=dict( data_files=[('data_dir', ['data.txt'])], ), install_tree=flatten_tree({ 'foo-1.0-py{py_version}.egg': { 'EGG-INFO': [ 'PKG-INFO', 'RECORD', 'WHEEL', 'top_level.txt' ], 'data_dir': [ 'data.txt' ] } }), ), dict( id='extension', file_defs={ 'extension.c': DALS( ''' #include "Python.h" #if PY_MAJOR_VERSION >= 3 static struct PyModuleDef moduledef = { PyModuleDef_HEAD_INIT, "extension", NULL, 0, NULL, NULL, NULL, NULL, NULL }; #define INITERROR return NULL PyMODINIT_FUNC PyInit_extension(void) #else #define INITERROR return void initextension(void) #endif { #if PY_MAJOR_VERSION >= 3 PyObject *module = PyModule_Create(&moduledef); #else PyObject *module = Py_InitModule("extension", NULL); #endif if (module == NULL) INITERROR; #if PY_MAJOR_VERSION >= 3 return module; #endif } ''' ), }, setup_kwargs=dict( ext_modules=[ Record('setuptools.Extension', name='extension', sources=['extension.c']) ], ), install_tree=flatten_tree({ 'foo-1.0-py{py_version}-{platform}.egg': [ 'extension{shlib_ext}', {'EGG-INFO': [ 'PKG-INFO', 'RECORD', 'WHEEL', 'top_level.txt', ]}, ] }), ), dict( id='header', file_defs={ 'header.h': DALS( ''' ''' ), }, setup_kwargs=dict( headers=['header.h'], ), install_tree=flatten_tree({ 'foo-1.0-py{py_version}.egg': [ 'header.h', {'EGG-INFO': [ 'PKG-INFO', 'RECORD', 'WHEEL', 'top_level.txt', ]}, ] }), ), dict( id='script', file_defs={ 'script.py': DALS( ''' #/usr/bin/python print('hello world!') ''' ), 'script.sh': DALS( ''' #/bin/sh echo 'hello world!' ''' ), }, setup_kwargs=dict( scripts=['script.py', 'script.sh'], ), install_tree=flatten_tree({ 'foo-1.0-py{py_version}.egg': { 'EGG-INFO': [ 'PKG-INFO', 'RECORD', 'WHEEL', 'top_level.txt', {'scripts': [ 'script.py', 'script.sh' ]} ] } }) ), dict( id='requires1', install_requires='foobar==2.0', install_tree=flatten_tree({ 'foo-1.0-py{py_version}.egg': { 'EGG-INFO': [ 'PKG-INFO', 'RECORD', 'WHEEL', 'requires.txt', 'top_level.txt', ] } }), requires_txt=DALS( ''' foobar==2.0 ''' ), ), dict( id='requires2', install_requires=''' bar foo<=2.0; %r in sys_platform ''' % sys.platform, requires_txt=DALS( ''' bar foo<=2.0 ''' ), ), dict( id='requires3', install_requires=''' bar; %r != sys_platform ''' % sys.platform, ), dict( id='requires4', install_requires=''' foo ''', extras_require={ 'extra': 'foobar>3', }, requires_txt=DALS( ''' foo [extra] foobar>3 ''' ), ), dict( id='requires5', extras_require={ 'extra': 'foobar; %r != sys_platform' % sys.platform, }, requires_txt=DALS( ''' [extra] ''' ), ), dict( id='namespace_package', file_defs={ 'foo': { 'bar': { '__init__.py': '' }, }, }, setup_kwargs=dict( namespace_packages=['foo'], packages=['foo.bar'], ), install_tree=flatten_tree({ 'foo-1.0-py{py_version}.egg': [ 'foo-1.0-py{py_version}-nspkg.pth', {'EGG-INFO': [ 'PKG-INFO', 'RECORD', 'WHEEL', 'namespace_packages.txt', 'top_level.txt', ]}, {'foo': [ '__init__.py', {'bar': ['__init__.py']}, ]}, ] }), ), dict( id='empty_namespace_package', file_defs={ 'foobar': { '__init__.py': "__import__('pkg_resources').declare_namespace(__name__)", }, }, setup_kwargs=dict( namespace_packages=['foobar'], packages=['foobar'], ), install_tree=flatten_tree({ 'foo-1.0-py{py_version}.egg': [ 'foo-1.0-py{py_version}-nspkg.pth', {'EGG-INFO': [ 'PKG-INFO', 'RECORD', 'WHEEL', 'namespace_packages.txt', 'top_level.txt', ]}, {'foobar': [ '__init__.py', ]}, ] }), ), dict( id='data_in_package', file_defs={ 'foo': { '__init__.py': '', 'data_dir': { 'data.txt': DALS( ''' Some data... ''' ), } } }, setup_kwargs=dict( packages=['foo'], data_files=[('foo/data_dir', ['foo/data_dir/data.txt'])], ), install_tree=flatten_tree({ 'foo-1.0-py{py_version}.egg': { 'EGG-INFO': [ 'PKG-INFO', 'RECORD', 'WHEEL', 'top_level.txt', ], 'foo': [ '__init__.py', {'data_dir': [ 'data.txt', ]} ] } }), ), ) @pytest.mark.parametrize( 'params', WHEEL_INSTALL_TESTS, ids=list(params['id'] for params in WHEEL_INSTALL_TESTS), ) def test_wheel_install(params): project_name = params.get('name', 'foo') version = params.get('version', '1.0') install_requires = params.get('install_requires', []) extras_require = params.get('extras_require', {}) requires_txt = params.get('requires_txt', None) install_tree = params.get('install_tree') file_defs = params.get('file_defs', {}) setup_kwargs = params.get('setup_kwargs', {}) with build_wheel( name=project_name, version=version, install_requires=install_requires, extras_require=extras_require, extra_file_defs=file_defs, **setup_kwargs ) as filename, tempdir() as install_dir: _check_wheel_install(filename, install_dir, install_tree, project_name, version, requires_txt) def test_wheel_install_pep_503(): project_name = 'Foo_Bar' version = '1.0' with build_wheel( name=project_name, version=version, ) as filename, tempdir() as install_dir: new_filename = filename.replace(project_name, canonicalize_name(project_name)) shutil.move(filename, new_filename) _check_wheel_install(new_filename, install_dir, None, canonicalize_name(project_name), version, None) def test_wheel_no_dist_dir(): project_name = 'nodistinfo' version = '1.0' wheel_name = '{0}-{1}-py2.py3-none-any.whl'.format(project_name, version) with tempdir() as source_dir: wheel_path = os.path.join(source_dir, wheel_name) zipfile.ZipFile(wheel_path, 'w').close() with tempdir() as install_dir: with pytest.raises(ValueError): _check_wheel_install(wheel_path, install_dir, None, project_name, version, None) def test_wheel_is_compatible(monkeypatch): def sys_tags(): for t in parse_tag('cp36-cp36m-manylinux1_x86_64'): yield t monkeypatch.setattr('setuptools.wheel.sys_tags', sys_tags) assert Wheel( 'onnxruntime-0.1.2-cp36-cp36m-manylinux1_x86_64.whl').is_compatible()
true
true
f72cccf7222dd5cd1076530b8dcc103fb3bb156d
246
py
Python
board/amebaz_dev/ucube.py
jinlongliu/AliOS-Things
ce051172a775f987183e7aca88bb6f3b809ea7b0
[ "Apache-2.0" ]
4
2019-03-12T11:04:48.000Z
2019-10-22T06:06:53.000Z
board/amebaz_dev/ucube.py
IamBaoMouMou/AliOS-Things
195a9160b871b3d78de6f8cf6c2ab09a71977527
[ "Apache-2.0" ]
3
2018-12-17T13:06:46.000Z
2018-12-28T01:40:59.000Z
board/amebaz_dev/ucube.py
IamBaoMouMou/AliOS-Things
195a9160b871b3d78de6f8cf6c2ab09a71977527
[ "Apache-2.0" ]
2
2018-01-23T07:54:08.000Z
2018-01-23T11:38:59.000Z
linux_only_targets="linuxapp helloworld helloworld_nocli linkkitapp alinkapp networkapp tls uDataapp hdlcapp.hdlcserver wifihalapp coapapp nano linkkit_gateway blink linkkit_sched meshapp acapp netmgrapp mqttapp wifimonitor vflashdemo athostapp"
123
245
0.894309
linux_only_targets="linuxapp helloworld helloworld_nocli linkkitapp alinkapp networkapp tls uDataapp hdlcapp.hdlcserver wifihalapp coapapp nano linkkit_gateway blink linkkit_sched meshapp acapp netmgrapp mqttapp wifimonitor vflashdemo athostapp"
true
true
f72ccd62512051e1b39bfbd0414538acd7914a7b
1,403
py
Python
Python/textrank/textrank.py
chasingegg/Data_Science
a499866ff92aa1107057b20563564bdd89fc370f
[ "MIT" ]
1
2021-04-03T14:21:14.000Z
2021-04-03T14:21:14.000Z
Python/textrank/textrank.py
chasingegg/Data_Science
a499866ff92aa1107057b20563564bdd89fc370f
[ "MIT" ]
null
null
null
Python/textrank/textrank.py
chasingegg/Data_Science
a499866ff92aa1107057b20563564bdd89fc370f
[ "MIT" ]
null
null
null
#!/usr/src/env python # -*- coding: utf-8 -*- # TextRank 博客 http://xiaosheng.me/2017/04/08/article49/ # 从PageRank转变而来,可以用来做关键字的提取。TextRank的计算公式其实跟PageRank可以认为是一样的 # 只不过就是要考虑权重的因素(算PageRank的时候就是均摊权值) # 在TextRank构建的图中,节点是句子,权值就是两个句子的相似程度 # 提取关键字的时候,单词作为图的节点,把权值都设成1,此时其实退化成PageRank # 把文本拆分成单词,将这一些单词设定一个简单的滑动窗口,每个窗口内的任意两个单词之间存在一条边 # 如果是要提取关键句,一般认为所有句子都是相邻的,不需要窗口提取。相似程度的计算公式一般是重合 # 单词数量除以总单词数量 import sys import pandas as pd import jieba.analyse def textrank(data, topK): idList, titleList, abstractList = data['id'], data['title'], data['abstract'] ids, title, keys = [], [], [] for i in range(len(idList)): text = '%s。%s' % (titleList[i], abstractList[i]) #拼接 jieba.analyse.set_stop_words('data/stopWord.txt') print("\"", titleList[i], "\"", " 10 keywords - TextRank :") keywords = jieba.analyse.textrank(text, topK = topK, allowPOS=('n','nz','v','vd','vn','l','a','d')) word_split = " ".join(keywords) print(word_split) keys.append(word_split.encode("utf-8")) ids.append(idList[i]) title.append(titleList[i]) result = pd.DataFrame({"id":ids, "title":title, "key":keys}, columns=['id', 'title', 'key']) return result if __name__ == "__main__": dataFile = 'data/sample_data.csv' data = pd.read_csv(dataFile) result = textrank(data, 10) result.to_csv("result/keys_textrank.csv", index=False)
36.921053
107
0.667142
import sys import pandas as pd import jieba.analyse def textrank(data, topK): idList, titleList, abstractList = data['id'], data['title'], data['abstract'] ids, title, keys = [], [], [] for i in range(len(idList)): text = '%s。%s' % (titleList[i], abstractList[i]) jieba.analyse.set_stop_words('data/stopWord.txt') print("\"", titleList[i], "\"", " 10 keywords - TextRank :") keywords = jieba.analyse.textrank(text, topK = topK, allowPOS=('n','nz','v','vd','vn','l','a','d')) word_split = " ".join(keywords) print(word_split) keys.append(word_split.encode("utf-8")) ids.append(idList[i]) title.append(titleList[i]) result = pd.DataFrame({"id":ids, "title":title, "key":keys}, columns=['id', 'title', 'key']) return result if __name__ == "__main__": dataFile = 'data/sample_data.csv' data = pd.read_csv(dataFile) result = textrank(data, 10) result.to_csv("result/keys_textrank.csv", index=False)
true
true
f72ccf21d93a0540ee9ca7edb99c6b9d48f98ad0
4,043
py
Python
StandardDataSets/collada/library_geometries/geometry/mesh/vertices/input/position_texcoord_color_normal/position_texcoord_color_normal.py
KhronosGroup/COLLADA-CTS
61f2a560cbb2a06ee62da8025241f6b08d06bfd9
[ "MIT" ]
20
2015-03-19T08:02:57.000Z
2020-10-16T15:16:11.000Z
StandardDataSets/collada/library_geometries/geometry/mesh/vertices/input/position_texcoord_color_normal/position_texcoord_color_normal.py
Acidburn0zzz/COLLADA-CTS
39a36188cf8710bbc003df43ed70b965eb4386bd
[ "MIT" ]
4
2017-04-19T18:42:05.000Z
2017-06-17T03:03:28.000Z
StandardDataSets/collada/library_geometries/geometry/mesh/vertices/input/position_texcoord_color_normal/position_texcoord_color_normal.py
Acidburn0zzz/COLLADA-CTS
39a36188cf8710bbc003df43ed70b965eb4386bd
[ "MIT" ]
10
2015-03-26T02:52:24.000Z
2022-02-24T08:43:48.000Z
# Copyright (C) 2007 - 2009 Khronos Group # Copyright (c) 2012 The Khronos Group Inc. # Permission is hereby granted, free of charge, to any person obtaining a copy of this software and /or associated documentation files (the "Materials "), to deal in the Materials without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Materials, and to permit persons to whom the Materials are furnished to do so, subject to # the following conditions: # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Materials. # THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. # See Core.Logic.FJudgementContext for the information # of the 'context' parameter. # # This sample judging object does the following: # # JudgeBaseline: verifies that app did not crash, the required steps have been performed, # the rendered images match, and the required element(s) has been preserved # JudgeExemplary: returns Baseline status. # JudgeSuperior: returns Baseline status. # We import an assistant script that includes the common verifications # methods. The assistant buffers its checks, so that running them again # does not incurs an unnecessary performance hint. from StandardDataSets.scripts import JudgeAssistant # Please feed your node list here: tagLst = [] attrName = '' attrVal = '' dataToCheck = '' class SimpleJudgingObject: def __init__(self, _tagLst, _attrName, _attrVal, _data): self.tagList = _tagLst self.attrName = _attrName self.attrVal = _attrVal self.dataToCheck = _data self.status_baseline = False self.status_superior = False self.status_exemplary = False self.__assistant = JudgeAssistant.JudgeAssistant() def JudgeBaseline(self, context): # No step should not crash self.__assistant.CheckCrashes(context) # Import/export/validate must exist and pass, while Render must only exist. self.__assistant.CheckSteps(context, ["Import", "Export", "Validate"], ["Render"]) self.status_baseline = self.__assistant.GetResults() return self.status_baseline # To pass intermediate you need to pass basic, this object could also include additional # tests that were specific to the intermediate badge. def JudgeSuperior(self, context): self.status_superior = self.status_baseline return self.status_superior # To pass advanced you need to pass intermediate, this object could also include additional # tests that were specific to the advanced badge def JudgeExemplary(self, context): # if superior fails, no point in further checking if (self.status_superior == False): self.status_exemplary = self.status_superior return self.status_exemplary # Compare the rendered images between import and export # Then compare images against reference test for non equivalence if ( self.__assistant.CompareRenderedImages(context) ): self.__assistant.CompareImagesAgainst(context, "position_texcoord_color", None, None, 5, True, False) self.status_exemplary = self.__assistant.DeferJudgement(context) return self.status_exemplary # This is where all the work occurs: "judgingObject" is an absolutely necessary token. # The dynamic loader looks very specifically for a class instance named "judgingObject". # judgingObject = SimpleJudgingObject(tagLst, attrName, attrVal, dataToCheck);
51.833333
466
0.73955
from StandardDataSets.scripts import JudgeAssistant tagLst = [] attrName = '' attrVal = '' dataToCheck = '' class SimpleJudgingObject: def __init__(self, _tagLst, _attrName, _attrVal, _data): self.tagList = _tagLst self.attrName = _attrName self.attrVal = _attrVal self.dataToCheck = _data self.status_baseline = False self.status_superior = False self.status_exemplary = False self.__assistant = JudgeAssistant.JudgeAssistant() def JudgeBaseline(self, context): self.__assistant.CheckCrashes(context) self.__assistant.CheckSteps(context, ["Import", "Export", "Validate"], ["Render"]) self.status_baseline = self.__assistant.GetResults() return self.status_baseline def JudgeSuperior(self, context): self.status_superior = self.status_baseline return self.status_superior def JudgeExemplary(self, context): if (self.status_superior == False): self.status_exemplary = self.status_superior return self.status_exemplary if ( self.__assistant.CompareRenderedImages(context) ): self.__assistant.CompareImagesAgainst(context, "position_texcoord_color", None, None, 5, True, False) self.status_exemplary = self.__assistant.DeferJudgement(context) return self.status_exemplary judgingObject = SimpleJudgingObject(tagLst, attrName, attrVal, dataToCheck);
true
true
f72ccf7bbd22c8e0b01ca0371dd14f7cf18a0601
2,792
py
Python
tests/unit/utils.py
canonical/hotsos
1960e80a3f7529045c44798b0d3ac27d75036562
[ "Apache-2.0" ]
6
2021-10-01T19:46:14.000Z
2022-03-31T17:05:08.000Z
tests/unit/utils.py
canonical/hotsos
1960e80a3f7529045c44798b0d3ac27d75036562
[ "Apache-2.0" ]
111
2021-10-01T18:18:17.000Z
2022-03-29T12:23:20.000Z
tests/unit/utils.py
canonical/hotsos
1960e80a3f7529045c44798b0d3ac27d75036562
[ "Apache-2.0" ]
10
2021-09-29T14:47:54.000Z
2022-03-18T14:52:16.000Z
import os import shutil import tempfile import unittest # disable for stestr otherwise output is much too verbose from hotsos.core.log import log, logging, setup_logging from hotsos.core.config import setup_config # Must be set prior to other imports TESTS_DIR = os.environ["TESTS_DIR"] DEFAULT_FAKE_ROOT = 'fake_data_root/openstack' setup_config(DATA_ROOT=os.path.join(TESTS_DIR, DEFAULT_FAKE_ROOT)) def is_def_filter(def_filename): """ Filter hotsos.core.ycheck.YDefsLoader._is_def to only match a file with the given name. This permits a unit test to only run the ydef checks that are under test. Note that in order for directory globals to run def_filename must be a relative path that includes the parent directory name e.g. foo/bar.yaml where bar contains the checks and there is also a file called foo/foo.yaml that contains directory globals. """ def inner(_inst, abs_path): # filename may optionally have a parent dir which allows us to permit # directory globals to be run. parent_dir = os.path.dirname(def_filename) """ Ensure we only load/run the yaml def with the given name. """ if parent_dir: # allow directory global to run base_dir = os.path.basename(os.path.dirname(abs_path)) if base_dir != parent_dir: return False if os.path.basename(abs_path) == "{}.yaml".format(parent_dir): return True if abs_path.endswith(def_filename): return True return False return inner class BaseTestCase(unittest.TestCase): def part_output_to_actual(self, output): actual = {} for key, entry in output.items(): actual[key] = entry.data return actual def setUp(self): self.maxDiff = None # ensure locale consistency wherever tests are run os.environ["LANG"] = 'C.UTF-8' self.global_tmp_dir = tempfile.mkdtemp() self.plugin_tmp_dir = tempfile.mkdtemp(dir=self.global_tmp_dir) # Always reset env globals # If a test relies on loading info from defs yaml this needs to be set # to actual plugin name. setup_config(DATA_ROOT=os.path.join(TESTS_DIR, DEFAULT_FAKE_ROOT), PLUGIN_NAME="testplugin", PLUGIN_YAML_DEFS=os.path.join(TESTS_DIR, "defs"), PART_NAME="01part", GLOBAL_TMP_DIR=self.global_tmp_dir, PLUGIN_TMP_DIR=self.plugin_tmp_dir, USE_ALL_LOGS=True) setup_logging(debug_mode=True) log.setLevel(logging.INFO) def tearDown(self): if os.path.isdir(self.plugin_tmp_dir): shutil.rmtree(self.plugin_tmp_dir)
34.469136
79
0.655802
import os import shutil import tempfile import unittest from hotsos.core.log import log, logging, setup_logging from hotsos.core.config import setup_config TESTS_DIR = os.environ["TESTS_DIR"] DEFAULT_FAKE_ROOT = 'fake_data_root/openstack' setup_config(DATA_ROOT=os.path.join(TESTS_DIR, DEFAULT_FAKE_ROOT)) def is_def_filter(def_filename): def inner(_inst, abs_path): parent_dir = os.path.dirname(def_filename) if parent_dir: base_dir = os.path.basename(os.path.dirname(abs_path)) if base_dir != parent_dir: return False if os.path.basename(abs_path) == "{}.yaml".format(parent_dir): return True if abs_path.endswith(def_filename): return True return False return inner class BaseTestCase(unittest.TestCase): def part_output_to_actual(self, output): actual = {} for key, entry in output.items(): actual[key] = entry.data return actual def setUp(self): self.maxDiff = None os.environ["LANG"] = 'C.UTF-8' self.global_tmp_dir = tempfile.mkdtemp() self.plugin_tmp_dir = tempfile.mkdtemp(dir=self.global_tmp_dir) setup_config(DATA_ROOT=os.path.join(TESTS_DIR, DEFAULT_FAKE_ROOT), PLUGIN_NAME="testplugin", PLUGIN_YAML_DEFS=os.path.join(TESTS_DIR, "defs"), PART_NAME="01part", GLOBAL_TMP_DIR=self.global_tmp_dir, PLUGIN_TMP_DIR=self.plugin_tmp_dir, USE_ALL_LOGS=True) setup_logging(debug_mode=True) log.setLevel(logging.INFO) def tearDown(self): if os.path.isdir(self.plugin_tmp_dir): shutil.rmtree(self.plugin_tmp_dir)
true
true
f72cd1215468a583aa37950b7930fb4d28106380
1,428
py
Python
dm_control/mujoco/wrapper/mjbindings/__init__.py
mhauskn/dm_control
b7944e0ed4392924f40a3e5c65b1a93c027b9718
[ "Apache-2.0" ]
2
2021-06-21T05:19:01.000Z
2021-07-02T14:51:16.000Z
dm_control/mujoco/wrapper/mjbindings/__init__.py
akssri/dm_control
1a0914f8df414685f1b336838e39e36fd378e0b9
[ "Apache-2.0" ]
2
2021-10-05T16:03:39.000Z
2022-03-12T01:03:17.000Z
dm_control/mujoco/wrapper/mjbindings/__init__.py
akssri/dm_control
1a0914f8df414685f1b336838e39e36fd378e0b9
[ "Apache-2.0" ]
2
2019-12-10T21:38:03.000Z
2020-12-22T08:42:45.000Z
# Copyright 2017 The dm_control Authors. # # 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 core names of MuJoCo ctypes bindings.""" from absl import logging from dm_control.mujoco.wrapper.mjbindings import constants from dm_control.mujoco.wrapper.mjbindings import enums from dm_control.mujoco.wrapper.mjbindings import sizes from dm_control.mujoco.wrapper.mjbindings import types from dm_control.mujoco.wrapper.mjbindings import wrappers # pylint: disable=g-import-not-at-top try: from dm_control.mujoco.wrapper.mjbindings import functions from dm_control.mujoco.wrapper.mjbindings.functions import mjlib logging.info('MuJoCo library version is: %d', mjlib.mj_version()) except (IOError, OSError): logging.warning('mjbindings failed to import mjlib and other functions. ' 'libmujoco.so may not be accessible.')
40.8
78
0.736695
from absl import logging from dm_control.mujoco.wrapper.mjbindings import constants from dm_control.mujoco.wrapper.mjbindings import enums from dm_control.mujoco.wrapper.mjbindings import sizes from dm_control.mujoco.wrapper.mjbindings import types from dm_control.mujoco.wrapper.mjbindings import wrappers try: from dm_control.mujoco.wrapper.mjbindings import functions from dm_control.mujoco.wrapper.mjbindings.functions import mjlib logging.info('MuJoCo library version is: %d', mjlib.mj_version()) except (IOError, OSError): logging.warning('mjbindings failed to import mjlib and other functions. ' 'libmujoco.so may not be accessible.')
true
true
f72cd2c662bd6709a900fab6f8b72a7287014147
16,047
py
Python
natlas-server/app/admin/routes.py
rosswsnider/natlas
71482c14213eb6b5e9e18365cde5875ed5441523
[ "Apache-2.0" ]
null
null
null
natlas-server/app/admin/routes.py
rosswsnider/natlas
71482c14213eb6b5e9e18365cde5875ed5441523
[ "Apache-2.0" ]
null
null
null
natlas-server/app/admin/routes.py
rosswsnider/natlas
71482c14213eb6b5e9e18365cde5875ed5441523
[ "Apache-2.0" ]
null
null
null
from flask import render_template, redirect, url_for, current_app, flash, Response, abort, request from flask_login import current_user from app import db from app.admin import bp from app.elastic import Elastic from app.admin.forms import * from app.models import User, ScopeItem, ConfigItem, NatlasServices, AgentConfig, Tag from app.auth.email import send_user_invite_email from app.auth.wrappers import isAuthenticated, isAdmin import ipaddress, hashlib @bp.route('/', methods=['GET', 'POST']) @isAuthenticated @isAdmin def admin(): configForm = ConfigForm() configItems = current_app.config if configForm.validate_on_submit(): for fieldname, fieldvalue in configForm.data.items(): if fieldname.upper() in ["SUBMIT", "CSRF_TOKEN"]: continue if fieldname.upper() == "ELASTICSEARCH_URL" and fieldvalue != current_app.config["ELASTICSEARCH_URL"]: # if we've got a new elasticsearch address, update our current handle to elastic current_app.elastic = Elastic(fieldvalue) current_app.config[fieldname.upper()] = fieldvalue confitem = ConfigItem.query.filter_by(name=fieldname.upper()).first() confitem.value=str(fieldvalue) db.session.add(confitem) db.session.commit() return render_template("admin/index.html", configForm=configForm, configItems=configItems) @bp.route('/users', methods=['GET', 'POST']) @isAuthenticated @isAdmin def users(): users = User.query.all() delForm = UserDeleteForm() editForm = UserEditForm() inviteForm = InviteUserForm() if inviteForm.validate_on_submit(): validemail = User.validate_email(inviteForm.email.data) if not validemail: flash("%s does not appear to be a valid, deliverable email address." % inviteForm.email.data, "danger") return redirect(request.referrer) newUser = User(email=validemail) db.session.add(newUser) db.session.commit() send_user_invite_email(newUser) flash('Invitation Sent!', 'success') return redirect(url_for('admin.users')) return render_template("admin/users.html", users=users, delForm=delForm, editForm=editForm, inviteForm=inviteForm) @bp.route('/users/<int:id>/delete', methods=['POST']) @isAuthenticated @isAdmin def deleteUser(id): delForm = UserDeleteForm() if delForm.validate_on_submit(): if current_user.id == id: flash('You can\'t delete yourself!', 'danger') return redirect(url_for('admin.users')) user = User.query.filter_by(id=id).first() User.query.filter_by(id=id).delete() db.session.commit() flash('%s deleted!' % user.email, 'success') return redirect(url_for('admin.users')) else: flash("Form couldn't validate!", 'danger') return redirect(url_for('admin.users')) @bp.route('/users/<int:id>/toggle', methods=['POST']) @isAuthenticated @isAdmin def toggleUser(id): editForm = UserEditForm() if editForm.validate_on_submit(): user = User.query.filter_by(id=id).first() if user.is_admin: admins = User.query.filter_by(is_admin=True).all() if len(admins) == 1: flash('Can\'t delete the last admin!', 'danger') return redirect(url_for('admin.users')) user.is_admin = False db.session.commit() flash('User demoted!', 'success') return redirect(url_for('admin.users')) else: user.is_admin = True db.session.commit() flash('User promoted!', 'success') return redirect(url_for('admin.users')) else: flash("Form couldn't validate!", 'danger') return redirect(url_for('admin.users')) @bp.route('/scope', methods=['GET', 'POST']) @isAuthenticated @isAdmin def scope(): scope = ScopeItem.getScope() scopeSize = current_app.ScopeManager.getScopeSize() if scopeSize == 0: # if it's zero, let's update the app's scopemanager current_app.ScopeManager.update() scopeSize = current_app.ScopeManager.getScopeSize() # if it's zero again that's fine, we just had to check newForm = NewScopeForm() delForm = ScopeDeleteForm() editForm = ScopeToggleForm() importForm = ImportScopeForm() addTagForm = TagScopeForm() addTagForm.tagname.choices = [(row.name, row.name) for row in Tag.query.all()] if newForm.validate_on_submit(): if '/' not in newForm.target.data: newForm.target.data = newForm.target.data + '/32' target = ipaddress.ip_network(newForm.target.data, False) newTarget = ScopeItem(target=target.with_prefixlen, blacklist=False) db.session.add(newTarget) db.session.commit() current_app.ScopeManager.update() flash('%s added!' % newTarget.target, 'success') return redirect(url_for('admin.scope')) return render_template("admin/scope.html", scope=scope, scopeSize=scopeSize, delForm=delForm, editForm=editForm, newForm=newForm, importForm=importForm, \ addTagForm=addTagForm) @bp.route('/blacklist', methods=['GET', 'POST']) @isAuthenticated @isAdmin def blacklist(): scope = ScopeItem.getBlacklist() blacklistSize = current_app.ScopeManager.getBlacklistSize() newForm = NewScopeForm() delForm = ScopeDeleteForm() editForm = ScopeToggleForm() importForm = ImportBlacklistForm() if newForm.validate_on_submit(): if '/' not in newForm.target.data: newForm.target.data = newForm.target.data + '/32' target = ipaddress.ip_network(newForm.target.data, False) newTarget = ScopeItem(target=target.with_prefixlen, blacklist=True) db.session.add(newTarget) db.session.commit() current_app.ScopeManager.update() flash('%s blacklisted!' % newTarget.target, 'success') return redirect(url_for('admin.blacklist')) return render_template("admin/blacklist.html", scope=scope, blacklistSize=blacklistSize, delForm=delForm, editForm=editForm, newForm=newForm, importForm=importForm) @bp.route('/import/<string:scopetype>', methods=['POST']) @isAuthenticated @isAdmin def importScope(scopetype=''): if scopetype == 'blacklist': importBlacklist = True importForm = ImportBlacklistForm() elif scopetype == 'scope': importBlacklist = False importForm = ImportScopeForm() else: abort(404) if importForm.validate_on_submit(): successImport = [] alreadyExists = [] failedImport = [] newScopeItems = importForm.scope.data.split('\n') for item in newScopeItems: item = item.strip() if '/' not in item: item = item + '/32' try: target = ipaddress.ip_network(item, False) except ValueError as e: failedImport.append(item) # this item couldn't be validated as an ip network continue exists = ScopeItem.query.filter_by(target=target.with_prefixlen).first() if exists: alreadyExists.append(target.with_prefixlen) # this range is already a scope item continue newTarget = ScopeItem(target=target.with_prefixlen, blacklist=importBlacklist) db.session.add(newTarget) successImport.append(newTarget.target) db.session.commit() current_app.ScopeManager.update() if len(successImport) > 0: flash('%s targets added to %s!' % (len(successImport), scopetype), 'success') if len(alreadyExists) > 0: flash('%s targets already existed!' % len(alreadyExists), 'info') if len(failedImport) > 0: flash('%s targets failed to import!' % len(failedImport), 'danger') for item in failedImport: flash('%s' % item, 'danger') return redirect(url_for('admin.%s' % scopetype)) else: for field, errors in importForm.errors.items(): for error in errors: flash(error, 'danger') return redirect(url_for('admin.%s' % scopetype)) @bp.route('/export/<string:scopetype>', methods=['GET']) @isAuthenticated @isAdmin def exportScope(scopetype=''): if scopetype == 'blacklist': exportBlacklist = True elif scopetype == 'scope': exportBlacklist = False else: abort(404) items = ScopeItem.query.filter_by(blacklist=exportBlacklist).all() return Response('\n'.join(str(item.target) for item in items), mimetype='text/plain') @bp.route('/scope/<int:id>/delete', methods=['POST']) @isAuthenticated @isAdmin def deleteScopeItem(id): delForm = ScopeDeleteForm() if delForm.validate_on_submit(): item = ScopeItem.query.filter_by(id=id).first() for tag in item.tags: item.tags.remove(tag) ScopeItem.query.filter_by(id=id).delete() db.session.commit() current_app.ScopeManager.update() flash('%s deleted!' % item.target, 'success') return redirect(request.referrer) else: flash("Form couldn't validate!", 'danger') return redirect(request.referrer) @bp.route('/scope/<int:id>/toggle', methods=['POST']) @isAuthenticated @isAdmin def toggleScopeItem(id): toggleForm = ScopeToggleForm() if toggleForm.validate_on_submit(): item = ScopeItem.query.filter_by(id=id).first() if item.blacklist: item.blacklist = False flash('%s removed from blacklist!' % item.target, 'success') else: item.blacklist = True flash('%s blacklisted!' % item.target, 'success') db.session.commit() current_app.ScopeManager.update() return redirect(request.referrer) else: flash("Form couldn't validate!", 'danger') return redirect(request.referrer) @bp.route('/scope/<int:id>/tag', methods=['POST']) @isAuthenticated @isAdmin def tagScopeItem(id): addTagForm = TagScopeForm() addTagForm.tagname.choices = [(row.name, row.name) for row in Tag.query.all()] if addTagForm.validate_on_submit(): scope = ScopeItem.query.get(id) mytag = Tag.query.filter_by(name=addTagForm.tagname.data).first() scope.addTag(mytag) db.session.commit() flash("Tag \"%s\" added to %s" % (mytag.name, scope.target), "success") return redirect(request.referrer) else: flash("Form couldn't validate!", 'danger') return redirect(request.referrer) @bp.route('/scope/<int:id>/untag', methods=['POST']) @isAuthenticated @isAdmin def untagScopeItem(id): delTagForm = TagScopeForm() scope = ScopeItem.query.get(id) delTagForm.tagname.choices = [(row.name, row.name) for row in scope.tags.all()] if delTagForm.validate_on_submit(): mytag = Tag.query.filter_by(name=delTagForm.tagname.data).first() scope.delTag(mytag) db.session.commit() flash("Tag \"%s\" removed from %s" % (mytag.name, scope.target), "success") return redirect(request.referrer) else: flash("Form couldn't validate!", 'danger') return redirect(request.referrer) @bp.route('/services', methods=['GET', 'POST']) @isAuthenticated @isAdmin def services(): uploadForm = ServicesUploadForm(prefix="upload-services") addServiceForm = AddServiceForm(prefix="add-service") addServiceForm.serviceProtocol.choices = [("tcp", "TCP"), ("udp","UDP")] if uploadForm.uploadFile.data and uploadForm.validate_on_submit(): newServicesContent = uploadForm.serviceFile.data.read().decode("utf-8").rstrip('\r\n') newServicesSha = hashlib.sha256(newServicesContent.encode()).hexdigest() if newServicesSha != current_app.current_services["sha256"]: ns = NatlasServices(sha256=newServicesSha, services=newServicesContent) db.session.add(ns) db.session.commit() current_app.current_services = NatlasServices.query.order_by(NatlasServices.id.desc()).first().as_dict() flash("New services file with hash %s has been uploaded." % current_app.current_services["sha256"], "success") return redirect(url_for('admin.services')) else: flash("That file is an exact match for our current services file!", "warning") return redirect(url_for('admin.services')) if addServiceForm.serviceName.data and addServiceForm.validate_on_submit(): newServiceName = addServiceForm.serviceName.data newServicePort = str(addServiceForm.servicePort.data) + '/' + addServiceForm.serviceProtocol.data if '\t' + newServicePort in str(current_app.current_services['services']): flash("A service with port %s already exists!" % newServicePort, "danger") return redirect(url_for('admin.services')) else: newServices = current_app.current_services["services"] + "\n" + newServiceName + "\t" + newServicePort newSha = hashlib.sha256(newServices.encode()).hexdigest() ns = NatlasServices(sha256=newSha, services=newServices) db.session.add(ns) db.session.commit() current_app.current_services = NatlasServices.query.order_by(NatlasServices.id.desc()).first().as_dict() flash("New service %s on port %s has been added." % (newServiceName, newServicePort), "success") return redirect(url_for('admin.services')) return render_template('admin/services.html', uploadForm=uploadForm, addServiceForm=addServiceForm, current_services=current_app.current_services, servlist=current_app.current_services['as_list']) @bp.route('/services/export', methods=['GET']) @isAuthenticated @isAdmin def exportServices(): return Response(str(current_app.current_services["services"]), mimetype='text/plain') @bp.route('/agents', methods=['GET', 'POST']) @isAuthenticated @isAdmin def agentConfig(): agentConfig = AgentConfig.query.get(1) agentForm = AgentConfigForm(obj=agentConfig) # pass the model to the form to populate addScriptForm = AddScriptForm(prefix="add-script") delScriptForm = DeleteForm(prefix="del-script") if agentForm.validate_on_submit(): agentForm.populate_obj(agentConfig) # populate the object from the form data db.session.commit() current_app.agentConfig = agentConfig.as_dict() return render_template('admin/agents.html', agentForm=agentForm, scripts=current_app.agentScripts, \ addScriptForm=addScriptForm, delScriptForm=delScriptForm) @bp.route('/agents/script/add', methods=['POST']) @isAuthenticated @isAdmin def addScript(): addScriptForm = AddScriptForm(prefix="add-script") if addScriptForm.validate_on_submit(): newscript = AgentScript(name=addScriptForm.scriptName.data) db.session.add(newscript) db.session.commit() current_app.agentScripts = AgentScript.query.all() current_app.agentScriptStr = AgentScript.getScriptsString(current_app.agentScripts) flash("%s successfully added to scripts" % newscript.name, "success") return redirect(request.referrer) else: flash("%s couldn't be added to scripts" % addScriptForm.scriptName.data, "danger") return redirect(request.referrer) @bp.route('/agents/script/<string:name>/delete', methods=['POST']) @isAuthenticated @isAdmin def deleteScript(name): deleteForm = DeleteForm() if deleteForm.validate_on_submit(): delScript = AgentScript.query.filter_by(name=name).first() if delScript: db.session.delete(delScript) db.session.commit() current_app.agentScripts = AgentScript.query.all() current_app.agentScriptStr = AgentScript.getScriptsString(current_app.agentScripts) flash("%s successfully deleted." % name, "success") else: flash("%s doesn't exist" % name, "danger") return redirect(request.referrer) @bp.route('/scans/delete/<scan_id>', methods=['POST']) @isAuthenticated @isAdmin def deleteScan(scan_id): delForm = DeleteForm() if delForm.validate_on_submit(): deleted = current_app.elastic.delete_scan(scan_id) if deleted in [1,2]: flash("Successfully deleted scan %s." % scan_id, "success") if request.referrer: if scan_id in request.referrer: redirectLoc = request.referrer.rsplit(scan_id)[0] else: redirectLoc = request.referrer else: redirectLoc = url_for('main.search') return redirect(redirectLoc) else: flash("Could not delete scan %s." % scan_id, "danger") return redirect(request.referrer or url_for('main.search')) else: flash("Couldn't validate form!") return redirect(request.referrer) @bp.route('/hosts/delete/<ip>', methods=['POST']) @isAuthenticated @isAdmin def deleteHost(ip): delForm = DeleteForm() if delForm.validate_on_submit(): deleted = current_app.elastic.delete_host(ip) if deleted > 0: flash("Successfully deleted host %s" % ip, "success") return redirect(url_for('main.search')) else: flash("Couldn't delete host: %s" % ip, "danger") else: flash("Couldn't validate form!") return redirect(request.referrer) @bp.route('/tags', methods=['GET', 'POST']) @isAuthenticated @isAdmin def tags(): tags = Tag.query.all() addForm = AddTagForm() if addForm.validate_on_submit(): newTag = Tag(name=addForm.tagname.data.lower()) db.session.add(newTag) db.session.commit() flash('Successfully added tag %s' % newTag.name, 'success') return redirect(url_for('admin.tags')) return render_template("admin/tags.html", tags=tags, addForm=addForm)
36.141892
197
0.737334
from flask import render_template, redirect, url_for, current_app, flash, Response, abort, request from flask_login import current_user from app import db from app.admin import bp from app.elastic import Elastic from app.admin.forms import * from app.models import User, ScopeItem, ConfigItem, NatlasServices, AgentConfig, Tag from app.auth.email import send_user_invite_email from app.auth.wrappers import isAuthenticated, isAdmin import ipaddress, hashlib @bp.route('/', methods=['GET', 'POST']) @isAuthenticated @isAdmin def admin(): configForm = ConfigForm() configItems = current_app.config if configForm.validate_on_submit(): for fieldname, fieldvalue in configForm.data.items(): if fieldname.upper() in ["SUBMIT", "CSRF_TOKEN"]: continue if fieldname.upper() == "ELASTICSEARCH_URL" and fieldvalue != current_app.config["ELASTICSEARCH_URL"]: current_app.elastic = Elastic(fieldvalue) current_app.config[fieldname.upper()] = fieldvalue confitem = ConfigItem.query.filter_by(name=fieldname.upper()).first() confitem.value=str(fieldvalue) db.session.add(confitem) db.session.commit() return render_template("admin/index.html", configForm=configForm, configItems=configItems) @bp.route('/users', methods=['GET', 'POST']) @isAuthenticated @isAdmin def users(): users = User.query.all() delForm = UserDeleteForm() editForm = UserEditForm() inviteForm = InviteUserForm() if inviteForm.validate_on_submit(): validemail = User.validate_email(inviteForm.email.data) if not validemail: flash("%s does not appear to be a valid, deliverable email address." % inviteForm.email.data, "danger") return redirect(request.referrer) newUser = User(email=validemail) db.session.add(newUser) db.session.commit() send_user_invite_email(newUser) flash('Invitation Sent!', 'success') return redirect(url_for('admin.users')) return render_template("admin/users.html", users=users, delForm=delForm, editForm=editForm, inviteForm=inviteForm) @bp.route('/users/<int:id>/delete', methods=['POST']) @isAuthenticated @isAdmin def deleteUser(id): delForm = UserDeleteForm() if delForm.validate_on_submit(): if current_user.id == id: flash('You can\'t delete yourself!', 'danger') return redirect(url_for('admin.users')) user = User.query.filter_by(id=id).first() User.query.filter_by(id=id).delete() db.session.commit() flash('%s deleted!' % user.email, 'success') return redirect(url_for('admin.users')) else: flash("Form couldn't validate!", 'danger') return redirect(url_for('admin.users')) @bp.route('/users/<int:id>/toggle', methods=['POST']) @isAuthenticated @isAdmin def toggleUser(id): editForm = UserEditForm() if editForm.validate_on_submit(): user = User.query.filter_by(id=id).first() if user.is_admin: admins = User.query.filter_by(is_admin=True).all() if len(admins) == 1: flash('Can\'t delete the last admin!', 'danger') return redirect(url_for('admin.users')) user.is_admin = False db.session.commit() flash('User demoted!', 'success') return redirect(url_for('admin.users')) else: user.is_admin = True db.session.commit() flash('User promoted!', 'success') return redirect(url_for('admin.users')) else: flash("Form couldn't validate!", 'danger') return redirect(url_for('admin.users')) @bp.route('/scope', methods=['GET', 'POST']) @isAuthenticated @isAdmin def scope(): scope = ScopeItem.getScope() scopeSize = current_app.ScopeManager.getScopeSize() if scopeSize == 0: # if it's zero, let's update the app's scopemanager current_app.ScopeManager.update() scopeSize = current_app.ScopeManager.getScopeSize() newForm = NewScopeForm() delForm = ScopeDeleteForm() editForm = ScopeToggleForm() importForm = ImportScopeForm() addTagForm = TagScopeForm() addTagForm.tagname.choices = [(row.name, row.name) for row in Tag.query.all()] if newForm.validate_on_submit(): if '/' not in newForm.target.data: newForm.target.data = newForm.target.data + '/32' target = ipaddress.ip_network(newForm.target.data, False) newTarget = ScopeItem(target=target.with_prefixlen, blacklist=False) db.session.add(newTarget) db.session.commit() current_app.ScopeManager.update() flash('%s added!' % newTarget.target, 'success') return redirect(url_for('admin.scope')) return render_template("admin/scope.html", scope=scope, scopeSize=scopeSize, delForm=delForm, editForm=editForm, newForm=newForm, importForm=importForm, \ addTagForm=addTagForm) @bp.route('/blacklist', methods=['GET', 'POST']) @isAuthenticated @isAdmin def blacklist(): scope = ScopeItem.getBlacklist() blacklistSize = current_app.ScopeManager.getBlacklistSize() newForm = NewScopeForm() delForm = ScopeDeleteForm() editForm = ScopeToggleForm() importForm = ImportBlacklistForm() if newForm.validate_on_submit(): if '/' not in newForm.target.data: newForm.target.data = newForm.target.data + '/32' target = ipaddress.ip_network(newForm.target.data, False) newTarget = ScopeItem(target=target.with_prefixlen, blacklist=True) db.session.add(newTarget) db.session.commit() current_app.ScopeManager.update() flash('%s blacklisted!' % newTarget.target, 'success') return redirect(url_for('admin.blacklist')) return render_template("admin/blacklist.html", scope=scope, blacklistSize=blacklistSize, delForm=delForm, editForm=editForm, newForm=newForm, importForm=importForm) @bp.route('/import/<string:scopetype>', methods=['POST']) @isAuthenticated @isAdmin def importScope(scopetype=''): if scopetype == 'blacklist': importBlacklist = True importForm = ImportBlacklistForm() elif scopetype == 'scope': importBlacklist = False importForm = ImportScopeForm() else: abort(404) if importForm.validate_on_submit(): successImport = [] alreadyExists = [] failedImport = [] newScopeItems = importForm.scope.data.split('\n') for item in newScopeItems: item = item.strip() if '/' not in item: item = item + '/32' try: target = ipaddress.ip_network(item, False) except ValueError as e: failedImport.append(item) continue exists = ScopeItem.query.filter_by(target=target.with_prefixlen).first() if exists: alreadyExists.append(target.with_prefixlen) # this range is already a scope item continue newTarget = ScopeItem(target=target.with_prefixlen, blacklist=importBlacklist) db.session.add(newTarget) successImport.append(newTarget.target) db.session.commit() current_app.ScopeManager.update() if len(successImport) > 0: flash('%s targets added to %s!' % (len(successImport), scopetype), 'success') if len(alreadyExists) > 0: flash('%s targets already existed!' % len(alreadyExists), 'info') if len(failedImport) > 0: flash('%s targets failed to import!' % len(failedImport), 'danger') for item in failedImport: flash('%s' % item, 'danger') return redirect(url_for('admin.%s' % scopetype)) else: for field, errors in importForm.errors.items(): for error in errors: flash(error, 'danger') return redirect(url_for('admin.%s' % scopetype)) @bp.route('/export/<string:scopetype>', methods=['GET']) @isAuthenticated @isAdmin def exportScope(scopetype=''): if scopetype == 'blacklist': exportBlacklist = True elif scopetype == 'scope': exportBlacklist = False else: abort(404) items = ScopeItem.query.filter_by(blacklist=exportBlacklist).all() return Response('\n'.join(str(item.target) for item in items), mimetype='text/plain') @bp.route('/scope/<int:id>/delete', methods=['POST']) @isAuthenticated @isAdmin def deleteScopeItem(id): delForm = ScopeDeleteForm() if delForm.validate_on_submit(): item = ScopeItem.query.filter_by(id=id).first() for tag in item.tags: item.tags.remove(tag) ScopeItem.query.filter_by(id=id).delete() db.session.commit() current_app.ScopeManager.update() flash('%s deleted!' % item.target, 'success') return redirect(request.referrer) else: flash("Form couldn't validate!", 'danger') return redirect(request.referrer) @bp.route('/scope/<int:id>/toggle', methods=['POST']) @isAuthenticated @isAdmin def toggleScopeItem(id): toggleForm = ScopeToggleForm() if toggleForm.validate_on_submit(): item = ScopeItem.query.filter_by(id=id).first() if item.blacklist: item.blacklist = False flash('%s removed from blacklist!' % item.target, 'success') else: item.blacklist = True flash('%s blacklisted!' % item.target, 'success') db.session.commit() current_app.ScopeManager.update() return redirect(request.referrer) else: flash("Form couldn't validate!", 'danger') return redirect(request.referrer) @bp.route('/scope/<int:id>/tag', methods=['POST']) @isAuthenticated @isAdmin def tagScopeItem(id): addTagForm = TagScopeForm() addTagForm.tagname.choices = [(row.name, row.name) for row in Tag.query.all()] if addTagForm.validate_on_submit(): scope = ScopeItem.query.get(id) mytag = Tag.query.filter_by(name=addTagForm.tagname.data).first() scope.addTag(mytag) db.session.commit() flash("Tag \"%s\" added to %s" % (mytag.name, scope.target), "success") return redirect(request.referrer) else: flash("Form couldn't validate!", 'danger') return redirect(request.referrer) @bp.route('/scope/<int:id>/untag', methods=['POST']) @isAuthenticated @isAdmin def untagScopeItem(id): delTagForm = TagScopeForm() scope = ScopeItem.query.get(id) delTagForm.tagname.choices = [(row.name, row.name) for row in scope.tags.all()] if delTagForm.validate_on_submit(): mytag = Tag.query.filter_by(name=delTagForm.tagname.data).first() scope.delTag(mytag) db.session.commit() flash("Tag \"%s\" removed from %s" % (mytag.name, scope.target), "success") return redirect(request.referrer) else: flash("Form couldn't validate!", 'danger') return redirect(request.referrer) @bp.route('/services', methods=['GET', 'POST']) @isAuthenticated @isAdmin def services(): uploadForm = ServicesUploadForm(prefix="upload-services") addServiceForm = AddServiceForm(prefix="add-service") addServiceForm.serviceProtocol.choices = [("tcp", "TCP"), ("udp","UDP")] if uploadForm.uploadFile.data and uploadForm.validate_on_submit(): newServicesContent = uploadForm.serviceFile.data.read().decode("utf-8").rstrip('\r\n') newServicesSha = hashlib.sha256(newServicesContent.encode()).hexdigest() if newServicesSha != current_app.current_services["sha256"]: ns = NatlasServices(sha256=newServicesSha, services=newServicesContent) db.session.add(ns) db.session.commit() current_app.current_services = NatlasServices.query.order_by(NatlasServices.id.desc()).first().as_dict() flash("New services file with hash %s has been uploaded." % current_app.current_services["sha256"], "success") return redirect(url_for('admin.services')) else: flash("That file is an exact match for our current services file!", "warning") return redirect(url_for('admin.services')) if addServiceForm.serviceName.data and addServiceForm.validate_on_submit(): newServiceName = addServiceForm.serviceName.data newServicePort = str(addServiceForm.servicePort.data) + '/' + addServiceForm.serviceProtocol.data if '\t' + newServicePort in str(current_app.current_services['services']): flash("A service with port %s already exists!" % newServicePort, "danger") return redirect(url_for('admin.services')) else: newServices = current_app.current_services["services"] + "\n" + newServiceName + "\t" + newServicePort newSha = hashlib.sha256(newServices.encode()).hexdigest() ns = NatlasServices(sha256=newSha, services=newServices) db.session.add(ns) db.session.commit() current_app.current_services = NatlasServices.query.order_by(NatlasServices.id.desc()).first().as_dict() flash("New service %s on port %s has been added." % (newServiceName, newServicePort), "success") return redirect(url_for('admin.services')) return render_template('admin/services.html', uploadForm=uploadForm, addServiceForm=addServiceForm, current_services=current_app.current_services, servlist=current_app.current_services['as_list']) @bp.route('/services/export', methods=['GET']) @isAuthenticated @isAdmin def exportServices(): return Response(str(current_app.current_services["services"]), mimetype='text/plain') @bp.route('/agents', methods=['GET', 'POST']) @isAuthenticated @isAdmin def agentConfig(): agentConfig = AgentConfig.query.get(1) agentForm = AgentConfigForm(obj=agentConfig) # pass the model to the form to populate addScriptForm = AddScriptForm(prefix="add-script") delScriptForm = DeleteForm(prefix="del-script") if agentForm.validate_on_submit(): agentForm.populate_obj(agentConfig) # populate the object from the form data db.session.commit() current_app.agentConfig = agentConfig.as_dict() return render_template('admin/agents.html', agentForm=agentForm, scripts=current_app.agentScripts, \ addScriptForm=addScriptForm, delScriptForm=delScriptForm) @bp.route('/agents/script/add', methods=['POST']) @isAuthenticated @isAdmin def addScript(): addScriptForm = AddScriptForm(prefix="add-script") if addScriptForm.validate_on_submit(): newscript = AgentScript(name=addScriptForm.scriptName.data) db.session.add(newscript) db.session.commit() current_app.agentScripts = AgentScript.query.all() current_app.agentScriptStr = AgentScript.getScriptsString(current_app.agentScripts) flash("%s successfully added to scripts" % newscript.name, "success") return redirect(request.referrer) else: flash("%s couldn't be added to scripts" % addScriptForm.scriptName.data, "danger") return redirect(request.referrer) @bp.route('/agents/script/<string:name>/delete', methods=['POST']) @isAuthenticated @isAdmin def deleteScript(name): deleteForm = DeleteForm() if deleteForm.validate_on_submit(): delScript = AgentScript.query.filter_by(name=name).first() if delScript: db.session.delete(delScript) db.session.commit() current_app.agentScripts = AgentScript.query.all() current_app.agentScriptStr = AgentScript.getScriptsString(current_app.agentScripts) flash("%s successfully deleted." % name, "success") else: flash("%s doesn't exist" % name, "danger") return redirect(request.referrer) @bp.route('/scans/delete/<scan_id>', methods=['POST']) @isAuthenticated @isAdmin def deleteScan(scan_id): delForm = DeleteForm() if delForm.validate_on_submit(): deleted = current_app.elastic.delete_scan(scan_id) if deleted in [1,2]: flash("Successfully deleted scan %s." % scan_id, "success") if request.referrer: if scan_id in request.referrer: redirectLoc = request.referrer.rsplit(scan_id)[0] else: redirectLoc = request.referrer else: redirectLoc = url_for('main.search') return redirect(redirectLoc) else: flash("Could not delete scan %s." % scan_id, "danger") return redirect(request.referrer or url_for('main.search')) else: flash("Couldn't validate form!") return redirect(request.referrer) @bp.route('/hosts/delete/<ip>', methods=['POST']) @isAuthenticated @isAdmin def deleteHost(ip): delForm = DeleteForm() if delForm.validate_on_submit(): deleted = current_app.elastic.delete_host(ip) if deleted > 0: flash("Successfully deleted host %s" % ip, "success") return redirect(url_for('main.search')) else: flash("Couldn't delete host: %s" % ip, "danger") else: flash("Couldn't validate form!") return redirect(request.referrer) @bp.route('/tags', methods=['GET', 'POST']) @isAuthenticated @isAdmin def tags(): tags = Tag.query.all() addForm = AddTagForm() if addForm.validate_on_submit(): newTag = Tag(name=addForm.tagname.data.lower()) db.session.add(newTag) db.session.commit() flash('Successfully added tag %s' % newTag.name, 'success') return redirect(url_for('admin.tags')) return render_template("admin/tags.html", tags=tags, addForm=addForm)
true
true
f72cd336a36193490a287d751208899587977749
3,822
py
Python
CAIL2020/cocr/torchocr/datasets/icdar15/ICDAR15CropSave.py
ShenDezhou/CAIL
c4cfa98ab4ecedbce34a7a5a186830486047540c
[ "Apache-2.0" ]
71
2020-07-16T01:49:27.000Z
2022-03-27T16:55:00.000Z
CAIL2020/cocr/torchocr/datasets/icdar15/ICDAR15CropSave.py
ShenDezhou/CAIL
c4cfa98ab4ecedbce34a7a5a186830486047540c
[ "Apache-2.0" ]
11
2020-09-18T14:26:25.000Z
2022-02-09T23:49:33.000Z
CAIL2020/cocr/torchocr/datasets/icdar15/ICDAR15CropSave.py
ShenDezhou/CAIL
c4cfa98ab4ecedbce34a7a5a186830486047540c
[ "Apache-2.0" ]
16
2020-07-15T07:24:30.000Z
2022-03-19T05:41:11.000Z
''' @Author: Jeffery Sheng (Zhenfei Sheng) @Time: 2020/5/21 18:34 @File: ICDAR15CropSave.py ''' import os import cv2 from glob import glob from tqdm import tqdm class icdar2015CropSave: def __init__(self, img_dir :str, gt_dir :str, save_data_dir :str, train_val_split_ratio: float or None=0.1): self.save_id = 1 self.img_dir = os.path.abspath(img_dir) self.gt_dir = os.path.abspath(gt_dir) if not os.path.exists(save_data_dir): os.mkdir(save_data_dir) self.save_data_dir = save_data_dir self.train_val_split_ratio = train_val_split_ratio def crop_save(self) -> None: all_img_paths = glob(os.path.join(self.img_dir, '*.jpg')) all_gt_paths = glob(os.path.join(self.gt_dir, '*.txt')) # check length assert len(all_img_paths) == len(all_gt_paths) # create lists to store text-line text_lines = list() # start to crop and save for img_path in tqdm(all_img_paths): img = cv2.imread(img_path) gt_path = os.path.join(self.gt_dir, 'gt_' + os.path.basename(img_path).replace('.jpg', '.txt')) with open(gt_path, 'r', encoding='utf-8-sig') as file: lines = file.readlines() for line in lines: line = line.strip().split(',') # get points x1, y1, x2, y2, x3, y3, x4, y4 = list(map(int, line[: 8])) # get transcript trans = line[8] if trans in {'', '*', '###'}: continue # check & make dir save_img_dir = os.path.join(self.save_data_dir, 'images') if not os.path.exists(save_img_dir): os.mkdir(save_img_dir) # build save img path save_img_path = os.path.join(save_img_dir, f'textbox_{self.save_id}.jpg') # check if rectangle if len({x1, y1, x2, y2, x3, y3, x4, y4}) == 4: # save rectangle cv2.imwrite(save_img_path, img[y1: y4, x1: x2]) # if polygon, save minimize circumscribed rectangle else: x_min, x_max = min((x1, x2, x3, x4)), max((x1, x2, x3, x4)) y_min, y_max = min((y1, y2, y3, y4)), max((y1, y2, y3, y4)) cv2.imwrite(save_img_path, img[y_min: y_max, x_min: x_max]) # save to text-line text_lines.append(f'textbox_{self.save_id}.jpg\t{trans}\n') # save_id self increase self.save_id += 1 if self.train_val_split_ratio: train = text_lines[: int(round((1-self.train_val_split_ratio)*self.save_id))] val = text_lines[int(round((1-self.train_val_split_ratio)*self.save_id)): ] # save text-line file with open(os.path.join(self.save_data_dir, 'train.txt'), 'w') as save_file: save_file.writelines(train) with open(os.path.join(self.save_data_dir, 'val.txt'), 'w') as save_file: save_file.writelines(val) print(f'{self.save_id-1} text-box images and 2 text-line file are saved.') else: # save text-line file with open(os.path.join(self.save_data_dir, 'train.txt'), 'w') as save_file: save_file.writelines(text_lines) print(f'{self.save_id-1} text-box images and 1 text-line file are saved.') if __name__ == '__main__': img_dir = '/data/disk7/private/szf/Datasets/ICDAR2015/train' gt_dir = '/data/disk7/private/szf/Datasets/ICDAR2015/train_local_trans' save_data_dir = '/data/disk7/private/szf/Datasets/ICDAR2015/data' icdar2015CropSave(img_dir, gt_dir, save_data_dir).crop_save()
45.5
107
0.570905
import os import cv2 from glob import glob from tqdm import tqdm class icdar2015CropSave: def __init__(self, img_dir :str, gt_dir :str, save_data_dir :str, train_val_split_ratio: float or None=0.1): self.save_id = 1 self.img_dir = os.path.abspath(img_dir) self.gt_dir = os.path.abspath(gt_dir) if not os.path.exists(save_data_dir): os.mkdir(save_data_dir) self.save_data_dir = save_data_dir self.train_val_split_ratio = train_val_split_ratio def crop_save(self) -> None: all_img_paths = glob(os.path.join(self.img_dir, '*.jpg')) all_gt_paths = glob(os.path.join(self.gt_dir, '*.txt')) assert len(all_img_paths) == len(all_gt_paths) text_lines = list() for img_path in tqdm(all_img_paths): img = cv2.imread(img_path) gt_path = os.path.join(self.gt_dir, 'gt_' + os.path.basename(img_path).replace('.jpg', '.txt')) with open(gt_path, 'r', encoding='utf-8-sig') as file: lines = file.readlines() for line in lines: line = line.strip().split(',') x1, y1, x2, y2, x3, y3, x4, y4 = list(map(int, line[: 8])) trans = line[8] if trans in {'', '*', '###'}: continue save_img_dir = os.path.join(self.save_data_dir, 'images') if not os.path.exists(save_img_dir): os.mkdir(save_img_dir) save_img_path = os.path.join(save_img_dir, f'textbox_{self.save_id}.jpg') if len({x1, y1, x2, y2, x3, y3, x4, y4}) == 4: cv2.imwrite(save_img_path, img[y1: y4, x1: x2]) else: x_min, x_max = min((x1, x2, x3, x4)), max((x1, x2, x3, x4)) y_min, y_max = min((y1, y2, y3, y4)), max((y1, y2, y3, y4)) cv2.imwrite(save_img_path, img[y_min: y_max, x_min: x_max]) text_lines.append(f'textbox_{self.save_id}.jpg\t{trans}\n') self.save_id += 1 if self.train_val_split_ratio: train = text_lines[: int(round((1-self.train_val_split_ratio)*self.save_id))] val = text_lines[int(round((1-self.train_val_split_ratio)*self.save_id)): ] with open(os.path.join(self.save_data_dir, 'train.txt'), 'w') as save_file: save_file.writelines(train) with open(os.path.join(self.save_data_dir, 'val.txt'), 'w') as save_file: save_file.writelines(val) print(f'{self.save_id-1} text-box images and 2 text-line file are saved.') else: with open(os.path.join(self.save_data_dir, 'train.txt'), 'w') as save_file: save_file.writelines(text_lines) print(f'{self.save_id-1} text-box images and 1 text-line file are saved.') if __name__ == '__main__': img_dir = '/data/disk7/private/szf/Datasets/ICDAR2015/train' gt_dir = '/data/disk7/private/szf/Datasets/ICDAR2015/train_local_trans' save_data_dir = '/data/disk7/private/szf/Datasets/ICDAR2015/data' icdar2015CropSave(img_dir, gt_dir, save_data_dir).crop_save()
true
true
f72cd357fb91883d347cb40323f2b77a59d3007f
1,228
py
Python
couchcrdt/counter.py
drsm79/couch-crdt
1717a8b03a488793984d7209f6da78c395b3477f
[ "Apache-2.0" ]
null
null
null
couchcrdt/counter.py
drsm79/couch-crdt
1717a8b03a488793984d7209f6da78c395b3477f
[ "Apache-2.0" ]
null
null
null
couchcrdt/counter.py
drsm79/couch-crdt
1717a8b03a488793984d7209f6da78c395b3477f
[ "Apache-2.0" ]
null
null
null
from crdt import CRDT class DistributedCounter(CRDT): def add(self, number): return self + number def remove(self, number): return self - number def inc(self): """ Increase the counters value by one """ return self + 1 def dec(self): """ Reduce the counters value by one """ return self - 1 def __abs__(self): """ Do the set operation and return the iterable over the result """ if self.state is None: return self.value if self.value is None: return self.state return self.value + self.state def __repr__(self): return "%s" % self.__abs__() def __add__(self, number): if isinstance(self.state, (int, long, float, complex)): self._update(self.state + number) else: self._update(number) return self def __sub__(self, number): if isinstance(self.state, (int, long, float, complex)): self._update(self.state - number) else: self._update(-number) return self def _parse(self, data): return data.json()['rows'][0]['value']
23.169811
68
0.545603
from crdt import CRDT class DistributedCounter(CRDT): def add(self, number): return self + number def remove(self, number): return self - number def inc(self): return self + 1 def dec(self): return self - 1 def __abs__(self): if self.state is None: return self.value if self.value is None: return self.state return self.value + self.state def __repr__(self): return "%s" % self.__abs__() def __add__(self, number): if isinstance(self.state, (int, long, float, complex)): self._update(self.state + number) else: self._update(number) return self def __sub__(self, number): if isinstance(self.state, (int, long, float, complex)): self._update(self.state - number) else: self._update(-number) return self def _parse(self, data): return data.json()['rows'][0]['value']
true
true
f72cd35995de0da138e9526f9b56429d06c45c97
359,560
py
Python
nova/virt/libvirt/driver_back.py
xuweiliang/Codelibrary
54e45b2daa205132c05b0ff5a2c3db7fca2853a7
[ "Apache-2.0" ]
null
null
null
nova/virt/libvirt/driver_back.py
xuweiliang/Codelibrary
54e45b2daa205132c05b0ff5a2c3db7fca2853a7
[ "Apache-2.0" ]
null
null
null
nova/virt/libvirt/driver_back.py
xuweiliang/Codelibrary
54e45b2daa205132c05b0ff5a2c3db7fca2853a7
[ "Apache-2.0" ]
null
null
null
# Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # Copyright (c) 2010 Citrix Systems, Inc. # Copyright (c) 2011 Piston Cloud Computing, Inc # Copyright (c) 2012 University Of Minho # (c) Copyright 2013 Hewlett-Packard Development Company, L.P. # # 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. """ A connection to a hypervisor through libvirt. Supports KVM, LXC, QEMU, UML, XEN and Parallels. """ import string import collections from collections import deque import contextlib import errno import functools import glob import itertools import mmap import operator import os import shutil import tempfile import time import uuid import eventlet from eventlet import greenthread from eventlet import tpool from lxml import etree from os_brick.initiator import connector from oslo_concurrency import processutils from oslo_log import log as logging from oslo_serialization import jsonutils from oslo_service import loopingcall from oslo_utils import excutils from oslo_utils import fileutils from oslo_utils import importutils from oslo_utils import strutils from oslo_utils import timeutils from oslo_utils import units import six from six.moves import range from nova.api.metadata import base as instance_metadata from nova import block_device from nova.compute import arch from nova.compute import hv_type from nova.compute import power_state from nova.compute import task_states from nova.compute import utils as compute_utils from nova.compute import vm_mode import nova.conf from nova.console import serial as serial_console from nova.console import type as ctype from nova import context as nova_context from nova import exception from nova.i18n import _ from nova.i18n import _LE from nova.i18n import _LI from nova.i18n import _LW from nova import image from nova.network import model as network_model from nova import objects from nova.objects import fields from nova.objects import migrate_data as migrate_data_obj from nova.pci import manager as pci_manager from nova.pci import utils as pci_utils from nova import utils from nova import version from nova.virt import block_device as driver_block_device from nova.virt import configdrive from nova.virt import diagnostics from nova.virt.disk import api as disk_api from nova.virt.disk.vfs import guestfs from nova.virt import driver from nova.virt import firewall from nova.virt import hardware from nova.virt.image import model as imgmodel from nova.virt import images from nova.virt.libvirt import blockinfo from nova.virt.libvirt import config as vconfig from nova.virt.libvirt import firewall as libvirt_firewall from nova.virt.libvirt import guest as libvirt_guest from nova.virt.libvirt import host from nova.virt.libvirt import imagebackend from nova.virt.libvirt import imagecache from nova.virt.libvirt import instancejobtracker from nova.virt.libvirt import migration as libvirt_migrate from nova.virt.libvirt.storage import dmcrypt from nova.virt.libvirt.storage import lvm from nova.virt.libvirt.storage import rbd_utils from nova.virt.libvirt import utils as libvirt_utils from nova.virt.libvirt import vif as libvirt_vif from nova.virt.libvirt.volume import remotefs from nova.virt import netutils from nova.virt import watchdog_actions from nova.volume import cinder from nova.volume import encryptors libvirt = None uefi_logged = False LOG = logging.getLogger(__name__) CONF = nova.conf.CONF DEFAULT_FIREWALL_DRIVER = "%s.%s" % ( libvirt_firewall.__name__, libvirt_firewall.IptablesFirewallDriver.__name__) DEFAULT_UEFI_LOADER_PATH = { "x86_64": "/usr/share/OVMF/OVMF_CODE.fd", "aarch64": "/usr/share/AAVMF/AAVMF_CODE.fd" } MAX_CONSOLE_BYTES = 100 * units.Ki # The libvirt driver will prefix any disable reason codes with this string. DISABLE_PREFIX = 'AUTO: ' # Disable reason for the service which was enabled or disabled without reason DISABLE_REASON_UNDEFINED = None # Guest config console string CONSOLE = "console=tty0 console=ttyS0" GuestNumaConfig = collections.namedtuple( 'GuestNumaConfig', ['cpuset', 'cputune', 'numaconfig', 'numatune']) libvirt_volume_drivers = [ 'iscsi=nova.virt.libvirt.volume.iscsi.LibvirtISCSIVolumeDriver', 'iser=nova.virt.libvirt.volume.iser.LibvirtISERVolumeDriver', 'local=nova.virt.libvirt.volume.volume.LibvirtVolumeDriver', 'fake=nova.virt.libvirt.volume.volume.LibvirtFakeVolumeDriver', 'rbd=nova.virt.libvirt.volume.net.LibvirtNetVolumeDriver', 'sheepdog=nova.virt.libvirt.volume.net.LibvirtNetVolumeDriver', 'nfs=nova.virt.libvirt.volume.nfs.LibvirtNFSVolumeDriver', 'smbfs=nova.virt.libvirt.volume.smbfs.LibvirtSMBFSVolumeDriver', 'aoe=nova.virt.libvirt.volume.aoe.LibvirtAOEVolumeDriver', 'glusterfs=' 'nova.virt.libvirt.volume.glusterfs.LibvirtGlusterfsVolumeDriver', 'fibre_channel=' 'nova.virt.libvirt.volume.fibrechannel.' 'LibvirtFibreChannelVolumeDriver', 'scality=nova.virt.libvirt.volume.scality.LibvirtScalityVolumeDriver', 'gpfs=nova.virt.libvirt.volume.gpfs.LibvirtGPFSVolumeDriver', 'quobyte=nova.virt.libvirt.volume.quobyte.LibvirtQuobyteVolumeDriver', 'hgst=nova.virt.libvirt.volume.hgst.LibvirtHGSTVolumeDriver', 'scaleio=nova.virt.libvirt.volume.scaleio.LibvirtScaleIOVolumeDriver', 'disco=nova.virt.libvirt.volume.disco.LibvirtDISCOVolumeDriver', 'vzstorage=' 'nova.virt.libvirt.volume.vzstorage.LibvirtVZStorageVolumeDriver', ] def patch_tpool_proxy(): """eventlet.tpool.Proxy doesn't work with old-style class in __str__() or __repr__() calls. See bug #962840 for details. We perform a monkey patch to replace those two instance methods. """ def str_method(self): return str(self._obj) def repr_method(self): return repr(self._obj) tpool.Proxy.__str__ = str_method tpool.Proxy.__repr__ = repr_method patch_tpool_proxy() # For information about when MIN_LIBVIRT_VERSION and # NEXT_MIN_LIBVIRT_VERSION can be changed, consult # # https://wiki.openstack.org/wiki/LibvirtDistroSupportMatrix # # Currently this is effectively the min version for i686/x86_64 # + KVM/QEMU, as other architectures/hypervisors require newer # versions. Over time, this will become a common min version # for all architectures/hypervisors, as this value rises to # meet them. MIN_LIBVIRT_VERSION = (1, 2, 1) MIN_QEMU_VERSION = (1, 5, 3) # TODO(berrange): Re-evaluate this at start of each release cycle # to decide if we want to plan a future min version bump. # MIN_LIBVIRT_VERSION can be updated to match this after # NEXT_MIN_LIBVIRT_VERSION has been at a higher value for # one cycle NEXT_MIN_LIBVIRT_VERSION = (1, 2, 1) NEXT_MIN_QEMU_VERSION = (1, 5, 3) # When the above version matches/exceeds this version # delete it & corresponding code using it # Relative block commit & rebase (feature is detected, # this version is only used for messaging) MIN_LIBVIRT_BLOCKJOB_RELATIVE_VERSION = (1, 2, 7) # Libvirt version 1.2.17 is required for successful block live migration # of vm booted from image with attached devices MIN_LIBVIRT_BLOCK_LM_WITH_VOLUMES_VERSION = (1, 2, 17) # libvirt discard feature MIN_QEMU_DISCARD_VERSION = (1, 6, 0) # While earlier versions could support NUMA reporting and # NUMA placement, not until 1.2.7 was there the ability # to pin guest nodes to host nodes, so mandate that. Without # this the scheduler cannot make guaranteed decisions, as the # guest placement may not match what was requested MIN_LIBVIRT_NUMA_VERSION = (1, 2, 7) # PowerPC based hosts that support NUMA using libvirt MIN_LIBVIRT_NUMA_VERSION_PPC = (1, 2, 19) # Versions of libvirt with known NUMA topology issues # See bug #1449028 BAD_LIBVIRT_NUMA_VERSIONS = [(1, 2, 9, 2)] # While earlier versions could support hugepage backed # guests, not until 1.2.8 was there the ability to request # a particular huge page size. Without this the scheduler # cannot make guaranteed decisions, as the huge page size # used by the guest may not match what was requested MIN_LIBVIRT_HUGEPAGE_VERSION = (1, 2, 8) # Versions of libvirt with broken cpu pinning support. This excludes # versions of libvirt with broken NUMA support since pinning needs # NUMA # See bug #1438226 BAD_LIBVIRT_CPU_POLICY_VERSIONS = [(1, 2, 10)] # qemu 2.1 introduces support for pinning memory on host # NUMA nodes, along with the ability to specify hugepage # sizes per guest NUMA node MIN_QEMU_NUMA_HUGEPAGE_VERSION = (2, 1, 0) # fsFreeze/fsThaw requirement MIN_LIBVIRT_FSFREEZE_VERSION = (1, 2, 5) # UEFI booting support MIN_LIBVIRT_UEFI_VERSION = (1, 2, 9) # Hyper-V paravirtualized time source MIN_LIBVIRT_HYPERV_TIMER_VERSION = (1, 2, 2) MIN_QEMU_HYPERV_TIMER_VERSION = (2, 0, 0) # parallels driver support MIN_LIBVIRT_PARALLELS_VERSION = (1, 2, 12) # Ability to set the user guest password with Qemu MIN_LIBVIRT_SET_ADMIN_PASSWD = (1, 2, 16) # s/390 & s/390x architectures with KVM MIN_LIBVIRT_KVM_S390_VERSION = (1, 2, 13) MIN_QEMU_S390_VERSION = (2, 3, 0) # libvirt < 1.3 reported virt_functions capability # only when VFs are enabled. # libvirt 1.3 fix f391889f4e942e22b9ef8ecca492de05106ce41e MIN_LIBVIRT_PF_WITH_NO_VFS_CAP_VERSION = (1, 3, 0) # ppc64/ppc64le architectures with KVM # NOTE(rfolco): Same levels for Libvirt/Qemu on Big Endian and Little # Endian giving the nuance around guest vs host architectures MIN_LIBVIRT_KVM_PPC64_VERSION = (1, 2, 12) MIN_QEMU_PPC64_VERSION = (2, 1, 0) # Auto converge support MIN_LIBVIRT_AUTO_CONVERGE_VERSION = (1, 2, 3) MIN_QEMU_AUTO_CONVERGE = (1, 6, 0) # Names of the types that do not get compressed during migration NO_COMPRESSION_TYPES = ('qcow2',) # number of serial console limit QEMU_MAX_SERIAL_PORTS = 4 # Qemu supports 4 serial consoles, we remove 1 because of the PTY one defined ALLOWED_QEMU_SERIAL_PORTS = QEMU_MAX_SERIAL_PORTS - 1 # realtime support MIN_LIBVIRT_REALTIME_VERSION = (1, 2, 13) # libvirt postcopy support MIN_LIBVIRT_POSTCOPY_VERSION = (1, 3, 3) # qemu postcopy support MIN_QEMU_POSTCOPY_VERSION = (2, 5, 0) MIN_LIBVIRT_OTHER_ARCH = {arch.S390: MIN_LIBVIRT_KVM_S390_VERSION, arch.S390X: MIN_LIBVIRT_KVM_S390_VERSION, arch.PPC: MIN_LIBVIRT_KVM_PPC64_VERSION, arch.PPC64: MIN_LIBVIRT_KVM_PPC64_VERSION, arch.PPC64LE: MIN_LIBVIRT_KVM_PPC64_VERSION, } MIN_QEMU_OTHER_ARCH = {arch.S390: MIN_QEMU_S390_VERSION, arch.S390X: MIN_QEMU_S390_VERSION, arch.PPC: MIN_QEMU_PPC64_VERSION, arch.PPC64: MIN_QEMU_PPC64_VERSION, arch.PPC64LE: MIN_QEMU_PPC64_VERSION, } # perf events support MIN_LIBVIRT_PERF_VERSION = (2, 0, 0) LIBVIRT_PERF_EVENT_PREFIX = 'VIR_PERF_PARAM_' PERF_EVENTS_CPU_FLAG_MAPPING = {'cmt': 'cmt', 'mbml': 'mbm_local', 'mbmt': 'mbm_total', } class LibvirtDriver(driver.ComputeDriver): capabilities = { "has_imagecache": True, "supports_recreate": True, "supports_migrate_to_same_host": False, "supports_attach_interface": True, "supports_device_tagging": True, } def __init__(self, virtapi, read_only=False): super(LibvirtDriver, self).__init__(virtapi) global libvirt if libvirt is None: libvirt = importutils.import_module('libvirt') libvirt_migrate.libvirt = libvirt self._host = host.Host(self._uri(), read_only, lifecycle_event_handler=self.emit_event, conn_event_handler=self._handle_conn_event) self._initiator = None self._fc_wwnns = None self._fc_wwpns = None self._caps = None self._supported_perf_events = [] self.firewall_driver = firewall.load_driver( DEFAULT_FIREWALL_DRIVER, host=self._host) self.vif_driver = libvirt_vif.LibvirtGenericVIFDriver() self.volume_drivers = driver.driver_dict_from_config( self._get_volume_drivers(), self) self._disk_cachemode = None self.image_cache_manager = imagecache.ImageCacheManager() self.image_backend = imagebackend.Backend(CONF.use_cow_images) self.disk_cachemodes = {} self.valid_cachemodes = ["default", "none", "writethrough", "writeback", "directsync", "unsafe", ] self._conn_supports_start_paused = CONF.libvirt.virt_type in ('kvm', 'qemu') for mode_str in CONF.libvirt.disk_cachemodes: disk_type, sep, cache_mode = mode_str.partition('=') if cache_mode not in self.valid_cachemodes: LOG.warning(_LW('Invalid cachemode %(cache_mode)s specified ' 'for disk type %(disk_type)s.'), {'cache_mode': cache_mode, 'disk_type': disk_type}) continue self.disk_cachemodes[disk_type] = cache_mode self._volume_api = cinder.API() self._image_api = image.API() sysinfo_serial_funcs = { 'none': lambda: None, 'hardware': self._get_host_sysinfo_serial_hardware, 'os': self._get_host_sysinfo_serial_os, 'auto': self._get_host_sysinfo_serial_auto, } self._sysinfo_serial_func = sysinfo_serial_funcs.get( CONF.libvirt.sysinfo_serial) self.job_tracker = instancejobtracker.InstanceJobTracker() self._remotefs = remotefs.RemoteFilesystem() self._live_migration_flags = self._block_migration_flags = 0 self.active_migrations = {} # Compute reserved hugepages from conf file at the very # beginning to ensure any syntax error will be reported and # avoid any re-calculation when computing resources. self._reserved_hugepages = hardware.numa_get_reserved_huge_pages() def _get_volume_drivers(self): return libvirt_volume_drivers @property def disk_cachemode(self): if self._disk_cachemode is None: # We prefer 'none' for consistent performance, host crash # safety & migration correctness by avoiding host page cache. # Some filesystems (eg GlusterFS via FUSE) don't support # O_DIRECT though. For those we fallback to 'writethrough' # which gives host crash safety, and is safe for migration # provided the filesystem is cache coherent (cluster filesystems # typically are, but things like NFS are not). self._disk_cachemode = "none" if not self._supports_direct_io(CONF.instances_path): self._disk_cachemode = "writethrough" return self._disk_cachemode def _set_cache_mode(self, conf): """Set cache mode on LibvirtConfigGuestDisk object.""" try: source_type = conf.source_type driver_cache = conf.driver_cache except AttributeError: return cache_mode = self.disk_cachemodes.get(source_type, driver_cache) conf.driver_cache = cache_mode def _do_quality_warnings(self): """Warn about untested driver configurations. This will log a warning message about untested driver or host arch configurations to indicate to administrators that the quality is unknown. Currently, only qemu or kvm on intel 32- or 64-bit systems is tested upstream. """ caps = self._host.get_capabilities() hostarch = caps.host.cpu.arch if (CONF.libvirt.virt_type not in ('qemu', 'kvm') or hostarch not in (arch.I686, arch.X86_64)): LOG.warning(_LW('The libvirt driver is not tested on ' '%(type)s/%(arch)s by the OpenStack project and ' 'thus its quality can not be ensured. For more ' 'information, see: http://docs.openstack.org/' 'developer/nova/support-matrix.html'), {'type': CONF.libvirt.virt_type, 'arch': hostarch}) def _handle_conn_event(self, enabled, reason): LOG.info(_LI("Connection event '%(enabled)d' reason '%(reason)s'"), {'enabled': enabled, 'reason': reason}) self._set_host_enabled(enabled, reason) def _version_to_string(self, version): return '.'.join([str(x) for x in version]) def init_host(self, host): self._host.initialize() self._do_quality_warnings() self._parse_migration_flags() self._supported_perf_events = self._get_supported_perf_events() if (CONF.libvirt.virt_type == 'lxc' and not (CONF.libvirt.uid_maps and CONF.libvirt.gid_maps)): LOG.warning(_LW("Running libvirt-lxc without user namespaces is " "dangerous. Containers spawned by Nova will be run " "as the host's root user. It is highly suggested " "that user namespaces be used in a public or " "multi-tenant environment.")) # Stop libguestfs using KVM unless we're also configured # to use this. This solves problem where people need to # stop Nova use of KVM because nested-virt is broken if CONF.libvirt.virt_type != "kvm": guestfs.force_tcg() if not self._host.has_min_version(MIN_LIBVIRT_VERSION): raise exception.NovaException( _('Nova requires libvirt version %s or greater.') % self._version_to_string(MIN_LIBVIRT_VERSION)) if (CONF.libvirt.virt_type in ("qemu", "kvm") and not self._host.has_min_version(hv_ver=MIN_QEMU_VERSION)): raise exception.NovaException( _('Nova requires QEMU version %s or greater.') % self._version_to_string(MIN_QEMU_VERSION)) if (CONF.libvirt.virt_type == 'parallels' and not self._host.has_min_version(MIN_LIBVIRT_PARALLELS_VERSION)): raise exception.NovaException( _('Running Nova with parallels virt_type requires ' 'libvirt version %s') % self._version_to_string(MIN_LIBVIRT_PARALLELS_VERSION)) # Give the cloud admin a heads up if we are intending to # change the MIN_LIBVIRT_VERSION in the next release. if not self._host.has_min_version(NEXT_MIN_LIBVIRT_VERSION): LOG.warning(_LW('Running Nova with a libvirt version less than ' '%(version)s is deprecated. The required minimum ' 'version of libvirt will be raised to %(version)s ' 'in the next release.'), {'version': self._version_to_string( NEXT_MIN_LIBVIRT_VERSION)}) if (CONF.libvirt.virt_type in ("qemu", "kvm") and not self._host.has_min_version(hv_ver=NEXT_MIN_QEMU_VERSION)): LOG.warning(_LW('Running Nova with a QEMU version less than ' '%(version)s is deprecated. The required minimum ' 'version of QEMU will be raised to %(version)s ' 'in the next release.'), {'version': self._version_to_string( NEXT_MIN_QEMU_VERSION)}) kvm_arch = arch.from_host() if (CONF.libvirt.virt_type in ('kvm', 'qemu') and kvm_arch in MIN_LIBVIRT_OTHER_ARCH and not self._host.has_min_version( MIN_LIBVIRT_OTHER_ARCH.get(kvm_arch), MIN_QEMU_OTHER_ARCH.get(kvm_arch))): raise exception.NovaException( _('Running Nova with qemu/kvm virt_type on %(arch)s ' 'requires libvirt version %(libvirt_ver)s and ' 'qemu version %(qemu_ver)s, or greater') % {'arch': kvm_arch, 'libvirt_ver': self._version_to_string( MIN_LIBVIRT_OTHER_ARCH.get(kvm_arch)), 'qemu_ver': self._version_to_string( MIN_QEMU_OTHER_ARCH.get(kvm_arch))}) def _prepare_migration_flags(self): migration_flags = 0 migration_flags |= libvirt.VIR_MIGRATE_LIVE # Adding p2p flag only if xen is not in use, because xen does not # support p2p migrations if CONF.libvirt.virt_type != 'xen': migration_flags |= libvirt.VIR_MIGRATE_PEER2PEER # Adding VIR_MIGRATE_UNDEFINE_SOURCE because, without it, migrated # instance will remain defined on the source host migration_flags |= libvirt.VIR_MIGRATE_UNDEFINE_SOURCE live_migration_flags = block_migration_flags = migration_flags # Adding VIR_MIGRATE_NON_SHARED_INC, otherwise all block-migrations # will be live-migrations instead block_migration_flags |= libvirt.VIR_MIGRATE_NON_SHARED_INC return (live_migration_flags, block_migration_flags) def _handle_live_migration_tunnelled(self, migration_flags): if (CONF.libvirt.live_migration_tunnelled is None or CONF.libvirt.live_migration_tunnelled): migration_flags |= libvirt.VIR_MIGRATE_TUNNELLED return migration_flags def _is_post_copy_available(self): if self._host.has_min_version(lv_ver=MIN_LIBVIRT_POSTCOPY_VERSION, hv_ver=MIN_QEMU_POSTCOPY_VERSION): return True return False def _handle_live_migration_post_copy(self, migration_flags): if CONF.libvirt.live_migration_permit_post_copy: if self._is_post_copy_available(): migration_flags |= libvirt.VIR_MIGRATE_POSTCOPY else: LOG.info(_LI('The live_migration_permit_post_copy is set ' 'to True, but it is not supported.')) return migration_flags def _handle_live_migration_auto_converge(self, migration_flags): if self._host.has_min_version(lv_ver=MIN_LIBVIRT_AUTO_CONVERGE_VERSION, hv_ver=MIN_QEMU_AUTO_CONVERGE): if (self._is_post_copy_available() and (migration_flags & libvirt.VIR_MIGRATE_POSTCOPY) != 0): LOG.info(_LI('The live_migration_permit_post_copy is set to ' 'True and post copy live migration is available ' 'so auto-converge will not be in use.')) elif CONF.libvirt.live_migration_permit_auto_converge: migration_flags |= libvirt.VIR_MIGRATE_AUTO_CONVERGE elif CONF.libvirt.live_migration_permit_auto_converge: LOG.info(_LI('The live_migration_permit_auto_converge is set ' 'to True, but it is not supported.')) return migration_flags def _parse_migration_flags(self): (live_migration_flags, block_migration_flags) = self._prepare_migration_flags() live_migration_flags = self._handle_live_migration_tunnelled( live_migration_flags) block_migration_flags = self._handle_live_migration_tunnelled( block_migration_flags) live_migration_flags = self._handle_live_migration_post_copy( live_migration_flags) block_migration_flags = self._handle_live_migration_post_copy( block_migration_flags) live_migration_flags = self._handle_live_migration_auto_converge( live_migration_flags) block_migration_flags = self._handle_live_migration_auto_converge( block_migration_flags) self._live_migration_flags = live_migration_flags self._block_migration_flags = block_migration_flags # TODO(sahid): This method is targeted for removal when the tests # have been updated to avoid its use # # All libvirt API calls on the libvirt.Connect object should be # encapsulated by methods on the nova.virt.libvirt.host.Host # object, rather than directly invoking the libvirt APIs. The goal # is to avoid a direct dependency on the libvirt API from the # driver.py file. def _get_connection(self): return self._host.get_connection() _conn = property(_get_connection) @staticmethod def _uri(): if CONF.libvirt.virt_type == 'uml': uri = CONF.libvirt.connection_uri or 'uml:///system' elif CONF.libvirt.virt_type == 'xen': uri = CONF.libvirt.connection_uri or 'xen:///' elif CONF.libvirt.virt_type == 'lxc': uri = CONF.libvirt.connection_uri or 'lxc:///' elif CONF.libvirt.virt_type == 'parallels': uri = CONF.libvirt.connection_uri or 'parallels:///system' else: uri = CONF.libvirt.connection_uri or 'qemu:///system' return uri @staticmethod def _live_migration_uri(dest): # Only Xen and QEMU support live migration, see # https://libvirt.org/migration.html#scenarios for reference uris = { 'kvm': 'qemu+tcp://%s/system', 'qemu': 'qemu+tcp://%s/system', 'xen': 'xenmigr://%s/system', } virt_type = CONF.libvirt.virt_type uri = CONF.libvirt.live_migration_uri or uris.get(virt_type) if uri is None: raise exception.LiveMigrationURINotAvailable(virt_type=virt_type) return uri % dest def instance_exists(self, instance): """Efficient override of base instance_exists method.""" try: self._host.get_guest(instance) return True except exception.NovaException: return False def list_instances(self): names = [] for guest in self._host.list_guests(only_running=False): names.append(guest.name) return names def list_instance_uuids(self): uuids = [] for guest in self._host.list_guests(only_running=False): uuids.append(guest.uuid) return uuids def plug_vifs(self, instance, network_info): """Plug VIFs into networks.""" for vif in network_info: self.vif_driver.plug(instance, vif) def _unplug_vifs(self, instance, network_info, ignore_errors): """Unplug VIFs from networks.""" for vif in network_info: try: self.vif_driver.unplug(instance, vif) except exception.NovaException: if not ignore_errors: raise def unplug_vifs(self, instance, network_info): self._unplug_vifs(instance, network_info, False) def _teardown_container(self, instance): inst_path = libvirt_utils.get_instance_path(instance) container_dir = os.path.join(inst_path, 'rootfs') rootfs_dev = instance.system_metadata.get('rootfs_device_name') LOG.debug('Attempting to teardown container at path %(dir)s with ' 'root device: %(rootfs_dev)s', {'dir': container_dir, 'rootfs_dev': rootfs_dev}, instance=instance) disk_api.teardown_container(container_dir, rootfs_dev) def _destroy(self, instance, attempt=1): try: guest = self._host.get_guest(instance) if CONF.serial_console.enabled: # This method is called for several events: destroy, # rebuild, hard-reboot, power-off - For all of these # events we want to release the serial ports acquired # for the guest before destroying it. serials = self._get_serial_ports_from_guest(guest) for hostname, port in serials: serial_console.release_port(host=hostname, port=port) except exception.InstanceNotFound: guest = None # If the instance is already terminated, we're still happy # Otherwise, destroy it old_domid = -1 if guest is not None: try: old_domid = guest.id guest.poweroff() except libvirt.libvirtError as e: is_okay = False errcode = e.get_error_code() if errcode == libvirt.VIR_ERR_NO_DOMAIN: # Domain already gone. This can safely be ignored. is_okay = True elif errcode == libvirt.VIR_ERR_OPERATION_INVALID: # If the instance is already shut off, we get this: # Code=55 Error=Requested operation is not valid: # domain is not running state = guest.get_power_state(self._host) if state == power_state.SHUTDOWN: is_okay = True elif errcode == libvirt.VIR_ERR_INTERNAL_ERROR: errmsg = e.get_error_message() if (CONF.libvirt.virt_type == 'lxc' and errmsg == 'internal error: ' 'Some processes refused to die'): # Some processes in the container didn't die # fast enough for libvirt. The container will # eventually die. For now, move on and let # the wait_for_destroy logic take over. is_okay = True elif errcode == libvirt.VIR_ERR_OPERATION_TIMEOUT: LOG.warning(_LW("Cannot destroy instance, operation time " "out"), instance=instance) reason = _("operation time out") raise exception.InstancePowerOffFailure(reason=reason) elif errcode == libvirt.VIR_ERR_SYSTEM_ERROR: if e.get_int1() == errno.EBUSY: # NOTE(danpb): When libvirt kills a process it sends it # SIGTERM first and waits 10 seconds. If it hasn't gone # it sends SIGKILL and waits another 5 seconds. If it # still hasn't gone then you get this EBUSY error. # Usually when a QEMU process fails to go away upon # SIGKILL it is because it is stuck in an # uninterruptible kernel sleep waiting on I/O from # some non-responsive server. # Given the CPU load of the gate tests though, it is # conceivable that the 15 second timeout is too short, # particularly if the VM running tempest has a high # steal time from the cloud host. ie 15 wallclock # seconds may have passed, but the VM might have only # have a few seconds of scheduled run time. LOG.warning(_LW('Error from libvirt during destroy. ' 'Code=%(errcode)s Error=%(e)s; ' 'attempt %(attempt)d of 3'), {'errcode': errcode, 'e': e, 'attempt': attempt}, instance=instance) with excutils.save_and_reraise_exception() as ctxt: # Try up to 3 times before giving up. if attempt < 3: ctxt.reraise = False self._destroy(instance, attempt + 1) return if not is_okay: with excutils.save_and_reraise_exception(): LOG.error(_LE('Error from libvirt during destroy. ' 'Code=%(errcode)s Error=%(e)s'), {'errcode': errcode, 'e': e}, instance=instance) def _wait_for_destroy(expected_domid): """Called at an interval until the VM is gone.""" # NOTE(vish): If the instance disappears during the destroy # we ignore it so the cleanup can still be # attempted because we would prefer destroy to # never fail. try: dom_info = self.get_info(instance) state = dom_info.state new_domid = dom_info.id except exception.InstanceNotFound: LOG.info(_LI("During wait destroy, instance disappeared."), instance=instance) raise loopingcall.LoopingCallDone() if state == power_state.SHUTDOWN: LOG.info(_LI("Instance destroyed successfully."), instance=instance) raise loopingcall.LoopingCallDone() # NOTE(wangpan): If the instance was booted again after destroy, # this may be an endless loop, so check the id of # domain here, if it changed and the instance is # still running, we should destroy it again. # see https://bugs.launchpad.net/nova/+bug/1111213 for more details if new_domid != expected_domid: LOG.info(_LI("Instance may be started again."), instance=instance) kwargs['is_running'] = True raise loopingcall.LoopingCallDone() kwargs = {'is_running': False} timer = loopingcall.FixedIntervalLoopingCall(_wait_for_destroy, old_domid) timer.start(interval=0.5).wait() if kwargs['is_running']: LOG.info(_LI("Going to destroy instance again."), instance=instance) self._destroy(instance) else: # NOTE(GuanQiang): teardown container to avoid resource leak if CONF.libvirt.virt_type == 'lxc': self._teardown_container(instance) def destroy(self, context, instance, network_info, block_device_info=None, destroy_disks=True, migrate_data=None): self._destroy(instance) self.cleanup(context, instance, network_info, block_device_info, destroy_disks, migrate_data) def _undefine_domain(self, instance): try: guest = self._host.get_guest(instance) try: guest.delete_configuration() except libvirt.libvirtError as e: with excutils.save_and_reraise_exception(): errcode = e.get_error_code() LOG.error(_LE('Error from libvirt during undefine. ' 'Code=%(errcode)s Error=%(e)s'), {'errcode': errcode, 'e': e}, instance=instance) except exception.InstanceNotFound: pass def cleanup(self, context, instance, network_info, block_device_info=None, destroy_disks=True, migrate_data=None, destroy_vifs=True): if destroy_vifs: self._unplug_vifs(instance, network_info, True) retry = True while retry: try: self.unfilter_instance(instance, network_info) except libvirt.libvirtError as e: try: state = self.get_info(instance).state except exception.InstanceNotFound: state = power_state.SHUTDOWN if state != power_state.SHUTDOWN: LOG.warning(_LW("Instance may be still running, destroy " "it again."), instance=instance) self._destroy(instance) else: retry = False errcode = e.get_error_code() LOG.exception(_LE('Error from libvirt during unfilter. ' 'Code=%(errcode)s Error=%(e)s'), {'errcode': errcode, 'e': e}, instance=instance) reason = "Error unfiltering instance." raise exception.InstanceTerminationFailure(reason=reason) except Exception: retry = False raise else: retry = False # FIXME(wangpan): if the instance is booted again here, such as the # the soft reboot operation boot it here, it will # become "running deleted", should we check and destroy # it at the end of this method? # NOTE(vish): we disconnect from volumes regardless block_device_mapping = driver.block_device_info_get_mapping( block_device_info) for vol in block_device_mapping: connection_info = vol['connection_info'] disk_dev = vol['mount_device'] if disk_dev is not None: disk_dev = disk_dev.rpartition("/")[2] if ('data' in connection_info and 'volume_id' in connection_info['data']): volume_id = connection_info['data']['volume_id'] encryption = encryptors.get_encryption_metadata( context, self._volume_api, volume_id, connection_info) if encryption: # The volume must be detached from the VM before # disconnecting it from its encryptor. Otherwise, the # encryptor may report that the volume is still in use. encryptor = self._get_volume_encryptor(connection_info, encryption) encryptor.detach_volume(**encryption) try: self._disconnect_volume(connection_info, disk_dev) except Exception as exc: with excutils.save_and_reraise_exception() as ctxt: if destroy_disks: # Don't block on Volume errors if we're trying to # delete the instance as we may be partially created # or deleted ctxt.reraise = False LOG.warning( _LW("Ignoring Volume Error on vol %(vol_id)s " "during delete %(exc)s"), {'vol_id': vol.get('volume_id'), 'exc': exc}, instance=instance) if destroy_disks: # NOTE(haomai): destroy volumes if needed if CONF.libvirt.images_type == 'lvm': self._cleanup_lvm(instance, block_device_info) if CONF.libvirt.images_type == 'rbd': self._cleanup_rbd(instance) is_shared_block_storage = False if migrate_data and 'is_shared_block_storage' in migrate_data: is_shared_block_storage = migrate_data.is_shared_block_storage if destroy_disks or is_shared_block_storage: attempts = int(instance.system_metadata.get('clean_attempts', '0')) success = self.delete_instance_files(instance) # NOTE(mriedem): This is used in the _run_pending_deletes periodic # task in the compute manager. The tight coupling is not great... instance.system_metadata['clean_attempts'] = str(attempts + 1) if success: instance.cleaned = True instance.save() self._undefine_domain(instance) def _detach_encrypted_volumes(self, instance, block_device_info): """Detaches encrypted volumes attached to instance.""" disks = jsonutils.loads(self.get_instance_disk_info(instance, block_device_info)) encrypted_volumes = filter(dmcrypt.is_encrypted, [disk['path'] for disk in disks]) for path in encrypted_volumes: dmcrypt.delete_volume(path) def _get_serial_ports_from_guest(self, guest, mode=None): """Returns an iterator over serial port(s) configured on guest. :param mode: Should be a value in (None, bind, connect) """ xml = guest.get_xml_desc() tree = etree.fromstring(xml) # The 'serial' device is the base for x86 platforms. Other platforms # (e.g. kvm on system z = arch.S390X) can only use 'console' devices. xpath_mode = "[@mode='%s']" % mode if mode else "" serial_tcp = "./devices/serial[@type='tcp']/source" + xpath_mode console_tcp = "./devices/console[@type='tcp']/source" + xpath_mode tcp_devices = tree.findall(serial_tcp) if len(tcp_devices) == 0: tcp_devices = tree.findall(console_tcp) for source in tcp_devices: yield (source.get("host"), int(source.get("service"))) @staticmethod def _get_rbd_driver(): return rbd_utils.RBDDriver( pool=CONF.libvirt.images_rbd_pool, ceph_conf=CONF.libvirt.images_rbd_ceph_conf, rbd_user=CONF.libvirt.rbd_user) def _cleanup_rbd(self, instance): # NOTE(nic): On revert_resize, the cleanup steps for the root # volume are handled with an "rbd snap rollback" command, # and none of this is needed (and is, in fact, harmful) so # filter out non-ephemerals from the list if instance.task_state == task_states.RESIZE_REVERTING: filter_fn = lambda disk: (disk.startswith(instance.uuid) and disk.endswith('disk.local')) else: filter_fn = lambda disk: disk.startswith(instance.uuid) LibvirtDriver._get_rbd_driver().cleanup_volumes(filter_fn) def _cleanup_lvm(self, instance, block_device_info): """Delete all LVM disks for given instance object.""" if instance.get('ephemeral_key_uuid') is not None: self._detach_encrypted_volumes(instance, block_device_info) disks = self._lvm_disks(instance) if disks: lvm.remove_volumes(disks) def _lvm_disks(self, instance): """Returns all LVM disks for given instance object.""" if CONF.libvirt.images_volume_group: vg = os.path.join('/dev', CONF.libvirt.images_volume_group) if not os.path.exists(vg): return [] pattern = '%s_' % instance.uuid def belongs_to_instance(disk): return disk.startswith(pattern) def fullpath(name): return os.path.join(vg, name) logical_volumes = lvm.list_volumes(vg) disk_names = filter(belongs_to_instance, logical_volumes) disks = map(fullpath, disk_names) return disks return [] def get_volume_connector(self, instance): root_helper = utils.get_root_helper() return connector.get_connector_properties( root_helper, CONF.my_block_storage_ip, CONF.libvirt.volume_use_multipath, enforce_multipath=True, host=CONF.host) def _cleanup_resize(self, instance, network_info): target = libvirt_utils.get_instance_path(instance) + '_resize' if os.path.exists(target): # Deletion can fail over NFS, so retry the deletion as required. # Set maximum attempt as 5, most test can remove the directory # for the second time. utils.execute('rm', '-rf', target, delay_on_retry=True, attempts=5) root_disk = self.image_backend.image(instance, 'disk') # TODO(nic): Set ignore_errors=False in a future release. # It is set to True here to avoid any upgrade issues surrounding # instances being in pending resize state when the software is updated; # in that case there will be no snapshot to remove. Once it can be # reasonably assumed that no such instances exist in the wild # anymore, it should be set back to False (the default) so it will # throw errors, like it should. if root_disk.exists(): root_disk.remove_snap(libvirt_utils.RESIZE_SNAPSHOT_NAME, ignore_errors=True) if instance.host != CONF.host: self._undefine_domain(instance) self.unplug_vifs(instance, network_info) self.unfilter_instance(instance, network_info) def _get_volume_driver(self, connection_info): driver_type = connection_info.get('driver_volume_type') if driver_type not in self.volume_drivers: raise exception.VolumeDriverNotFound(driver_type=driver_type) return self.volume_drivers[driver_type] def _connect_volume(self, connection_info, disk_info): vol_driver = self._get_volume_driver(connection_info) vol_driver.connect_volume(connection_info, disk_info) def _disconnect_volume(self, connection_info, disk_dev): vol_driver = self._get_volume_driver(connection_info) vol_driver.disconnect_volume(connection_info, disk_dev) def _get_volume_config(self, connection_info, disk_info): vol_driver = self._get_volume_driver(connection_info) return vol_driver.get_config(connection_info, disk_info) def _get_volume_encryptor(self, connection_info, encryption): encryptor = encryptors.get_volume_encryptor(connection_info, **encryption) return encryptor def _check_discard_for_attach_volume(self, conf, instance): """Perform some checks for volumes configured for discard support. If discard is configured for the volume, and the guest is using a configuration known to not work, we will log a message explaining the reason why. """ if conf.driver_discard == 'unmap' and conf.target_bus == 'virtio': LOG.debug('Attempting to attach volume %(id)s with discard ' 'support enabled to an instance using an ' 'unsupported configuration. target_bus = ' '%(bus)s. Trim commands will not be issued to ' 'the storage device.', {'bus': conf.target_bus, 'id': conf.serial}, instance=instance) def attach_volume(self, context, connection_info, instance, mountpoint, disk_bus=None, device_type=None, encryption=None): guest = self._host.get_guest(instance) disk_dev = mountpoint.rpartition("/")[2] bdm = { 'device_name': disk_dev, 'disk_bus': disk_bus, 'device_type': device_type} # Note(cfb): If the volume has a custom block size, check that # that we are using QEMU/KVM and libvirt >= 0.10.2. The # presence of a block size is considered mandatory by # cinder so we fail if we can't honor the request. data = {} if ('data' in connection_info): data = connection_info['data'] if ('logical_block_size' in data or 'physical_block_size' in data): if ((CONF.libvirt.virt_type != "kvm" and CONF.libvirt.virt_type != "qemu")): msg = _("Volume sets block size, but the current " "libvirt hypervisor '%s' does not support custom " "block size") % CONF.libvirt.virt_type raise exception.InvalidHypervisorType(msg) disk_info = blockinfo.get_info_from_bdm( instance, CONF.libvirt.virt_type, instance.image_meta, bdm) self._connect_volume(connection_info, disk_info) conf = self._get_volume_config(connection_info, disk_info) self._set_cache_mode(conf) self._check_discard_for_attach_volume(conf, instance) try: state = guest.get_power_state(self._host) live = state in (power_state.RUNNING, power_state.PAUSED) if encryption: encryptor = self._get_volume_encryptor(connection_info, encryption) encryptor.attach_volume(context, **encryption) guest.attach_device(conf, persistent=True, live=live) except Exception as ex: LOG.exception(_LE('Failed to attach volume at mountpoint: %s'), mountpoint, instance=instance) if isinstance(ex, libvirt.libvirtError): errcode = ex.get_error_code() if errcode == libvirt.VIR_ERR_OPERATION_FAILED: self._disconnect_volume(connection_info, disk_dev) raise exception.DeviceIsBusy(device=disk_dev) with excutils.save_and_reraise_exception(): self._disconnect_volume(connection_info, disk_dev) def _swap_volume(self, guest, disk_path, new_path, resize_to): """Swap existing disk with a new block device.""" dev = guest.get_block_device(disk_path) # Save a copy of the domain's persistent XML file xml = guest.get_xml_desc(dump_inactive=True, dump_sensitive=True) # Abort is an idempotent operation, so make sure any block # jobs which may have failed are ended. try: dev.abort_job() except Exception: pass try: # NOTE (rmk): blockRebase cannot be executed on persistent # domains, so we need to temporarily undefine it. # If any part of this block fails, the domain is # re-defined regardless. if guest.has_persistent_configuration(): guest.delete_configuration() # Start copy with VIR_DOMAIN_REBASE_REUSE_EXT flag to # allow writing to existing external volume file dev.rebase(new_path, copy=True, reuse_ext=True) while dev.wait_for_job(): time.sleep(0.5) dev.abort_job(pivot=True) if resize_to: # NOTE(alex_xu): domain.blockJobAbort isn't sync call. This # is bug in libvirt. So we need waiting for the pivot is # finished. libvirt bug #1119173 while dev.wait_for_job(wait_for_job_clean=True): time.sleep(0.5) dev.resize(resize_to * units.Gi / units.Ki) finally: self._host.write_instance_config(xml) def swap_volume(self, old_connection_info, new_connection_info, instance, mountpoint, resize_to): guest = self._host.get_guest(instance) disk_dev = mountpoint.rpartition("/")[2] if not guest.get_disk(disk_dev): raise exception.DiskNotFound(location=disk_dev) disk_info = { 'dev': disk_dev, 'bus': blockinfo.get_disk_bus_for_disk_dev( CONF.libvirt.virt_type, disk_dev), 'type': 'disk', } self._connect_volume(new_connection_info, disk_info) conf = self._get_volume_config(new_connection_info, disk_info) if not conf.source_path: self._disconnect_volume(new_connection_info, disk_dev) raise NotImplementedError(_("Swap only supports host devices")) # Save updates made in connection_info when connect_volume was called volume_id = new_connection_info.get('serial') bdm = objects.BlockDeviceMapping.get_by_volume_and_instance( nova_context.get_admin_context(), volume_id, instance.uuid) driver_bdm = driver_block_device.convert_volume(bdm) driver_bdm['connection_info'] = new_connection_info driver_bdm.save() self._swap_volume(guest, disk_dev, conf.source_path, resize_to) self._disconnect_volume(old_connection_info, disk_dev) def _get_existing_domain_xml(self, instance, network_info, block_device_info=None): try: guest = self._host.get_guest(instance) xml = guest.get_xml_desc() except exception.InstanceNotFound: disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance, instance.image_meta, block_device_info) xml = self._get_guest_xml(nova_context.get_admin_context(), instance, network_info, disk_info, instance.image_meta, block_device_info=block_device_info) return xml def detach_volume(self, connection_info, instance, mountpoint, encryption=None): disk_dev = mountpoint.rpartition("/")[2] try: guest = self._host.get_guest(instance) state = guest.get_power_state(self._host) live = state in (power_state.RUNNING, power_state.PAUSED) wait_for_detach = guest.detach_device_with_retry(guest.get_disk, disk_dev, persistent=True, live=live) if encryption: # The volume must be detached from the VM before # disconnecting it from its encryptor. Otherwise, the # encryptor may report that the volume is still in use. encryptor = self._get_volume_encryptor(connection_info, encryption) encryptor.detach_volume(**encryption) wait_for_detach() except exception.InstanceNotFound: # NOTE(zhaoqin): If the instance does not exist, _lookup_by_name() # will throw InstanceNotFound exception. Need to # disconnect volume under this circumstance. LOG.warning(_LW("During detach_volume, instance disappeared."), instance=instance) except exception.DeviceNotFound: raise exception.DiskNotFound(location=disk_dev) except libvirt.libvirtError as ex: # NOTE(vish): This is called to cleanup volumes after live # migration, so we should still disconnect even if # the instance doesn't exist here anymore. error_code = ex.get_error_code() if error_code == libvirt.VIR_ERR_NO_DOMAIN: # NOTE(vish): LOG.warning(_LW("During detach_volume, instance disappeared."), instance=instance) else: raise self._disconnect_volume(connection_info, disk_dev) def attach_interface(self, instance, image_meta, vif): guest = self._host.get_guest(instance) self.vif_driver.plug(instance, vif) self.firewall_driver.setup_basic_filtering(instance, [vif]) cfg = self.vif_driver.get_config(instance, vif, image_meta, instance.flavor, CONF.libvirt.virt_type, self._host) try: state = guest.get_power_state(self._host) live = state in (power_state.RUNNING, power_state.PAUSED) guest.attach_device(cfg, persistent=True, live=live) except libvirt.libvirtError: LOG.error(_LE('attaching network adapter failed.'), instance=instance, exc_info=True) self.vif_driver.unplug(instance, vif) raise exception.InterfaceAttachFailed( instance_uuid=instance.uuid) def detach_interface(self, instance, vif): guest = self._host.get_guest(instance) cfg = self.vif_driver.get_config(instance, vif, instance.image_meta, instance.flavor, CONF.libvirt.virt_type, self._host) try: self.vif_driver.unplug(instance, vif) state = guest.get_power_state(self._host) live = state in (power_state.RUNNING, power_state.PAUSED) guest.detach_device(cfg, persistent=True, live=live) except libvirt.libvirtError as ex: error_code = ex.get_error_code() if error_code == libvirt.VIR_ERR_NO_DOMAIN: LOG.warning(_LW("During detach_interface, " "instance disappeared."), instance=instance) else: # NOTE(mriedem): When deleting an instance and using Neutron, # we can be racing against Neutron deleting the port and # sending the vif-deleted event which then triggers a call to # detach the interface, so we might have failed because the # network device no longer exists. Libvirt will fail with # "operation failed: no matching network device was found" # which unfortunately does not have a unique error code so we # need to look up the interface by MAC and if it's not found # then we can just log it as a warning rather than tracing an # error. mac = vif.get('address') interface = guest.get_interface_by_mac(mac) if interface: LOG.error(_LE('detaching network adapter failed.'), instance=instance, exc_info=True) raise exception.InterfaceDetachFailed( instance_uuid=instance.uuid) # The interface is gone so just log it as a warning. LOG.warning(_LW('Detaching interface %(mac)s failed because ' 'the device is no longer found on the guest.'), {'mac': mac}, instance=instance) def _create_snapshot_metadata(self, image_meta, instance, img_fmt, snp_name): metadata = {'is_public': False, 'status': 'active', 'name': snp_name, 'properties': { 'kernel_id': instance.kernel_id, 'image_location': 'snapshot', 'image_state': 'available', 'owner_id': instance.project_id, 'ramdisk_id': instance.ramdisk_id, } } if instance.os_type: metadata['properties']['os_type'] = instance.os_type # NOTE(vish): glance forces ami disk format to be ami if image_meta.disk_format == 'ami': metadata['disk_format'] = 'ami' else: metadata['disk_format'] = img_fmt if image_meta.obj_attr_is_set("container_format"): metadata['container_format'] = image_meta.container_format else: metadata['container_format'] = "bare" return metadata def snapshot(self, context, instance, image_id, update_task_state): """Create snapshot from a running VM instance. This command only works with qemu 0.14+ """ try: guest = self._host.get_guest(instance) # TODO(sahid): We are converting all calls from a # virDomain object to use nova.virt.libvirt.Guest. # We should be able to remove virt_dom at the end. virt_dom = guest._domain except exception.InstanceNotFound: raise exception.InstanceNotRunning(instance_id=instance.uuid) snapshot = self._image_api.get(context, image_id) # source_format is an on-disk format # source_type is a backend type disk_path, source_format = libvirt_utils.find_disk(virt_dom) source_type = libvirt_utils.get_disk_type_from_path(disk_path) # We won't have source_type for raw or qcow2 disks, because we can't # determine that from the path. We should have it from the libvirt # xml, though. if source_type is None: source_type = source_format # For lxc instances we won't have it either from libvirt xml # (because we just gave libvirt the mounted filesystem), or the path, # so source_type is still going to be None. In this case, # snapshot_backend is going to default to CONF.libvirt.images_type # below, which is still safe. image_format = CONF.libvirt.snapshot_image_format or source_type # NOTE(bfilippov): save lvm and rbd as raw if image_format == 'lvm' or image_format == 'rbd': image_format = 'raw' metadata = self._create_snapshot_metadata(instance.image_meta, instance, image_format, snapshot['name']) snapshot_name = uuid.uuid4().hex state = guest.get_power_state(self._host) # NOTE(dgenin): Instances with LVM encrypted ephemeral storage require # cold snapshots. Currently, checking for encryption is # redundant because LVM supports only cold snapshots. # It is necessary in case this situation changes in the # future. if (self._host.has_min_version(hv_type=host.HV_DRIVER_QEMU) and source_type not in ('lvm') and not CONF.ephemeral_storage_encryption.enabled and not CONF.workarounds.disable_libvirt_livesnapshot): live_snapshot = True # Abort is an idempotent operation, so make sure any block # jobs which may have failed are ended. This operation also # confirms the running instance, as opposed to the system as a # whole, has a new enough version of the hypervisor (bug 1193146). try: guest.get_block_device(disk_path).abort_job() except libvirt.libvirtError as ex: error_code = ex.get_error_code() if error_code == libvirt.VIR_ERR_CONFIG_UNSUPPORTED: live_snapshot = False else: pass else: live_snapshot = False # NOTE(rmk): We cannot perform live snapshots when a managedSave # file is present, so we will use the cold/legacy method # for instances which are shutdown. if state == power_state.SHUTDOWN: live_snapshot = False self._prepare_domain_for_snapshot(context, live_snapshot, state, instance) snapshot_backend = self.image_backend.snapshot(instance, disk_path, image_type=source_type) if live_snapshot: LOG.info(_LI("Beginning live snapshot process"), instance=instance) else: LOG.info(_LI("Beginning cold snapshot process"), instance=instance) update_task_state(task_state=task_states.IMAGE_PENDING_UPLOAD) try: update_task_state(task_state=task_states.IMAGE_UPLOADING, expected_state=task_states.IMAGE_PENDING_UPLOAD) metadata['location'] = snapshot_backend.direct_snapshot( context, snapshot_name, image_format, image_id, instance.image_ref) self._snapshot_domain(context, live_snapshot, virt_dom, state, instance) self._image_api.update(context, image_id, metadata, purge_props=False) except (NotImplementedError, exception.ImageUnacceptable, exception.Forbidden) as e: if type(e) != NotImplementedError: LOG.warning(_LW('Performing standard snapshot because direct ' 'snapshot failed: %(error)s'), {'error': e}) failed_snap = metadata.pop('location', None) if failed_snap: failed_snap = {'url': str(failed_snap)} snapshot_backend.cleanup_direct_snapshot(failed_snap, also_destroy_volume=True, ignore_errors=True) update_task_state(task_state=task_states.IMAGE_PENDING_UPLOAD, expected_state=task_states.IMAGE_UPLOADING) # TODO(nic): possibly abstract this out to the snapshot_backend if source_type == 'rbd' and live_snapshot: # Standard snapshot uses qemu-img convert from RBD which is # not safe to run with live_snapshot. live_snapshot = False # Suspend the guest, so this is no longer a live snapshot self._prepare_domain_for_snapshot(context, live_snapshot, state, instance) snapshot_directory = CONF.libvirt.snapshots_directory fileutils.ensure_tree(snapshot_directory) with utils.tempdir(dir=snapshot_directory) as tmpdir: try: out_path = os.path.join(tmpdir, snapshot_name) if live_snapshot: # NOTE(xqueralt): libvirt needs o+x in the tempdir os.chmod(tmpdir, 0o701) self._live_snapshot(context, instance, guest, disk_path, out_path, source_format, image_format, instance.image_meta) else: snapshot_backend.snapshot_extract(out_path, image_format) finally: self._snapshot_domain(context, live_snapshot, virt_dom, state, instance) LOG.info(_LI("Snapshot extracted, beginning image upload"), instance=instance) # Upload that image to the image service update_task_state(task_state=task_states.IMAGE_UPLOADING, expected_state=task_states.IMAGE_PENDING_UPLOAD) with libvirt_utils.file_open(out_path) as image_file: self._image_api.update(context, image_id, metadata, image_file) except Exception: with excutils.save_and_reraise_exception(): LOG.exception(_LE("Failed to snapshot image")) failed_snap = metadata.pop('location', None) if failed_snap: failed_snap = {'url': str(failed_snap)} snapshot_backend.cleanup_direct_snapshot( failed_snap, also_destroy_volume=True, ignore_errors=True) LOG.info(_LI("Snapshot image upload complete"), instance=instance) def _prepare_domain_for_snapshot(self, context, live_snapshot, state, instance): # NOTE(dkang): managedSave does not work for LXC if CONF.libvirt.virt_type != 'lxc' and not live_snapshot: if state == power_state.RUNNING or state == power_state.PAUSED: self.suspend(context, instance) def _snapshot_domain(self, context, live_snapshot, virt_dom, state, instance): guest = None # NOTE(dkang): because previous managedSave is not called # for LXC, _create_domain must not be called. if CONF.libvirt.virt_type != 'lxc' and not live_snapshot: if state == power_state.RUNNING: guest = self._create_domain(domain=virt_dom) elif state == power_state.PAUSED: guest = self._create_domain(domain=virt_dom, pause=True) if guest is not None: self._attach_pci_devices( guest, pci_manager.get_instance_pci_devs(instance)) self._attach_sriov_ports(context, instance, guest) def _can_set_admin_password(self, image_meta): if (CONF.libvirt.virt_type not in ('kvm', 'qemu') or not self._host.has_min_version(MIN_LIBVIRT_SET_ADMIN_PASSWD)): raise exception.SetAdminPasswdNotSupported() hw_qga = image_meta.properties.get('hw_qemu_guest_agent', '') if not strutils.bool_from_string(hw_qga): raise exception.QemuGuestAgentNotEnabled() def set_admin_password(self, instance, new_pass): self._can_set_admin_password(instance.image_meta) guest = self._host.get_guest(instance) user = instance.image_meta.properties.get("os_admin_user") if not user: if instance.os_type == "windows": user = "Administrator" else: user = "root" try: guest.set_user_password(user, new_pass) except libvirt.libvirtError as ex: error_code = ex.get_error_code() msg = (_('Error from libvirt while set password for username ' '"%(user)s": [Error Code %(error_code)s] %(ex)s') % {'user': user, 'error_code': error_code, 'ex': ex}) raise exception.NovaException(msg) def _can_quiesce(self, instance, image_meta): if (CONF.libvirt.virt_type not in ('kvm', 'qemu') or not self._host.has_min_version(MIN_LIBVIRT_FSFREEZE_VERSION)): raise exception.InstanceQuiesceNotSupported( instance_id=instance.uuid) if not image_meta.properties.get('hw_qemu_guest_agent', False): raise exception.QemuGuestAgentNotEnabled() def _set_quiesced(self, context, instance, image_meta, quiesced): self._can_quiesce(instance, image_meta) try: guest = self._host.get_guest(instance) if quiesced: guest.freeze_filesystems() else: guest.thaw_filesystems() except libvirt.libvirtError as ex: error_code = ex.get_error_code() msg = (_('Error from libvirt while quiescing %(instance_name)s: ' '[Error Code %(error_code)s] %(ex)s') % {'instance_name': instance.name, 'error_code': error_code, 'ex': ex}) raise exception.NovaException(msg) def quiesce(self, context, instance, image_meta): """Freeze the guest filesystems to prepare for snapshot. The qemu-guest-agent must be setup to execute fsfreeze. """ self._set_quiesced(context, instance, image_meta, True) def unquiesce(self, context, instance, image_meta): """Thaw the guest filesystems after snapshot.""" self._set_quiesced(context, instance, image_meta, False) def _live_snapshot(self, context, instance, guest, disk_path, out_path, source_format, image_format, image_meta): """Snapshot an instance without downtime.""" dev = guest.get_block_device(disk_path) # Save a copy of the domain's persistent XML file xml = guest.get_xml_desc(dump_inactive=True, dump_sensitive=True) # Abort is an idempotent operation, so make sure any block # jobs which may have failed are ended. try: dev.abort_job() except Exception: pass # NOTE (rmk): We are using shallow rebases as a workaround to a bug # in QEMU 1.3. In order to do this, we need to create # a destination image with the original backing file # and matching size of the instance root disk. src_disk_size = libvirt_utils.get_disk_size(disk_path, format=source_format) src_back_path = libvirt_utils.get_disk_backing_file(disk_path, format=source_format, basename=False) disk_delta = out_path + '.delta' libvirt_utils.create_cow_image(src_back_path, disk_delta, src_disk_size) quiesced = False try: self._set_quiesced(context, instance, image_meta, True) quiesced = True except exception.NovaException as err: if image_meta.properties.get('os_require_quiesce', False): raise LOG.info(_LI('Skipping quiescing instance: %(reason)s.'), {'reason': err}, instance=instance) try: # NOTE (rmk): blockRebase cannot be executed on persistent # domains, so we need to temporarily undefine it. # If any part of this block fails, the domain is # re-defined regardless. if guest.has_persistent_configuration(): guest.delete_configuration() # NOTE (rmk): Establish a temporary mirror of our root disk and # issue an abort once we have a complete copy. dev.rebase(disk_delta, copy=True, reuse_ext=True, shallow=True) while dev.wait_for_job(): time.sleep(0.5) dev.abort_job() libvirt_utils.chown(disk_delta, os.getuid()) finally: self._host.write_instance_config(xml) if quiesced: self._set_quiesced(context, instance, image_meta, False) # Convert the delta (CoW) image with a backing file to a flat # image with no backing file. libvirt_utils.extract_snapshot(disk_delta, 'qcow2', out_path, image_format) def cdrom_list(self, context, instance): cdroms = [] guest = self._host.get_guest(instance) domain = guest._domain xml = domain.XMLDesc(0) xml_doc = etree.fromstring(xml) disks = xml_doc.findall('devices/disk') for disk in disks: if disk.get('device') == 'cdrom': source = disk.find('source') target = disk.find('target') if target is not None: cdrom ={} device = target.get('dev') cdrom['device_name'] = device if source is not None: disk_path = source.get('file') image_id = os.path.basename(disk_path) else: image_id = '' cdrom['image_id'] = image_id cdroms.append(cdrom) return cdroms def attach_cdrom(self, context, instance, device, image_id): cdrom_device={} guest = self._host.get_guest(instance) domain = guest._domain cdrom_config = self._get_guest_cdrom_config(context, instance, image_id, device) is_updated = False is_active = domain.isActive() if is_active == 1: domain.updateDeviceFlags(cdrom_config.to_xml(), libvirt.VIR_DOMAIN_AFFECT_LIVE | libvirt.VIR_DOMAIN_AFFECT_CONFIG) is_updated = True elif is_active == 0: domain.updateDeviceFlags(cdrom_config.to_xml(), libvirt.VIR_DOMAIN_AFFECT_CONFIG) is_updated = True if is_updated: # Sync the xml between default libvirt xml path and nova instance xml path instance_dir = libvirt_utils.get_instance_path(instance) xml_path = os.path.join(instance_dir, 'libvirt.xml') xml = domain.XMLDesc(0) libvirt_utils.write_to_file(xml_path, xml) cdrom_device['device_name'] = device cdrom_device['image_id'] = image_id return cdrom_device def has_cdrom(self,instance, disk_info): #LOG.info("disk_info:%s",disk_info) disk_mapping = disk_info['mapping'] cdxml = None inst_type = objects.Flavor.get_by_id( nova_context.get_admin_context(read_deleted='yes'), instance['instance_type_id']) if 'disk' in disk_mapping: disk = disk_mapping['disk'] if disk['type'] == 'cdrom': image = self.image_backend.image(instance, 'disk', None) cdxml = image.libvirt_info(disk['bus'], disk['dev'], disk['type'], self.disk_cachemode, inst_type['extra_specs'], self._get_hypervisor_version()) if 'disk.local' in disk_mapping: disklocal = disk_mapping['disk.local'] if disklocal['type'] == 'cdrom': image = self.image_backend.image(instance, 'disk.local', None) cdxml = image.libvirt_info(disklocal['bus'], disklocal['dev'], disklocal['type'], self.disk_cachemode, inst_type['extra_specs'], self._get_hypervisor_version()) return cdxml def _get_guest_cdrom_config(self, context, instance, image_id, device, enable_cache_image=True): cdrom_config = vconfig.LibvirtConfigGuestDisk() cdrom_config.source_type = 'file' cdrom_config.source_device = 'cdrom' cdrom_config.target_bus = 'ide' if device: cdrom_config.target_dev = device cdrom_config.readonly = True cdrom_config.driver_name = 'qemu' cdrom_config.driver_format = 'raw' if image_id != '0': # image_info = {} # image_info['image_id'] = image_id fake_image_id = imagecache.get_cache_fname(image_id) if enable_cache_image: imagecache.cache_image(libvirt_utils.fetch_image, fake_image_id, context=context, image_id=image_id) #user_id=instance.user_id, #project_id=instance.project_id) base_url = self.image_cache_manager._get_base() image_url = os.path.join(base_url, fake_image_id) else: image_url = '' cdrom_config.source_path = image_url return cdrom_config def dev_snapshot_create(self, context, instance, name): guest = self._host.get_guest(instance) domain = guest._domain xml = domain.XMLDesc(0) xml_doc = etree.fromstring(xml) device_info = vconfig.LibvirtConfigGuest() device_info.parse_dom(xml_doc) disks_to_snap = [] network_disks_to_snap = [] disks_to_skip = [] for guest_disk in device_info.devices: if (guest_disk.root_name != 'disk'): continue if (guest_disk.target_dev is None): continue disk_info = { 'dev': guest_disk.target_dev, 'serial': guest_disk.serial, 'current_file': guest_disk.source_path, 'source_protocol': guest_disk.source_protocol, 'source_name': guest_disk.source_name, 'source_hosts': guest_disk.source_hosts, 'source_ports': guest_disk.source_ports } if guest_disk.target_dev == 'vda': xwl_target_dev='vda' disks_to_snap.append(guest_disk.source_path) if guest_disk.target_dev == 'hda': xwl_target_dev='hda' disks_to_snap.append(guest_disk.source_path) if not disks_to_snap : msg = _('Found no disk to snapshot.') raise exception.NovaException(msg) snapshot = vconfig.LibvirtConfigGuestSnapshot() if name: uname = repr(name) snapshot_name =unicode(uname, 'unicode-escape') else: snapshot_name = None if xwl_target_dev == 'hda': for current_name in disks_to_snap: snap_disk = vconfig.LibvirtConfigGuestSnapshotDisk() if snapshot_name: snapshot.name = snapshot_name snap_disk.name = 'hda' snap_disk.snapshot = 'internal' snap_disk.driver_name = 'qcow2' snapshot.add_disk(snap_disk) for dev in disks_to_skip: snap_disk = vconfig.LibvirtConfigGuestSnapshotDisk() snap_disk.name = dev snap_disk.snapshot = 'no' snapshot.add_disk(snap_disk) else: for current_name in disks_to_snap: snap_disk = vconfig.LibvirtConfigGuestSnapshotDisk() if snapshot_name: snapshot.name = snapshot_name snap_disk.name = 'vda' snap_disk.snapshot = 'internal' snap_disk.driver_name = 'qcow2' snapshot.add_disk(snap_disk) for dev in disks_to_skip: snap_disk = vconfig.LibvirtConfigGuestSnapshotDisk() snap_disk.name = dev snap_disk.snapshot = 'no' snapshot.add_disk(snap_disk) snapshot_xml = snapshot.to_xml() snap_flags = 0 #QUIESCE = libvirt.VIR_DOMAIN_SNAPSHOT_CREATE_QUIESCE try: guest._domain.snapshotCreateXML(snapshot_xml, snap_flags) return except libvirt.libvirtError: LOG.exception(_LE('Unable to create quiesced dev_snapshot, ' 'attempting again with quiescing disabled.')) try: guest._domain.snapshotCreateXML(snapshot_xml, snap_flags ) except libvirt.libvirtError: LOG.exception(_LE('Unable to create dev_snapshot, ' 'failing dev_snapshot operation.')) raise def dev_snapshot_list(self, context, instance): snaps = [] try: guest = self._host.get_guest(instance) snapshotlist=guest._domain.listAllSnapshots(0) except exception.InstanceNotFound: return snaps for snapshot in snapshotlist: Desc = snapshot.getName() try: Desctime = time.strftime("%y-%m-%d %H:%M:%S", time.localtime(string.atof(Desc))) name = {} name['dev_snapshot_name'] = Desctime except: name = {} Desctime = Desc[2:-1] name['dev_snapshot_name'] = Desctime snaps.append(name) return snaps def dev_snapshot_delete(self, context, instance, name): try: guest = self._host.get_guest(instance) timeName = time.mktime(time.strptime(name, "%y-%m-%d %H:%M:%S")) tem='%.0f' % timeName snapshot = guest._domain.snapshotLookupByName(tem,0) snapshot.delete(0) except: stringName = repr(name) unicodeName = unicode(stringName,'unicode-escape') tem =unicodeName.encode('utf8') snapshot = guest._domain.snapshotLookupByName(tem,0) snapshot.delete(0) def dev_snapshot_revert(self, context, instance, name): try: guest = self._host.get_guest(instance) timeName = time.mktime(time.strptime(name, "%y-%m-%d %H:%M:%S")) tem='%.0f' % timeName snapshot = guest._domain.snapshotLookupByName(tem,0) guest._domain.revertToSnapshot(snapshot,0) except: stringName = repr(name) unicodeName = unicode(stringName,'unicode-escape') tem =unicodeName.encode('utf8') snapshot = guest._domain.snapshotLookupByName(tem,0) guest._domain.revertToSnapshot(snapshot,0) def _volume_snapshot_update_status(self, context, snapshot_id, status): """Send a snapshot status update to Cinder. This method captures and logs exceptions that occur since callers cannot do anything useful with these exceptions. Operations on the Cinder side waiting for this will time out if a failure occurs sending the update. :param context: security context :param snapshot_id: id of snapshot being updated :param status: new status value """ try: self._volume_api.update_snapshot_status(context, snapshot_id, status) except Exception: LOG.exception(_LE('Failed to send updated snapshot status ' 'to volume service.')) def _volume_snapshot_create(self, context, instance, guest, volume_id, new_file): """Perform volume snapshot. :param guest: VM that volume is attached to :param volume_id: volume UUID to snapshot :param new_file: relative path to new qcow2 file present on share """ xml = guest.get_xml_desc() xml_doc = etree.fromstring(xml) device_info = vconfig.LibvirtConfigGuest() device_info.parse_dom(xml_doc) disks_to_snap = [] # to be snapshotted by libvirt network_disks_to_snap = [] # network disks (netfs, gluster, etc.) disks_to_skip = [] # local disks not snapshotted for guest_disk in device_info.devices: if (guest_disk.root_name != 'disk'): continue if (guest_disk.target_dev is None): continue if (guest_disk.serial is None or guest_disk.serial != volume_id): disks_to_skip.append(guest_disk.target_dev) continue # disk is a Cinder volume with the correct volume_id disk_info = { 'dev': guest_disk.target_dev, 'serial': guest_disk.serial, 'current_file': guest_disk.source_path, 'source_protocol': guest_disk.source_protocol, 'source_name': guest_disk.source_name, 'source_hosts': guest_disk.source_hosts, 'source_ports': guest_disk.source_ports } # Determine path for new_file based on current path if disk_info['current_file'] is not None: current_file = disk_info['current_file'] new_file_path = os.path.join(os.path.dirname(current_file), new_file) disks_to_snap.append((current_file, new_file_path)) elif disk_info['source_protocol'] in ('gluster', 'netfs'): network_disks_to_snap.append((disk_info, new_file)) if not disks_to_snap and not network_disks_to_snap: msg = _('Found no disk to snapshot.') raise exception.NovaException(msg) snapshot = vconfig.LibvirtConfigGuestSnapshot() for current_name, new_filename in disks_to_snap: snap_disk = vconfig.LibvirtConfigGuestSnapshotDisk() snap_disk.name = current_name snap_disk.source_path = new_filename snap_disk.source_type = 'file' snap_disk.snapshot = 'external' snap_disk.driver_name = 'qcow2' snapshot.add_disk(snap_disk) for disk_info, new_filename in network_disks_to_snap: snap_disk = vconfig.LibvirtConfigGuestSnapshotDisk() snap_disk.name = disk_info['dev'] snap_disk.source_type = 'network' snap_disk.source_protocol = disk_info['source_protocol'] snap_disk.snapshot = 'external' snap_disk.source_path = new_filename old_dir = disk_info['source_name'].split('/')[0] snap_disk.source_name = '%s/%s' % (old_dir, new_filename) snap_disk.source_hosts = disk_info['source_hosts'] snap_disk.source_ports = disk_info['source_ports'] snapshot.add_disk(snap_disk) for dev in disks_to_skip: snap_disk = vconfig.LibvirtConfigGuestSnapshotDisk() snap_disk.name = dev snap_disk.snapshot = 'no' snapshot.add_disk(snap_disk) snapshot_xml = snapshot.to_xml() LOG.debug("snap xml: %s", snapshot_xml, instance=instance) try: guest.snapshot(snapshot, no_metadata=True, disk_only=True, reuse_ext=True, quiesce=True) return except libvirt.libvirtError: LOG.exception(_LE('Unable to create quiesced VM snapshot, ' 'attempting again with quiescing disabled.'), instance=instance) try: guest.snapshot(snapshot, no_metadata=True, disk_only=True, reuse_ext=True, quiesce=False) except libvirt.libvirtError: LOG.exception(_LE('Unable to create VM snapshot, ' 'failing volume_snapshot operation.'), instance=instance) raise def _volume_refresh_connection_info(self, context, instance, volume_id): bdm = objects.BlockDeviceMapping.get_by_volume_and_instance( context, volume_id, instance.uuid) driver_bdm = driver_block_device.convert_volume(bdm) if driver_bdm: driver_bdm.refresh_connection_info(context, instance, self._volume_api, self) def volume_snapshot_create(self, context, instance, volume_id, create_info): """Create snapshots of a Cinder volume via libvirt. :param instance: VM instance object reference :param volume_id: id of volume being snapshotted :param create_info: dict of information used to create snapshots - snapshot_id : ID of snapshot - type : qcow2 / <other> - new_file : qcow2 file created by Cinder which becomes the VM's active image after the snapshot is complete """ LOG.debug("volume_snapshot_create: create_info: %(c_info)s", {'c_info': create_info}, instance=instance) try: guest = self._host.get_guest(instance) except exception.InstanceNotFound: raise exception.InstanceNotRunning(instance_id=instance.uuid) if create_info['type'] != 'qcow2': raise exception.NovaException(_('Unknown type: %s') % create_info['type']) snapshot_id = create_info.get('snapshot_id', None) if snapshot_id is None: raise exception.NovaException(_('snapshot_id required ' 'in create_info')) try: self._volume_snapshot_create(context, instance, guest, volume_id, create_info['new_file']) except Exception: with excutils.save_and_reraise_exception(): LOG.exception(_LE('Error occurred during ' 'volume_snapshot_create, ' 'sending error status to Cinder.'), instance=instance) self._volume_snapshot_update_status( context, snapshot_id, 'error') self._volume_snapshot_update_status( context, snapshot_id, 'creating') def _wait_for_snapshot(): snapshot = self._volume_api.get_snapshot(context, snapshot_id) if snapshot.get('status') != 'creating': self._volume_refresh_connection_info(context, instance, volume_id) raise loopingcall.LoopingCallDone() timer = loopingcall.FixedIntervalLoopingCall(_wait_for_snapshot) timer.start(interval=0.5).wait() @staticmethod def _rebase_with_qemu_img(guest, device, active_disk_object, rebase_base): """Rebase a device tied to a guest using qemu-img. :param guest:the Guest which owns the device being rebased :type guest: nova.virt.libvirt.guest.Guest :param device: the guest block device to rebase :type device: nova.virt.libvirt.guest.BlockDevice :param active_disk_object: the guest block device to rebase :type active_disk_object: nova.virt.libvirt.config.\ LibvirtConfigGuestDisk :param rebase_base: the new parent in the backing chain :type rebase_base: None or string """ # It's unsure how well qemu-img handles network disks for # every protocol. So let's be safe. active_protocol = active_disk_object.source_protocol if active_protocol is not None: msg = _("Something went wrong when deleting a volume snapshot: " "rebasing a %(protocol)s network disk using qemu-img " "has not been fully tested") % {'protocol': active_protocol} LOG.error(msg) raise exception.NovaException(msg) if rebase_base is None: # If backing_file is specified as "" (the empty string), then # the image is rebased onto no backing file (i.e. it will exist # independently of any backing file). backing_file = "" qemu_img_extra_arg = [] else: # If the rebased image is going to have a backing file then # explicitly set the backing file format to avoid any security # concerns related to file format auto detection. backing_file = rebase_base b_file_fmt = images.qemu_img_info(backing_file).file_format qemu_img_extra_arg = ['-F', b_file_fmt] qemu_img_extra_arg.append(active_disk_object.source_path) utils.execute("qemu-img", "rebase", "-b", backing_file, *qemu_img_extra_arg) def _volume_snapshot_delete(self, context, instance, volume_id, snapshot_id, delete_info=None): """Note: if file being merged into == active image: do a blockRebase (pull) operation else: do a blockCommit operation Files must be adjacent in snap chain. :param instance: instance object reference :param volume_id: volume UUID :param snapshot_id: snapshot UUID (unused currently) :param delete_info: { 'type': 'qcow2', 'file_to_merge': 'a.img', 'merge_target_file': 'b.img' or None (if merging file_to_merge into active image) } """ LOG.debug('volume_snapshot_delete: delete_info: %s', delete_info, instance=instance) if delete_info['type'] != 'qcow2': msg = _('Unknown delete_info type %s') % delete_info['type'] raise exception.NovaException(msg) try: guest = self._host.get_guest(instance) except exception.InstanceNotFound: raise exception.InstanceNotRunning(instance_id=instance.uuid) # Find dev name my_dev = None active_disk = None xml = guest.get_xml_desc() xml_doc = etree.fromstring(xml) device_info = vconfig.LibvirtConfigGuest() device_info.parse_dom(xml_doc) active_disk_object = None for guest_disk in device_info.devices: if (guest_disk.root_name != 'disk'): continue if (guest_disk.target_dev is None or guest_disk.serial is None): continue if guest_disk.serial == volume_id: my_dev = guest_disk.target_dev active_disk = guest_disk.source_path active_protocol = guest_disk.source_protocol active_disk_object = guest_disk break if my_dev is None or (active_disk is None and active_protocol is None): msg = _('Disk with id: %s ' 'not found attached to instance.') % volume_id LOG.debug('Domain XML: %s', xml, instance=instance) raise exception.NovaException(msg) LOG.debug("found device at %s", my_dev, instance=instance) def _get_snap_dev(filename, backing_store): if filename is None: msg = _('filename cannot be None') raise exception.NovaException(msg) # libgfapi delete LOG.debug("XML: %s", xml) LOG.debug("active disk object: %s", active_disk_object) # determine reference within backing store for desired image filename_to_merge = filename matched_name = None b = backing_store index = None current_filename = active_disk_object.source_name.split('/')[1] if current_filename == filename_to_merge: return my_dev + '[0]' while b is not None: source_filename = b.source_name.split('/')[1] if source_filename == filename_to_merge: LOG.debug('found match: %s', b.source_name) matched_name = b.source_name index = b.index break b = b.backing_store if matched_name is None: msg = _('no match found for %s') % (filename_to_merge) raise exception.NovaException(msg) LOG.debug('index of match (%s) is %s', b.source_name, index) my_snap_dev = '%s[%s]' % (my_dev, index) return my_snap_dev if delete_info['merge_target_file'] is None: # pull via blockRebase() # Merge the most recent snapshot into the active image rebase_disk = my_dev rebase_base = delete_info['file_to_merge'] # often None if (active_protocol is not None) and (rebase_base is not None): rebase_base = _get_snap_dev(rebase_base, active_disk_object.backing_store) # NOTE(deepakcs): libvirt added support for _RELATIVE in v1.2.7, # and when available this flag _must_ be used to ensure backing # paths are maintained relative by qemu. # # If _RELATIVE flag not found, continue with old behaviour # (relative backing path seems to work for this case) try: libvirt.VIR_DOMAIN_BLOCK_REBASE_RELATIVE relative = rebase_base is not None except AttributeError: LOG.warning(_LW( "Relative blockrebase support was not detected. " "Continuing with old behaviour.")) relative = False LOG.debug( 'disk: %(disk)s, base: %(base)s, ' 'bw: %(bw)s, relative: %(relative)s', {'disk': rebase_disk, 'base': rebase_base, 'bw': libvirt_guest.BlockDevice.REBASE_DEFAULT_BANDWIDTH, 'relative': str(relative)}, instance=instance) dev = guest.get_block_device(rebase_disk) if guest.is_active(): result = dev.rebase(rebase_base, relative=relative) if result == 0: LOG.debug('blockRebase started successfully', instance=instance) while dev.wait_for_job(abort_on_error=True): LOG.debug('waiting for blockRebase job completion', instance=instance) time.sleep(0.5) # If the guest is not running libvirt won't do a blockRebase. # In that case, let's ask qemu-img to rebase the disk. else: LOG.debug('Guest is not running so doing a block rebase ' 'using "qemu-img rebase"', instance=instance) self._rebase_with_qemu_img(guest, dev, active_disk_object, rebase_base) else: # commit with blockCommit() my_snap_base = None my_snap_top = None commit_disk = my_dev # NOTE(deepakcs): libvirt added support for _RELATIVE in v1.2.7, # and when available this flag _must_ be used to ensure backing # paths are maintained relative by qemu. # # If _RELATIVE flag not found, raise exception as relative backing # path may not be maintained and Cinder flow is broken if allowed # to continue. try: libvirt.VIR_DOMAIN_BLOCK_COMMIT_RELATIVE except AttributeError: ver = '.'.join( [str(x) for x in MIN_LIBVIRT_BLOCKJOB_RELATIVE_VERSION]) msg = _("Relative blockcommit support was not detected. " "Libvirt '%s' or later is required for online " "deletion of file/network storage-backed volume " "snapshots.") % ver raise exception.Invalid(msg) if active_protocol is not None: my_snap_base = _get_snap_dev(delete_info['merge_target_file'], active_disk_object.backing_store) my_snap_top = _get_snap_dev(delete_info['file_to_merge'], active_disk_object.backing_store) commit_base = my_snap_base or delete_info['merge_target_file'] commit_top = my_snap_top or delete_info['file_to_merge'] LOG.debug('will call blockCommit with commit_disk=%(commit_disk)s ' 'commit_base=%(commit_base)s ' 'commit_top=%(commit_top)s ', {'commit_disk': commit_disk, 'commit_base': commit_base, 'commit_top': commit_top}, instance=instance) dev = guest.get_block_device(commit_disk) result = dev.commit(commit_base, commit_top, relative=True) if result == 0: LOG.debug('blockCommit started successfully', instance=instance) while dev.wait_for_job(abort_on_error=True): LOG.debug('waiting for blockCommit job completion', instance=instance) time.sleep(0.5) def volume_snapshot_delete(self, context, instance, volume_id, snapshot_id, delete_info): try: self._volume_snapshot_delete(context, instance, volume_id, snapshot_id, delete_info=delete_info) except Exception: with excutils.save_and_reraise_exception(): LOG.exception(_LE('Error occurred during ' 'volume_snapshot_delete, ' 'sending error status to Cinder.'), instance=instance) self._volume_snapshot_update_status( context, snapshot_id, 'error_deleting') self._volume_snapshot_update_status(context, snapshot_id, 'deleting') self._volume_refresh_connection_info(context, instance, volume_id) def reboot(self, context, instance, network_info, reboot_type, block_device_info=None, bad_volumes_callback=None): """Reboot a virtual machine, given an instance reference.""" if reboot_type == 'SOFT': # NOTE(vish): This will attempt to do a graceful shutdown/restart. try: soft_reboot_success = self._soft_reboot(instance) except libvirt.libvirtError as e: LOG.debug("Instance soft reboot failed: %s", e, instance=instance) soft_reboot_success = False if soft_reboot_success: LOG.info(_LI("Instance soft rebooted successfully."), instance=instance) return else: LOG.warning(_LW("Failed to soft reboot instance. " "Trying hard reboot."), instance=instance) return self._hard_reboot(context, instance, network_info, block_device_info) def _soft_reboot(self, instance): """Attempt to shutdown and restart the instance gracefully. We use shutdown and create here so we can return if the guest responded and actually rebooted. Note that this method only succeeds if the guest responds to acpi. Therefore we return success or failure so we can fall back to a hard reboot if necessary. :returns: True if the reboot succeeded """ guest = self._host.get_guest(instance) state = guest.get_power_state(self._host) old_domid = guest.id # NOTE(vish): This check allows us to reboot an instance that # is already shutdown. if state == power_state.RUNNING: guest.shutdown() # NOTE(vish): This actually could take slightly longer than the # FLAG defines depending on how long the get_info # call takes to return. self._prepare_pci_devices_for_use( pci_manager.get_instance_pci_devs(instance, 'all')) for x in range(CONF.libvirt.wait_soft_reboot_seconds): guest = self._host.get_guest(instance) state = guest.get_power_state(self._host) new_domid = guest.id # NOTE(ivoks): By checking domain IDs, we make sure we are # not recreating domain that's already running. if old_domid != new_domid: if state in [power_state.SHUTDOWN, power_state.CRASHED]: LOG.info(_LI("Instance shutdown successfully."), instance=instance) self._create_domain(domain=guest._domain) timer = loopingcall.FixedIntervalLoopingCall( self._wait_for_running, instance) timer.start(interval=0.5).wait() return True else: LOG.info(_LI("Instance may have been rebooted during soft " "reboot, so return now."), instance=instance) return True greenthread.sleep(1) return False def _hard_reboot(self, context, instance, network_info, block_device_info=None): """Reboot a virtual machine, given an instance reference. Performs a Libvirt reset (if supported) on the domain. If Libvirt reset is unavailable this method actually destroys and re-creates the domain to ensure the reboot happens, as the guest OS cannot ignore this action. """ self._destroy(instance) # Domain XML will be redefined so we can safely undefine it # from libvirt. This ensure that such process as create serial # console for guest will run smoothly. self._undefine_domain(instance) # Convert the system metadata to image metadata instance_dir = libvirt_utils.get_instance_path(instance) fileutils.ensure_tree(instance_dir) disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance, instance.image_meta, block_device_info) # NOTE(vish): This could generate the wrong device_format if we are # using the raw backend and the images don't exist yet. # The create_images_and_backing below doesn't properly # regenerate raw backend images, however, so when it # does we need to (re)generate the xml after the images # are in place. xml = self._get_guest_xml(context, instance, network_info, disk_info, instance.image_meta, block_device_info=block_device_info, write_to_disk=True) if context.auth_token is not None: # NOTE (rmk): Re-populate any missing backing files. backing_disk_info = self._get_instance_disk_info(instance.name, xml, block_device_info) self._create_images_and_backing(context, instance, instance_dir, backing_disk_info) # Initialize all the necessary networking, block devices and # start the instance. self._create_domain_and_network(context, xml, instance, network_info, disk_info, block_device_info=block_device_info, reboot=True, vifs_already_plugged=True) self._prepare_pci_devices_for_use( pci_manager.get_instance_pci_devs(instance, 'all')) def _wait_for_reboot(): """Called at an interval until the VM is running again.""" state = self.get_info(instance).state if state == power_state.RUNNING: LOG.info(_LI("Instance rebooted successfully."), instance=instance) raise loopingcall.LoopingCallDone() timer = loopingcall.FixedIntervalLoopingCall(_wait_for_reboot) timer.start(interval=0.5).wait() def pause(self, instance): """Pause VM instance.""" self._host.get_guest(instance).pause() def unpause(self, instance): """Unpause paused VM instance.""" self._host.get_guest(instance).resume() def _clean_shutdown(self, instance, timeout, retry_interval): """Attempt to shutdown the instance gracefully. :param instance: The instance to be shutdown :param timeout: How long to wait in seconds for the instance to shutdown :param retry_interval: How often in seconds to signal the instance to shutdown while waiting :returns: True if the shutdown succeeded """ # List of states that represent a shutdown instance SHUTDOWN_STATES = [power_state.SHUTDOWN, power_state.CRASHED] try: guest = self._host.get_guest(instance) except exception.InstanceNotFound: # If the instance has gone then we don't need to # wait for it to shutdown return True state = guest.get_power_state(self._host) if state in SHUTDOWN_STATES: LOG.info(_LI("Instance already shutdown."), instance=instance) return True LOG.debug("Shutting down instance from state %s", state, instance=instance) guest.shutdown() retry_countdown = retry_interval for sec in six.moves.range(timeout): guest = self._host.get_guest(instance) state = guest.get_power_state(self._host) if state in SHUTDOWN_STATES: LOG.info(_LI("Instance shutdown successfully after %d " "seconds."), sec, instance=instance) return True # Note(PhilD): We can't assume that the Guest was able to process # any previous shutdown signal (for example it may # have still been startingup, so within the overall # timeout we re-trigger the shutdown every # retry_interval if retry_countdown == 0: retry_countdown = retry_interval # Instance could shutdown at any time, in which case we # will get an exception when we call shutdown try: LOG.debug("Instance in state %s after %d seconds - " "resending shutdown", state, sec, instance=instance) guest.shutdown() except libvirt.libvirtError: # Assume this is because its now shutdown, so loop # one more time to clean up. LOG.debug("Ignoring libvirt exception from shutdown " "request.", instance=instance) continue else: retry_countdown -= 1 time.sleep(1) LOG.info(_LI("Instance failed to shutdown in %d seconds."), timeout, instance=instance) return False def power_off(self, instance, timeout=0, retry_interval=0): """Power off the specified instance.""" if timeout: self._clean_shutdown(instance, timeout, retry_interval) self._destroy(instance) def power_on(self, context, instance, network_info, block_device_info=None): """Power on the specified instance.""" # We use _hard_reboot here to ensure that all backing files, # network, and block device connections, etc. are established # and available before we attempt to start the instance. self._hard_reboot(context, instance, network_info, block_device_info) def trigger_crash_dump(self, instance): """Trigger crash dump by injecting an NMI to the specified instance.""" try: self._host.get_guest(instance).inject_nmi() except libvirt.libvirtError as ex: error_code = ex.get_error_code() if error_code == libvirt.VIR_ERR_NO_SUPPORT: raise exception.TriggerCrashDumpNotSupported() elif error_code == libvirt.VIR_ERR_OPERATION_INVALID: raise exception.InstanceNotRunning(instance_id=instance.uuid) LOG.exception(_LE('Error from libvirt while injecting an NMI to ' '%(instance_uuid)s: ' '[Error Code %(error_code)s] %(ex)s'), {'instance_uuid': instance.uuid, 'error_code': error_code, 'ex': ex}) raise def suspend(self, context, instance): """Suspend the specified instance.""" guest = self._host.get_guest(instance) self._detach_pci_devices(guest, pci_manager.get_instance_pci_devs(instance)) self._detach_sriov_ports(context, instance, guest) guest.save_memory_state() def resume(self, context, instance, network_info, block_device_info=None): """resume the specified instance.""" disk_info = blockinfo.get_disk_info( CONF.libvirt.virt_type, instance, instance.image_meta, block_device_info=block_device_info) xml = self._get_existing_domain_xml(instance, network_info, block_device_info) guest = self._create_domain_and_network(context, xml, instance, network_info, disk_info, block_device_info=block_device_info, vifs_already_plugged=True) self._attach_pci_devices(guest, pci_manager.get_instance_pci_devs(instance)) self._attach_sriov_ports(context, instance, guest, network_info) def resume_state_on_host_boot(self, context, instance, network_info, block_device_info=None): """resume guest state when a host is booted.""" # Check if the instance is running already and avoid doing # anything if it is. try: guest = self._host.get_guest(instance) state = guest.get_power_state(self._host) ignored_states = (power_state.RUNNING, power_state.SUSPENDED, power_state.NOSTATE, power_state.PAUSED) if state in ignored_states: return except exception.NovaException: pass # Instance is not up and could be in an unknown state. # Be as absolute as possible about getting it back into # a known and running state. self._hard_reboot(context, instance, network_info, block_device_info) def rescue(self, context, instance, network_info, image_meta, rescue_password): """Loads a VM using rescue images. A rescue is normally performed when something goes wrong with the primary images and data needs to be corrected/recovered. Rescuing should not edit or over-ride the original image, only allow for data recovery. """ instance_dir = libvirt_utils.get_instance_path(instance) unrescue_xml = self._get_existing_domain_xml(instance, network_info) unrescue_xml_path = os.path.join(instance_dir, 'unrescue.xml') libvirt_utils.write_to_file(unrescue_xml_path, unrescue_xml) rescue_image_id = None if image_meta.obj_attr_is_set("id"): rescue_image_id = image_meta.id rescue_images = { 'image_id': (rescue_image_id or CONF.libvirt.rescue_image_id or instance.image_ref), 'kernel_id': (CONF.libvirt.rescue_kernel_id or instance.kernel_id), 'ramdisk_id': (CONF.libvirt.rescue_ramdisk_id or instance.ramdisk_id), } disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance, image_meta, rescue=True) gen_confdrive = functools.partial(self._create_configdrive, context, instance, admin_pass=rescue_password, network_info=network_info, suffix='.rescue') self._create_image(context, instance, disk_info['mapping'], suffix='.rescue', disk_images=rescue_images, network_info=network_info, admin_pass=rescue_password) xml = self._get_guest_xml(context, instance, network_info, disk_info, image_meta, rescue=rescue_images, write_to_disk=True) self._destroy(instance) self._create_domain(xml, post_xml_callback=gen_confdrive) def unrescue(self, instance, network_info): """Reboot the VM which is being rescued back into primary images. """ instance_dir = libvirt_utils.get_instance_path(instance) unrescue_xml_path = os.path.join(instance_dir, 'unrescue.xml') xml_path = os.path.join(instance_dir, 'libvirt.xml') xml = libvirt_utils.load_file(unrescue_xml_path) libvirt_utils.write_to_file(xml_path, xml) guest = self._host.get_guest(instance) # TODO(sahid): We are converting all calls from a # virDomain object to use nova.virt.libvirt.Guest. # We should be able to remove virt_dom at the end. virt_dom = guest._domain self._destroy(instance) self._create_domain(xml, virt_dom) libvirt_utils.file_delete(unrescue_xml_path) rescue_files = os.path.join(instance_dir, "*.rescue") for rescue_file in glob.iglob(rescue_files): if os.path.isdir(rescue_file): shutil.rmtree(rescue_file) else: libvirt_utils.file_delete(rescue_file) # cleanup rescue volume lvm.remove_volumes([lvmdisk for lvmdisk in self._lvm_disks(instance) if lvmdisk.endswith('.rescue')]) if CONF.libvirt.images_type == 'rbd': filter_fn = lambda disk: (disk.startswith(instance.uuid) and disk.endswith('.rescue')) LibvirtDriver._get_rbd_driver().cleanup_volumes(filter_fn) # def poll_rebooting_instances(self, timeout, instances): # pass # NOTE(ilyaalekseyev): Implementation like in multinics # for xenapi(tr3buchet) def spawn(self, context, instance, image_meta, injected_files, admin_password, network_info=None, block_device_info=None): disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance, image_meta, block_device_info) gen_confdrive = functools.partial(self._create_configdrive, context, instance, admin_pass=admin_password, files=injected_files, network_info=network_info) self._create_image(context, instance, disk_info['mapping'], network_info=network_info, block_device_info=block_device_info, files=injected_files, admin_pass=admin_password) # Required by Quobyte CI self._ensure_console_log_for_instance(instance) xml = self._get_guest_xml(context, instance, network_info, disk_info, image_meta, block_device_info=block_device_info, write_to_disk=True) self._create_domain_and_network( context, xml, instance, network_info, disk_info, block_device_info=block_device_info, post_xml_callback=gen_confdrive) LOG.debug("Instance is running", instance=instance) def _wait_for_boot(): """Called at an interval until the VM is running.""" state = self.get_info(instance).state if state == power_state.RUNNING: LOG.info(_LI("Instance spawned successfully."), instance=instance) raise loopingcall.LoopingCallDone() timer = loopingcall.FixedIntervalLoopingCall(_wait_for_boot) timer.start(interval=0.5).wait() def _flush_libvirt_console(self, pty): out, err = utils.execute('dd', 'if=%s' % pty, 'iflag=nonblock', run_as_root=True, check_exit_code=False) return out def _append_to_file(self, data, fpath): LOG.info(_LI('data: %(data)r, fpath: %(fpath)r'), {'data': data, 'fpath': fpath}) with open(fpath, 'a+') as fp: fp.write(data) return fpath def get_console_output(self, context, instance): guest = self._host.get_guest(instance) xml = guest.get_xml_desc() tree = etree.fromstring(xml) console_types = {} # NOTE(comstud): We want to try 'file' types first, then try 'pty' # types. We can't use Python 2.7 syntax of: # tree.find("./devices/console[@type='file']/source") # because we need to support 2.6. console_nodes = tree.findall('./devices/console') for console_node in console_nodes: console_type = console_node.get('type') console_types.setdefault(console_type, []) console_types[console_type].append(console_node) # If the guest has a console logging to a file prefer to use that if console_types.get('file'): for file_console in console_types.get('file'): source_node = file_console.find('./source') if source_node is None: continue path = source_node.get("path") if not path: continue if not os.path.exists(path): LOG.info(_LI('Instance is configured with a file console, ' 'but the backing file is not (yet?) present'), instance=instance) return "" libvirt_utils.chown(path, os.getuid()) with libvirt_utils.file_open(path, 'rb') as fp: log_data, remaining = utils.last_bytes(fp, MAX_CONSOLE_BYTES) if remaining > 0: LOG.info(_LI('Truncated console log returned, ' '%d bytes ignored'), remaining, instance=instance) return log_data # Try 'pty' types if console_types.get('pty'): for pty_console in console_types.get('pty'): source_node = pty_console.find('./source') if source_node is None: continue pty = source_node.get("path") if not pty: continue break else: raise exception.ConsoleNotAvailable() console_log = self._get_console_log_path(instance) # By default libvirt chowns the console log when it starts a domain. # We need to chown it back before attempting to read from or write # to it. if os.path.exists(console_log): libvirt_utils.chown(console_log, os.getuid()) data = self._flush_libvirt_console(pty) fpath = self._append_to_file(data, console_log) with libvirt_utils.file_open(fpath, 'rb') as fp: log_data, remaining = utils.last_bytes(fp, MAX_CONSOLE_BYTES) if remaining > 0: LOG.info(_LI('Truncated console log returned, ' '%d bytes ignored'), remaining, instance=instance) return log_data def get_host_ip_addr(self): ips = compute_utils.get_machine_ips() if CONF.my_ip not in ips: LOG.warning(_LW('my_ip address (%(my_ip)s) was not found on ' 'any of the interfaces: %(ifaces)s'), {'my_ip': CONF.my_ip, 'ifaces': ", ".join(ips)}) return CONF.my_ip def get_vnc_console(self, context, instance): def get_vnc_port_for_instance(instance_name): guest = self._host.get_guest(instance) xml = guest.get_xml_desc() xml_dom = etree.fromstring(xml) graphic = xml_dom.find("./devices/graphics[@type='vnc']") if graphic is not None: return graphic.get('port') # NOTE(rmk): We had VNC consoles enabled but the instance in # question is not actually listening for connections. raise exception.ConsoleTypeUnavailable(console_type='vnc') port = get_vnc_port_for_instance(instance.name) host = CONF.vnc.vncserver_proxyclient_address return ctype.ConsoleVNC(host=host, port=port) def get_spice_console(self, context, instance): def get_spice_ports_for_instance(instance_name): guest = self._host.get_guest(instance) xml = guest.get_xml_desc() xml_dom = etree.fromstring(xml) graphic = xml_dom.find("./devices/graphics[@type='spice']") if graphic is not None: return (graphic.get('port'), graphic.get('tlsPort')) # NOTE(rmk): We had Spice consoles enabled but the instance in # question is not actually listening for connections. raise exception.ConsoleTypeUnavailable(console_type='spice') ports = get_spice_ports_for_instance(instance.name) host = CONF.spice.server_proxyclient_address return ctype.ConsoleSpice(host=host, port=ports[0], tlsPort=ports[1]) def get_serial_console(self, context, instance): guest = self._host.get_guest(instance) for hostname, port in self._get_serial_ports_from_guest( guest, mode='bind'): return ctype.ConsoleSerial(host=hostname, port=port) raise exception.ConsoleTypeUnavailable(console_type='serial') @staticmethod def _supports_direct_io(dirpath): if not hasattr(os, 'O_DIRECT'): LOG.debug("This python runtime does not support direct I/O") return False testfile = os.path.join(dirpath, ".directio.test") hasDirectIO = True fd = None try: fd = os.open(testfile, os.O_CREAT | os.O_WRONLY | os.O_DIRECT) # Check is the write allowed with 512 byte alignment align_size = 512 m = mmap.mmap(-1, align_size) m.write(r"x" * align_size) os.write(fd, m) LOG.debug("Path '%(path)s' supports direct I/O", {'path': dirpath}) except OSError as e: if e.errno == errno.EINVAL: LOG.debug("Path '%(path)s' does not support direct I/O: " "'%(ex)s'", {'path': dirpath, 'ex': e}) hasDirectIO = False else: with excutils.save_and_reraise_exception(): LOG.error(_LE("Error on '%(path)s' while checking " "direct I/O: '%(ex)s'"), {'path': dirpath, 'ex': e}) except Exception as e: with excutils.save_and_reraise_exception(): LOG.error(_LE("Error on '%(path)s' while checking direct I/O: " "'%(ex)s'"), {'path': dirpath, 'ex': e}) finally: # ensure unlink(filepath) will actually remove the file by deleting # the remaining link to it in close(fd) if fd is not None: os.close(fd) try: os.unlink(testfile) except Exception: pass return hasDirectIO @staticmethod def _create_ephemeral(target, ephemeral_size, fs_label, os_type, is_block_dev=False, context=None, specified_fs=None): if not is_block_dev: libvirt_utils.create_image('raw', target, '%dG' % ephemeral_size) # Run as root only for block devices. disk_api.mkfs(os_type, fs_label, target, run_as_root=is_block_dev, specified_fs=specified_fs) @staticmethod def _create_swap(target, swap_mb, context=None): """Create a swap file of specified size.""" libvirt_utils.create_image('raw', target, '%dM' % swap_mb) utils.mkfs('swap', target) @staticmethod def _get_console_log_path(instance): return os.path.join(libvirt_utils.get_instance_path(instance), 'console.log') def _ensure_console_log_for_instance(self, instance): # NOTE(mdbooth): Although libvirt will create this file for us # automatically when it starts, it will initially create it with # root ownership and then chown it depending on the configuration of # the domain it is launching. Quobyte CI explicitly disables the # chown by setting dynamic_ownership=0 in libvirt's config. # Consequently when the domain starts it is unable to write to its # console.log. See bug https://bugs.launchpad.net/nova/+bug/1597644 # # To work around this, we create the file manually before starting # the domain so it has the same ownership as Nova. This works # for Quobyte CI because it is also configured to run qemu as the same # user as the Nova service. Installations which don't set # dynamic_ownership=0 are not affected because libvirt will always # correctly configure permissions regardless of initial ownership. # # Setting dynamic_ownership=0 is dubious and potentially broken in # more ways than console.log (see comment #22 on the above bug), so # Future Maintainer who finds this code problematic should check to see # if we still support it. console_file = self._get_console_log_path(instance) LOG.debug('Ensure instance console log exists: %s', console_file, instance=instance) libvirt_utils.file_open(console_file, 'a').close() @staticmethod def _get_disk_config_path(instance, suffix=''): return os.path.join(libvirt_utils.get_instance_path(instance), 'disk.config' + suffix) @staticmethod def _get_disk_config_image_type(): # TODO(mikal): there is a bug here if images_type has # changed since creation of the instance, but I am pretty # sure that this bug already exists. return 'rbd' if CONF.libvirt.images_type == 'rbd' else 'raw' @staticmethod def _is_booted_from_volume(instance, disk_mapping): """Determines whether the VM is booting from volume Determines whether the disk mapping indicates that the VM is booting from a volume. """ return ((not bool(instance.get('image_ref'))) or 'disk' not in disk_mapping) @staticmethod def _has_local_disk(instance, disk_mapping): """Determines whether the VM has a local disk Determines whether the disk mapping indicates that the VM has a local disk (e.g. ephemeral, swap disk and config-drive). """ if disk_mapping: if ('disk.local' in disk_mapping or 'disk.swap' in disk_mapping or 'disk.config' in disk_mapping): return True return False def _inject_data(self, injection_image, instance, network_info, admin_pass, files): """Injects data in a disk image Helper used for injecting data in a disk image file system. Keyword arguments: injection_image -- An Image object we're injecting into instance -- a dict that refers instance specifications network_info -- a dict that refers network speficications admin_pass -- a string used to set an admin password files -- a list of files needs to be injected """ # Handles the partition need to be used. target_partition = None if not instance.kernel_id: target_partition = CONF.libvirt.inject_partition if target_partition == 0: target_partition = None if CONF.libvirt.virt_type == 'lxc': target_partition = None # Handles the key injection. if CONF.libvirt.inject_key and instance.get('key_data'): key = str(instance.key_data) else: key = None # Handles the admin password injection. if not CONF.libvirt.inject_password: admin_pass = None # Handles the network injection. net = netutils.get_injected_network_template( network_info, libvirt_virt_type=CONF.libvirt.virt_type) # Handles the metadata injection metadata = instance.get('metadata') if any((key, net, metadata, admin_pass, files)): img_id = instance.image_ref try: disk_api.inject_data(injection_image.get_model(self._conn), key, net, metadata, admin_pass, files, partition=target_partition, mandatory=('files',)) except Exception as e: with excutils.save_and_reraise_exception(): LOG.error(_LE('Error injecting data into image ' '%(img_id)s (%(e)s)'), {'img_id': img_id, 'e': e}, instance=instance) # NOTE(sileht): many callers of this method assume that this # method doesn't fail if an image already exists but instead # think that it will be reused (ie: (live)-migration/resize) def _create_image(self, context, instance, disk_mapping, suffix='', disk_images=None, network_info=None, block_device_info=None, files=None, admin_pass=None, inject_files=True, fallback_from_host=None): booted_from_volume = self._is_booted_from_volume( instance, disk_mapping) def image(fname, image_type=CONF.libvirt.images_type): return self.image_backend.image(instance, fname + suffix, image_type) def raw(fname): return image(fname, image_type='raw') # ensure directories exist and are writable fileutils.ensure_tree(libvirt_utils.get_instance_path(instance)) LOG.info(_LI('Creating image'), instance=instance) if not disk_images: disk_images = {'image_id': instance.image_ref, 'kernel_id': instance.kernel_id, 'ramdisk_id': instance.ramdisk_id} if disk_images['kernel_id']: fname = imagecache.get_cache_fname(disk_images['kernel_id']) raw('kernel').cache(fetch_func=libvirt_utils.fetch_raw_image, context=context, filename=fname, image_id=disk_images['kernel_id']) if disk_images['ramdisk_id']: fname = imagecache.get_cache_fname(disk_images['ramdisk_id']) raw('ramdisk').cache(fetch_func=libvirt_utils.fetch_raw_image, context=context, filename=fname, image_id=disk_images['ramdisk_id']) inst_type = instance.get_flavor() if CONF.libvirt.virt_type == 'uml': libvirt_utils.chown(image('disk').path, 'root') self._create_and_inject_local_root(context, instance, booted_from_volume, suffix, disk_images, network_info, admin_pass, files, inject_files, fallback_from_host) # Lookup the filesystem type if required os_type_with_default = disk_api.get_fs_type_for_os_type( instance.os_type) # Generate a file extension based on the file system # type and the mkfs commands configured if any file_extension = disk_api.get_file_extension_for_os_type( os_type_with_default) ephemeral_gb = instance.flavor.ephemeral_gb if 'disk.local' in disk_mapping: disk_image = image('disk.local') fn = functools.partial(self._create_ephemeral, fs_label='ephemeral0', os_type=instance.os_type, is_block_dev=disk_image.is_block_dev) fname = "ephemeral_%s_%s" % (ephemeral_gb, file_extension) size = ephemeral_gb * units.Gi disk_image.cache(fetch_func=fn, context=context, filename=fname, size=size, ephemeral_size=ephemeral_gb) for idx, eph in enumerate(driver.block_device_info_get_ephemerals( block_device_info)): disk_image = image(blockinfo.get_eph_disk(idx)) specified_fs = eph.get('guest_format') if specified_fs and not self.is_supported_fs_format(specified_fs): msg = _("%s format is not supported") % specified_fs raise exception.InvalidBDMFormat(details=msg) fn = functools.partial(self._create_ephemeral, fs_label='ephemeral%d' % idx, os_type=instance.os_type, is_block_dev=disk_image.is_block_dev) size = eph['size'] * units.Gi fname = "ephemeral_%s_%s" % (eph['size'], file_extension) disk_image.cache(fetch_func=fn, context=context, filename=fname, size=size, ephemeral_size=eph['size'], specified_fs=specified_fs) if 'disk.swap' in disk_mapping: mapping = disk_mapping['disk.swap'] swap_mb = 0 swap = driver.block_device_info_get_swap(block_device_info) if driver.swap_is_usable(swap): swap_mb = swap['swap_size'] elif (inst_type['swap'] > 0 and not block_device.volume_in_mapping( mapping['dev'], block_device_info)): swap_mb = inst_type['swap'] if swap_mb > 0: size = swap_mb * units.Mi image('disk.swap').cache(fetch_func=self._create_swap, context=context, filename="swap_%s" % swap_mb, size=size, swap_mb=swap_mb) def _create_and_inject_local_root(self, context, instance, booted_from_volume, suffix, disk_images, network_info, admin_pass, files, inject_files, fallback_from_host): # File injection only if needed need_inject = (not configdrive.required_by(instance) and inject_files and CONF.libvirt.inject_partition != -2) # NOTE(ndipanov): Even if disk_mapping was passed in, which # currently happens only on rescue - we still don't want to # create a base image. if not booted_from_volume: root_fname = imagecache.get_cache_fname(disk_images['image_id']) size = instance.flavor.root_gb * units.Gi if size == 0 or suffix == '.rescue': size = None backend = self.image_backend.image(instance, 'disk' + suffix, CONF.libvirt.images_type) if instance.task_state == task_states.RESIZE_FINISH: backend.create_snap(libvirt_utils.RESIZE_SNAPSHOT_NAME) if backend.SUPPORTS_CLONE: def clone_fallback_to_fetch(*args, **kwargs): try: backend.clone(context, disk_images['image_id']) except exception.ImageUnacceptable: libvirt_utils.fetch_image(*args, **kwargs) fetch_func = clone_fallback_to_fetch else: fetch_func = libvirt_utils.fetch_image self._try_fetch_image_cache(backend, fetch_func, context, root_fname, disk_images['image_id'], instance, size, fallback_from_host) if need_inject: self._inject_data(backend, instance, network_info, admin_pass, files) elif need_inject: LOG.warning(_LW('File injection into a boot from volume ' 'instance is not supported'), instance=instance) def _create_configdrive(self, context, instance, admin_pass=None, files=None, network_info=None, suffix=''): # As this method being called right after the definition of a # domain, but before its actual launch, device metadata will be built # and saved in the instance for it to be used by the config drive and # the metadata service. instance.device_metadata = self._build_device_metadata(context, instance) config_drive_image = None if configdrive.required_by(instance): LOG.info(_LI('Using config drive'), instance=instance) config_drive_image = self.image_backend.image( instance, 'disk.config' + suffix, self._get_disk_config_image_type()) # Don't overwrite an existing config drive if not config_drive_image.exists(): extra_md = {} if admin_pass: extra_md['admin_pass'] = admin_pass inst_md = instance_metadata.InstanceMetadata( instance, content=files, extra_md=extra_md, network_info=network_info, request_context=context) cdb = configdrive.ConfigDriveBuilder(instance_md=inst_md) with cdb: config_drive_local_path = self._get_disk_config_path( instance, suffix) LOG.info(_LI('Creating config drive at %(path)s'), {'path': config_drive_local_path}, instance=instance) try: cdb.make_drive(config_drive_local_path) except processutils.ProcessExecutionError as e: with excutils.save_and_reraise_exception(): LOG.error(_LE('Creating config drive failed ' 'with error: %s'), e, instance=instance) try: config_drive_image.import_file( instance, config_drive_local_path, 'disk.config' + suffix) finally: # NOTE(mikal): if the config drive was imported into RBD, # then we no longer need the local copy if CONF.libvirt.images_type == 'rbd': os.unlink(config_drive_local_path) def _prepare_pci_devices_for_use(self, pci_devices): # kvm , qemu support managed mode # In managed mode, the configured device will be automatically # detached from the host OS drivers when the guest is started, # and then re-attached when the guest shuts down. if CONF.libvirt.virt_type != 'xen': # we do manual detach only for xen return try: for dev in pci_devices: libvirt_dev_addr = dev['hypervisor_name'] libvirt_dev = \ self._host.device_lookup_by_name(libvirt_dev_addr) # Note(yjiang5) Spelling for 'dettach' is correct, see # http://libvirt.org/html/libvirt-libvirt.html. libvirt_dev.dettach() # Note(yjiang5): A reset of one PCI device may impact other # devices on the same bus, thus we need two separated loops # to detach and then reset it. for dev in pci_devices: libvirt_dev_addr = dev['hypervisor_name'] libvirt_dev = \ self._host.device_lookup_by_name(libvirt_dev_addr) libvirt_dev.reset() except libvirt.libvirtError as exc: raise exception.PciDevicePrepareFailed(id=dev['id'], instance_uuid= dev['instance_uuid'], reason=six.text_type(exc)) def _detach_pci_devices(self, guest, pci_devs): try: for dev in pci_devs: guest.detach_device(self._get_guest_pci_device(dev), live=True) # after detachDeviceFlags returned, we should check the dom to # ensure the detaching is finished xml = guest.get_xml_desc() xml_doc = etree.fromstring(xml) guest_config = vconfig.LibvirtConfigGuest() guest_config.parse_dom(xml_doc) for hdev in [d for d in guest_config.devices if isinstance(d, vconfig.LibvirtConfigGuestHostdevPCI)]: hdbsf = [hdev.domain, hdev.bus, hdev.slot, hdev.function] dbsf = pci_utils.parse_address(dev.address) if [int(x, 16) for x in hdbsf] ==\ [int(x, 16) for x in dbsf]: raise exception.PciDeviceDetachFailed(reason= "timeout", dev=dev) except libvirt.libvirtError as ex: error_code = ex.get_error_code() if error_code == libvirt.VIR_ERR_NO_DOMAIN: LOG.warning(_LW("Instance disappeared while detaching " "a PCI device from it.")) else: raise def _attach_pci_devices(self, guest, pci_devs): try: for dev in pci_devs: guest.attach_device(self._get_guest_pci_device(dev)) except libvirt.libvirtError: LOG.error(_LE('Attaching PCI devices %(dev)s to %(dom)s failed.'), {'dev': pci_devs, 'dom': guest.id}) raise @staticmethod def _has_sriov_port(network_info): for vif in network_info: if vif['vnic_type'] == network_model.VNIC_TYPE_DIRECT: return True return False def _attach_sriov_ports(self, context, instance, guest, network_info=None): if network_info is None: network_info = instance.info_cache.network_info if network_info is None: return if self._has_sriov_port(network_info): for vif in network_info: if vif['vnic_type'] in network_model.VNIC_TYPES_SRIOV: cfg = self.vif_driver.get_config(instance, vif, instance.image_meta, instance.flavor, CONF.libvirt.virt_type, self._host) LOG.debug('Attaching SR-IOV port %(port)s to %(dom)s', {'port': vif, 'dom': guest.id}, instance=instance) guest.attach_device(cfg) def _detach_sriov_ports(self, context, instance, guest): network_info = instance.info_cache.network_info if network_info is None: return if self._has_sriov_port(network_info): # In case of SR-IOV vif types we create pci request per SR-IOV port # Therefore we can trust that pci_slot value in the vif is correct. sriov_pci_addresses = [ vif['profile']['pci_slot'] for vif in network_info if vif['vnic_type'] in network_model.VNIC_TYPES_SRIOV and vif['profile'].get('pci_slot') is not None ] # use detach_pci_devices to avoid failure in case of # multiple guest SRIOV ports with the same MAC # (protection use-case, ports are on different physical # interfaces) pci_devs = pci_manager.get_instance_pci_devs(instance, 'all') sriov_devs = [pci_dev for pci_dev in pci_devs if pci_dev.address in sriov_pci_addresses] self._detach_pci_devices(guest, sriov_devs) def _set_host_enabled(self, enabled, disable_reason=DISABLE_REASON_UNDEFINED): """Enables / Disables the compute service on this host. This doesn't override non-automatic disablement with an automatic setting; thereby permitting operators to keep otherwise healthy hosts out of rotation. """ status_name = {True: 'disabled', False: 'enabled'} disable_service = not enabled ctx = nova_context.get_admin_context() try: service = objects.Service.get_by_compute_host(ctx, CONF.host) if service.disabled != disable_service: # Note(jang): this is a quick fix to stop operator- # disabled compute hosts from re-enabling themselves # automatically. We prefix any automatic reason code # with a fixed string. We only re-enable a host # automatically if we find that string in place. # This should probably be replaced with a separate flag. if not service.disabled or ( service.disabled_reason and service.disabled_reason.startswith(DISABLE_PREFIX)): service.disabled = disable_service service.disabled_reason = ( DISABLE_PREFIX + disable_reason if disable_service else DISABLE_REASON_UNDEFINED) service.save() LOG.debug('Updating compute service status to %s', status_name[disable_service]) else: LOG.debug('Not overriding manual compute service ' 'status with: %s', status_name[disable_service]) except exception.ComputeHostNotFound: LOG.warning(_LW('Cannot update service status on host "%s" ' 'since it is not registered.'), CONF.host) except Exception: LOG.warning(_LW('Cannot update service status on host "%s" ' 'due to an unexpected exception.'), CONF.host, exc_info=True) def _get_guest_cpu_model_config(self): mode = CONF.libvirt.cpu_mode model = CONF.libvirt.cpu_model if (CONF.libvirt.virt_type == "kvm" or CONF.libvirt.virt_type == "qemu"): if mode is None: mode = "host-model" if mode == "none": return vconfig.LibvirtConfigGuestCPU() else: if mode is None or mode == "none": return None if ((CONF.libvirt.virt_type != "kvm" and CONF.libvirt.virt_type != "qemu")): msg = _("Config requested an explicit CPU model, but " "the current libvirt hypervisor '%s' does not " "support selecting CPU models") % CONF.libvirt.virt_type raise exception.Invalid(msg) if mode == "custom" and model is None: msg = _("Config requested a custom CPU model, but no " "model name was provided") raise exception.Invalid(msg) elif mode != "custom" and model is not None: msg = _("A CPU model name should not be set when a " "host CPU model is requested") raise exception.Invalid(msg) LOG.debug("CPU mode '%(mode)s' model '%(model)s' was chosen", {'mode': mode, 'model': (model or "")}) cpu = vconfig.LibvirtConfigGuestCPU() cpu.mode = mode cpu.model = model return cpu def _get_guest_cpu_config(self, flavor, image_meta, guest_cpu_numa_config, instance_numa_topology): cpu = self._get_guest_cpu_model_config() if cpu is None: return None topology = hardware.get_best_cpu_topology( flavor, image_meta, numa_topology=instance_numa_topology) cpu.sockets = topology.sockets cpu.cores = topology.cores cpu.threads = topology.threads cpu.numa = guest_cpu_numa_config return cpu def _get_guest_disk_config(self, instance, name, disk_mapping, inst_type, image_type=None): if CONF.libvirt.hw_disk_discard: if not self._host.has_min_version(hv_ver=MIN_QEMU_DISCARD_VERSION, hv_type=host.HV_DRIVER_QEMU): msg = (_('Volume sets discard option, qemu %(qemu)s' ' or later is required.') % {'qemu': MIN_QEMU_DISCARD_VERSION}) raise exception.Invalid(msg) image = self.image_backend.image(instance, name, image_type) if (name == 'disk.config' and image_type == 'rbd' and not image.exists()): # This is likely an older config drive that has not been migrated # to rbd yet. Try to fall back on 'flat' image type. # TODO(melwitt): Add online migration of some sort so we can # remove this fall back once we know all config drives are in rbd. # NOTE(vladikr): make sure that the flat image exist, otherwise # the image will be created after the domain definition. flat_image = self.image_backend.image(instance, name, 'flat') if flat_image.exists(): image = flat_image LOG.debug('Config drive not found in RBD, falling back to the ' 'instance directory', instance=instance) disk_info = disk_mapping[name] return image.libvirt_info(disk_info['bus'], disk_info['dev'], disk_info['type'], self.disk_cachemode, inst_type['extra_specs'], self._host.get_version()) def _get_guest_fs_config(self, instance, name, image_type=None): image = self.image_backend.image(instance, name, image_type) return image.libvirt_fs_info("/", "ploop") def _get_guest_storage_config(self, instance, image_meta, disk_info, rescue, block_device_info, inst_type, os_type): devices = [] disk_mapping = disk_info['mapping'] block_device_mapping = driver.block_device_info_get_mapping( block_device_info) mount_rootfs = CONF.libvirt.virt_type == "lxc" if mount_rootfs: fs = vconfig.LibvirtConfigGuestFilesys() fs.source_type = "mount" fs.source_dir = os.path.join( libvirt_utils.get_instance_path(instance), 'rootfs') devices.append(fs) elif os_type == vm_mode.EXE and CONF.libvirt.virt_type == "parallels": if rescue: fsrescue = self._get_guest_fs_config(instance, "disk.rescue") devices.append(fsrescue) fsos = self._get_guest_fs_config(instance, "disk") fsos.target_dir = "/mnt/rescue" devices.append(fsos) else: if 'disk' in disk_mapping: fs = self._get_guest_fs_config(instance, "disk") devices.append(fs) else: if rescue: diskrescue = self._get_guest_disk_config(instance, 'disk.rescue', disk_mapping, inst_type) devices.append(diskrescue) diskos = self._get_guest_disk_config(instance, 'disk', disk_mapping, inst_type) devices.append(diskos) else: if 'disk' in disk_mapping: diskos = self._get_guest_disk_config(instance, 'disk', disk_mapping, inst_type) devices.append(diskos) if 'disk.local' in disk_mapping: disklocal = self._get_guest_disk_config(instance, 'disk.local', disk_mapping, inst_type) devices.append(disklocal) instance.default_ephemeral_device = ( block_device.prepend_dev(disklocal.target_dev)) for idx, eph in enumerate( driver.block_device_info_get_ephemerals( block_device_info)): diskeph = self._get_guest_disk_config( instance, blockinfo.get_eph_disk(idx), disk_mapping, inst_type) devices.append(diskeph) if 'disk.swap' in disk_mapping: diskswap = self._get_guest_disk_config(instance, 'disk.swap', disk_mapping, inst_type) devices.append(diskswap) instance.default_swap_device = ( block_device.prepend_dev(diskswap.target_dev)) if 'disk.config' in disk_mapping: diskconfig = self._get_guest_disk_config( instance, 'disk.config', disk_mapping, inst_type, self._get_disk_config_image_type()) devices.append(diskconfig) for vol in block_device.get_bdms_to_connect(block_device_mapping, mount_rootfs): connection_info = vol['connection_info'] vol_dev = block_device.prepend_dev(vol['mount_device']) info = disk_mapping[vol_dev] self._connect_volume(connection_info, info) cfg = self._get_volume_config(connection_info, info) devices.append(cfg) vol['connection_info'] = connection_info vol.save() for d in devices: self._set_cache_mode(d) if image_meta.properties.get('hw_scsi_model'): hw_scsi_model = image_meta.properties.hw_scsi_model scsi_controller = vconfig.LibvirtConfigGuestController() scsi_controller.type = 'scsi' scsi_controller.model = hw_scsi_model devices.append(scsi_controller) return devices def _get_host_sysinfo_serial_hardware(self): """Get a UUID from the host hardware Get a UUID for the host hardware reported by libvirt. This is typically from the SMBIOS data, unless it has been overridden in /etc/libvirt/libvirtd.conf """ caps = self._host.get_capabilities() return caps.host.uuid def _get_host_sysinfo_serial_os(self): """Get a UUID from the host operating system Get a UUID for the host operating system. Modern Linux distros based on systemd provide a /etc/machine-id file containing a UUID. This is also provided inside systemd based containers and can be provided by other init systems too, since it is just a plain text file. """ if not os.path.exists("/etc/machine-id"): msg = _("Unable to get host UUID: /etc/machine-id does not exist") raise exception.NovaException(msg) with open("/etc/machine-id") as f: # We want to have '-' in the right place # so we parse & reformat the value lines = f.read().split() if not lines: msg = _("Unable to get host UUID: /etc/machine-id is empty") raise exception.NovaException(msg) return str(uuid.UUID(lines[0])) def _get_host_sysinfo_serial_auto(self): if os.path.exists("/etc/machine-id"): return self._get_host_sysinfo_serial_os() else: return self._get_host_sysinfo_serial_hardware() def _get_guest_config_sysinfo(self, instance): sysinfo = vconfig.LibvirtConfigGuestSysinfo() sysinfo.system_manufacturer = version.vendor_string() sysinfo.system_product = version.product_string() sysinfo.system_version = version.version_string_with_package() sysinfo.system_serial = self._sysinfo_serial_func() sysinfo.system_uuid = instance.uuid sysinfo.system_family = "Virtual Machine" return sysinfo def _get_guest_pci_device(self, pci_device): dbsf = pci_utils.parse_address(pci_device.address) dev = vconfig.LibvirtConfigGuestHostdevPCI() dev.domain, dev.bus, dev.slot, dev.function = dbsf # only kvm support managed mode if CONF.libvirt.virt_type in ('xen', 'parallels',): dev.managed = 'no' if CONF.libvirt.virt_type in ('kvm', 'qemu'): dev.managed = 'yes' return dev def _get_guest_config_meta(self, context, instance): """Get metadata config for guest.""" meta = vconfig.LibvirtConfigGuestMetaNovaInstance() meta.package = version.version_string_with_package() meta.name = instance.display_name meta.creationTime = time.time() if instance.image_ref not in ("", None): meta.roottype = "image" meta.rootid = instance.image_ref if context is not None: ometa = vconfig.LibvirtConfigGuestMetaNovaOwner() ometa.userid = context.user_id ometa.username = context.user_name ometa.projectid = context.project_id ometa.projectname = context.project_name meta.owner = ometa fmeta = vconfig.LibvirtConfigGuestMetaNovaFlavor() flavor = instance.flavor fmeta.name = flavor.name fmeta.memory = flavor.memory_mb fmeta.vcpus = flavor.vcpus fmeta.ephemeral = flavor.ephemeral_gb fmeta.disk = flavor.root_gb fmeta.swap = flavor.swap meta.flavor = fmeta return meta def _machine_type_mappings(self): mappings = {} for mapping in CONF.libvirt.hw_machine_type: host_arch, _, machine_type = mapping.partition('=') mappings[host_arch] = machine_type return mappings def _get_machine_type(self, image_meta, caps): # The underlying machine type can be set as an image attribute, # or otherwise based on some architecture specific defaults mach_type = None if image_meta.properties.get('hw_machine_type') is not None: mach_type = image_meta.properties.hw_machine_type else: # For ARM systems we will default to vexpress-a15 for armv7 # and virt for aarch64 if caps.host.cpu.arch == arch.ARMV7: mach_type = "vexpress-a15" if caps.host.cpu.arch == arch.AARCH64: mach_type = "virt" if caps.host.cpu.arch in (arch.S390, arch.S390X): mach_type = 's390-ccw-virtio' # If set in the config, use that as the default. if CONF.libvirt.hw_machine_type: mappings = self._machine_type_mappings() mach_type = mappings.get(caps.host.cpu.arch) return mach_type @staticmethod def _create_idmaps(klass, map_strings): idmaps = [] if len(map_strings) > 5: map_strings = map_strings[0:5] LOG.warning(_LW("Too many id maps, only included first five.")) for map_string in map_strings: try: idmap = klass() values = [int(i) for i in map_string.split(":")] idmap.start = values[0] idmap.target = values[1] idmap.count = values[2] idmaps.append(idmap) except (ValueError, IndexError): LOG.warning(_LW("Invalid value for id mapping %s"), map_string) return idmaps def _get_guest_idmaps(self): id_maps = [] if CONF.libvirt.virt_type == 'lxc' and CONF.libvirt.uid_maps: uid_maps = self._create_idmaps(vconfig.LibvirtConfigGuestUIDMap, CONF.libvirt.uid_maps) id_maps.extend(uid_maps) if CONF.libvirt.virt_type == 'lxc' and CONF.libvirt.gid_maps: gid_maps = self._create_idmaps(vconfig.LibvirtConfigGuestGIDMap, CONF.libvirt.gid_maps) id_maps.extend(gid_maps) return id_maps def _update_guest_cputune(self, guest, flavor, virt_type): is_able = self._host.is_cpu_control_policy_capable() cputuning = ['shares', 'period', 'quota'] wants_cputune = any([k for k in cputuning if "quota:cpu_" + k in flavor.extra_specs.keys()]) if wants_cputune and not is_able: raise exception.UnsupportedHostCPUControlPolicy() if not is_able or virt_type not in ('lxc', 'kvm', 'qemu'): return if guest.cputune is None: guest.cputune = vconfig.LibvirtConfigGuestCPUTune() # Setting the default cpu.shares value to be a value # dependent on the number of vcpus guest.cputune.shares = 1024 * guest.vcpus for name in cputuning: key = "quota:cpu_" + name if key in flavor.extra_specs: setattr(guest.cputune, name, int(flavor.extra_specs[key])) def _get_cpu_numa_config_from_instance(self, instance_numa_topology, wants_hugepages): if instance_numa_topology: guest_cpu_numa = vconfig.LibvirtConfigGuestCPUNUMA() for instance_cell in instance_numa_topology.cells: guest_cell = vconfig.LibvirtConfigGuestCPUNUMACell() guest_cell.id = instance_cell.id guest_cell.cpus = instance_cell.cpuset guest_cell.memory = instance_cell.memory * units.Ki # The vhost-user network backend requires file backed # guest memory (ie huge pages) to be marked as shared # access, not private, so an external process can read # and write the pages. # # You can't change the shared vs private flag for an # already running guest, and since we can't predict what # types of NIC may be hotplugged, we have no choice but # to unconditionally turn on the shared flag. This has # no real negative functional effect on the guest, so # is a reasonable approach to take if wants_hugepages: guest_cell.memAccess = "shared" guest_cpu_numa.cells.append(guest_cell) return guest_cpu_numa def _has_cpu_policy_support(self): for ver in BAD_LIBVIRT_CPU_POLICY_VERSIONS: if self._host.has_version(ver): ver_ = self._version_to_string(ver) raise exception.CPUPinningNotSupported(reason=_( 'Invalid libvirt version %(version)s') % {'version': ver_}) return True def _wants_hugepages(self, host_topology, instance_topology): """Determine if the guest / host topology implies the use of huge pages for guest RAM backing """ if host_topology is None or instance_topology is None: return False avail_pagesize = [page.size_kb for page in host_topology.cells[0].mempages] avail_pagesize.sort() # Remove smallest page size as that's not classed as a largepage avail_pagesize = avail_pagesize[1:] # See if we have page size set for cell in instance_topology.cells: if (cell.pagesize is not None and cell.pagesize in avail_pagesize): return True return False def _get_guest_numa_config(self, instance_numa_topology, flavor, allowed_cpus=None, image_meta=None): """Returns the config objects for the guest NUMA specs. Determines the CPUs that the guest can be pinned to if the guest specifies a cell topology and the host supports it. Constructs the libvirt XML config object representing the NUMA topology selected for the guest. Returns a tuple of: (cpu_set, guest_cpu_tune, guest_cpu_numa, guest_numa_tune) With the following caveats: a) If there is no specified guest NUMA topology, then all tuple elements except cpu_set shall be None. cpu_set will be populated with the chosen CPUs that the guest allowed CPUs fit within, which could be the supplied allowed_cpus value if the host doesn't support NUMA topologies. b) If there is a specified guest NUMA topology, then cpu_set will be None and guest_cpu_numa will be the LibvirtConfigGuestCPUNUMA object representing the guest's NUMA topology. If the host supports NUMA, then guest_cpu_tune will contain a LibvirtConfigGuestCPUTune object representing the optimized chosen cells that match the host capabilities with the instance's requested topology. If the host does not support NUMA, then guest_cpu_tune and guest_numa_tune will be None. """ if (not self._has_numa_support() and instance_numa_topology is not None): # We should not get here, since we should have avoided # reporting NUMA topology from _get_host_numa_topology # in the first place. Just in case of a scheduler # mess up though, raise an exception raise exception.NUMATopologyUnsupported() topology = self._get_host_numa_topology() # We have instance NUMA so translate it to the config class guest_cpu_numa_config = self._get_cpu_numa_config_from_instance( instance_numa_topology, self._wants_hugepages(topology, instance_numa_topology)) if not guest_cpu_numa_config: # No NUMA topology defined for instance - let the host kernel deal # with the NUMA effects. # TODO(ndipanov): Attempt to spread the instance # across NUMA nodes and expose the topology to the # instance as an optimisation return GuestNumaConfig(allowed_cpus, None, None, None) else: if topology: # Now get the CpuTune configuration from the numa_topology guest_cpu_tune = vconfig.LibvirtConfigGuestCPUTune() guest_numa_tune = vconfig.LibvirtConfigGuestNUMATune() allpcpus = [] numa_mem = vconfig.LibvirtConfigGuestNUMATuneMemory() numa_memnodes = [vconfig.LibvirtConfigGuestNUMATuneMemNode() for _ in guest_cpu_numa_config.cells] for host_cell in topology.cells: for guest_node_id, guest_config_cell in enumerate( guest_cpu_numa_config.cells): if guest_config_cell.id == host_cell.id: node = numa_memnodes[guest_node_id] node.cellid = guest_node_id node.nodeset = [host_cell.id] node.mode = "strict" numa_mem.nodeset.append(host_cell.id) object_numa_cell = ( instance_numa_topology.cells[guest_node_id] ) for cpu in guest_config_cell.cpus: pin_cpuset = ( vconfig.LibvirtConfigGuestCPUTuneVCPUPin()) pin_cpuset.id = cpu # If there is pinning information in the cell # we pin to individual CPUs, otherwise we float # over the whole host NUMA node if (object_numa_cell.cpu_pinning and self._has_cpu_policy_support()): pcpu = object_numa_cell.cpu_pinning[cpu] pin_cpuset.cpuset = set([pcpu]) else: pin_cpuset.cpuset = host_cell.cpuset allpcpus.extend(pin_cpuset.cpuset) guest_cpu_tune.vcpupin.append(pin_cpuset) # TODO(berrange) When the guest has >1 NUMA node, it will # span multiple host NUMA nodes. By pinning emulator threads # to the union of all nodes, we guarantee there will be # cross-node memory access by the emulator threads when # responding to guest I/O operations. The only way to avoid # this would be to pin emulator threads to a single node and # tell the guest OS to only do I/O from one of its virtual # NUMA nodes. This is not even remotely practical. # # The long term solution is to make use of a new QEMU feature # called "I/O Threads" which will let us configure an explicit # I/O thread for each guest vCPU or guest NUMA node. It is # still TBD how to make use of this feature though, especially # how to associate IO threads with guest devices to eliminiate # cross NUMA node traffic. This is an area of investigation # for QEMU community devs. emulatorpin = vconfig.LibvirtConfigGuestCPUTuneEmulatorPin() emulatorpin.cpuset = set(allpcpus) guest_cpu_tune.emulatorpin = emulatorpin # Sort the vcpupin list per vCPU id for human-friendlier XML guest_cpu_tune.vcpupin.sort(key=operator.attrgetter("id")) if hardware.is_realtime_enabled(flavor): if not self._host.has_min_version( MIN_LIBVIRT_REALTIME_VERSION): raise exception.RealtimePolicyNotSupported() vcpus_rt, vcpus_em = hardware.vcpus_realtime_topology( set(cpu.id for cpu in guest_cpu_tune.vcpupin), flavor, image_meta) vcpusched = vconfig.LibvirtConfigGuestCPUTuneVCPUSched() vcpusched.vcpus = vcpus_rt vcpusched.scheduler = "fifo" vcpusched.priority = ( CONF.libvirt.realtime_scheduler_priority) guest_cpu_tune.vcpusched.append(vcpusched) guest_cpu_tune.emulatorpin.cpuset = vcpus_em guest_numa_tune.memory = numa_mem guest_numa_tune.memnodes = numa_memnodes # normalize cell.id for i, (cell, memnode) in enumerate( zip(guest_cpu_numa_config.cells, guest_numa_tune.memnodes)): cell.id = i memnode.cellid = i return GuestNumaConfig(None, guest_cpu_tune, guest_cpu_numa_config, guest_numa_tune) else: return GuestNumaConfig(allowed_cpus, None, guest_cpu_numa_config, None) def _get_guest_os_type(self, virt_type): """Returns the guest OS type based on virt type.""" if virt_type == "lxc": ret = vm_mode.EXE elif virt_type == "uml": ret = vm_mode.UML elif virt_type == "xen": ret = vm_mode.XEN else: ret = vm_mode.HVM return ret def _set_guest_for_rescue(self, rescue, guest, inst_path, virt_type, root_device_name): if rescue.get('kernel_id'): guest.os_kernel = os.path.join(inst_path, "kernel.rescue") if virt_type == "xen": guest.os_cmdline = "ro root=%s" % root_device_name else: guest.os_cmdline = ("root=%s %s" % (root_device_name, CONSOLE)) if virt_type == "qemu": guest.os_cmdline += " no_timer_check" if rescue.get('ramdisk_id'): guest.os_initrd = os.path.join(inst_path, "ramdisk.rescue") def _set_guest_for_inst_kernel(self, instance, guest, inst_path, virt_type, root_device_name, image_meta): guest.os_kernel = os.path.join(inst_path, "kernel") if virt_type == "xen": guest.os_cmdline = "ro root=%s" % root_device_name else: guest.os_cmdline = ("root=%s %s" % (root_device_name, CONSOLE)) if virt_type == "qemu": guest.os_cmdline += " no_timer_check" if instance.ramdisk_id: guest.os_initrd = os.path.join(inst_path, "ramdisk") # we only support os_command_line with images with an explicit # kernel set and don't want to break nova if there's an # os_command_line property without a specified kernel_id param if image_meta.properties.get("os_command_line"): guest.os_cmdline = image_meta.properties.os_command_line def _set_clock(self, guest, os_type, image_meta, virt_type): # NOTE(mikal): Microsoft Windows expects the clock to be in # "localtime". If the clock is set to UTC, then you can use a # registry key to let windows know, but Microsoft says this is # buggy in http://support.microsoft.com/kb/2687252 clk = vconfig.LibvirtConfigGuestClock() if os_type == 'windows': LOG.info(_LI('Configuring timezone for windows instance to ' 'localtime')) clk.offset = 'localtime' else: clk.offset = 'utc' guest.set_clock(clk) if virt_type == "kvm": self._set_kvm_timers(clk, os_type, image_meta) def _set_kvm_timers(self, clk, os_type, image_meta): # TODO(berrange) One day this should be per-guest # OS type configurable tmpit = vconfig.LibvirtConfigGuestTimer() tmpit.name = "pit" tmpit.tickpolicy = "delay" tmrtc = vconfig.LibvirtConfigGuestTimer() tmrtc.name = "rtc" tmrtc.tickpolicy = "catchup" clk.add_timer(tmpit) clk.add_timer(tmrtc) guestarch = libvirt_utils.get_arch(image_meta) if guestarch in (arch.I686, arch.X86_64): # NOTE(rfolco): HPET is a hardware timer for x86 arch. # qemu -no-hpet is not supported on non-x86 targets. tmhpet = vconfig.LibvirtConfigGuestTimer() tmhpet.name = "hpet" tmhpet.present = False clk.add_timer(tmhpet) # With new enough QEMU we can provide Windows guests # with the paravirtualized hyperv timer source. This # is the windows equiv of kvm-clock, allowing Windows # guests to accurately keep time. if (os_type == 'windows' and self._host.has_min_version(MIN_LIBVIRT_HYPERV_TIMER_VERSION, MIN_QEMU_HYPERV_TIMER_VERSION)): tmhyperv = vconfig.LibvirtConfigGuestTimer() tmhyperv.name = "hypervclock" tmhyperv.present = True clk.add_timer(tmhyperv) def _set_features(self, guest, os_type, caps, virt_type): if virt_type == "xen": # PAE only makes sense in X86 if caps.host.cpu.arch in (arch.I686, arch.X86_64): guest.features.append(vconfig.LibvirtConfigGuestFeaturePAE()) if (virt_type not in ("lxc", "uml", "parallels", "xen") or (virt_type == "xen" and guest.os_type == vm_mode.HVM)): guest.features.append(vconfig.LibvirtConfigGuestFeatureACPI()) guest.features.append(vconfig.LibvirtConfigGuestFeatureAPIC()) if (virt_type in ("qemu", "kvm") and os_type == 'windows'): hv = vconfig.LibvirtConfigGuestFeatureHyperV() hv.relaxed = True hv.spinlocks = True # Increase spinlock retries - value recommended by # KVM maintainers who certify Windows guests # with Microsoft hv.spinlock_retries = 8191 hv.vapic = True guest.features.append(hv) def _check_number_of_serial_console(self, num_ports): virt_type = CONF.libvirt.virt_type if (virt_type in ("kvm", "qemu") and num_ports > ALLOWED_QEMU_SERIAL_PORTS): raise exception.SerialPortNumberLimitExceeded( allowed=ALLOWED_QEMU_SERIAL_PORTS, virt_type=virt_type) def _create_serial_console_devices(self, guest, instance, flavor, image_meta): guest_arch = libvirt_utils.get_arch(image_meta) if CONF.serial_console.enabled: num_ports = hardware.get_number_of_serial_ports( flavor, image_meta) if guest_arch in (arch.S390, arch.S390X): console_cls = vconfig.LibvirtConfigGuestConsole else: console_cls = vconfig.LibvirtConfigGuestSerial self._check_number_of_serial_console(num_ports) for port in six.moves.range(num_ports): console = console_cls() console.port = port console.type = "tcp" console.listen_host = ( CONF.serial_console.proxyclient_address) console.listen_port = ( serial_console.acquire_port( console.listen_host)) guest.add_device(console) else: # The QEMU 'pty' driver throws away any data if no # client app is connected. Thus we can't get away # with a single type=pty console. Instead we have # to configure two separate consoles. if guest_arch in (arch.S390, arch.S390X): consolelog = vconfig.LibvirtConfigGuestConsole() consolelog.target_type = "sclplm" else: consolelog = vconfig.LibvirtConfigGuestSerial() consolelog.type = "file" consolelog.source_path = self._get_console_log_path(instance) guest.add_device(consolelog) def _add_video_driver(self, guest, image_meta, flavor): VALID_VIDEO_DEVICES = ("vga", "cirrus", "vmvga", "xen", "qxl") video = vconfig.LibvirtConfigGuestVideo() # NOTE(ldbragst): The following logic sets the video.type # depending on supported defaults given the architecture, # virtualization type, and features. The video.type attribute can # be overridden by the user with image_meta.properties, which # is carried out in the next if statement below this one. guestarch = libvirt_utils.get_arch(image_meta) if guest.os_type == vm_mode.XEN: video.type = 'xen' elif CONF.libvirt.virt_type == 'parallels': video.type = 'vga' elif guestarch in (arch.PPC, arch.PPC64, arch.PPC64LE): # NOTE(ldbragst): PowerKVM doesn't support 'cirrus' be default # so use 'vga' instead when running on Power hardware. video.type = 'vga' elif CONF.spice.enabled: video.type = 'qxl' if image_meta.properties.get('hw_video_model'): video.type = image_meta.properties.hw_video_model if (video.type not in VALID_VIDEO_DEVICES): raise exception.InvalidVideoMode(model=video.type) # Set video memory, only if the flavor's limit is set video_ram = image_meta.properties.get('hw_video_ram', 0) max_vram = int(flavor.extra_specs.get('hw_video:ram_max_mb', 0)) if video_ram > max_vram: raise exception.RequestedVRamTooHigh(req_vram=video_ram, max_vram=max_vram) if max_vram and video_ram: video.vram = video_ram * units.Mi / units.Ki guest.add_device(video) def _add_qga_device(self, guest, instance): qga = vconfig.LibvirtConfigGuestChannel() qga.type = "unix" qga.target_name = "org.qemu.guest_agent.0" qga.source_path = ("/var/lib/libvirt/qemu/%s.%s.sock" % ("org.qemu.guest_agent.0", instance.name)) guest.add_device(qga) def _add_rng_device(self, guest, flavor): rng_device = vconfig.LibvirtConfigGuestRng() rate_bytes = flavor.extra_specs.get('hw_rng:rate_bytes', 0) period = flavor.extra_specs.get('hw_rng:rate_period', 0) if rate_bytes: rng_device.rate_bytes = int(rate_bytes) rng_device.rate_period = int(period) rng_path = CONF.libvirt.rng_dev_path if (rng_path and not os.path.exists(rng_path)): raise exception.RngDeviceNotExist(path=rng_path) rng_device.backend = rng_path guest.add_device(rng_device) def _set_qemu_guest_agent(self, guest, flavor, instance, image_meta): # Enable qga only if the 'hw_qemu_guest_agent' is equal to yes if image_meta.properties.get('hw_qemu_guest_agent', False): LOG.debug("Qemu guest agent is enabled through image " "metadata", instance=instance) self._add_qga_device(guest, instance) rng_is_virtio = image_meta.properties.get('hw_rng_model') == 'virtio' rng_allowed_str = flavor.extra_specs.get('hw_rng:allowed', '') rng_allowed = strutils.bool_from_string(rng_allowed_str) if rng_is_virtio and rng_allowed: self._add_rng_device(guest, flavor) def _get_guest_memory_backing_config( self, inst_topology, numatune, flavor): wantsmempages = False if inst_topology: for cell in inst_topology.cells: if cell.pagesize: wantsmempages = True break wantsrealtime = hardware.is_realtime_enabled(flavor) membacking = None if wantsmempages: pages = self._get_memory_backing_hugepages_support( inst_topology, numatune) if pages: membacking = vconfig.LibvirtConfigGuestMemoryBacking() membacking.hugepages = pages if wantsrealtime: if not membacking: membacking = vconfig.LibvirtConfigGuestMemoryBacking() membacking.locked = True membacking.sharedpages = False return membacking def _get_memory_backing_hugepages_support(self, inst_topology, numatune): if not self._has_hugepage_support(): # We should not get here, since we should have avoided # reporting NUMA topology from _get_host_numa_topology # in the first place. Just in case of a scheduler # mess up though, raise an exception raise exception.MemoryPagesUnsupported() host_topology = self._get_host_numa_topology() if host_topology is None: # As above, we should not get here but just in case... raise exception.MemoryPagesUnsupported() # Currently libvirt does not support the smallest # pagesize set as a backend memory. # https://bugzilla.redhat.com/show_bug.cgi?id=1173507 avail_pagesize = [page.size_kb for page in host_topology.cells[0].mempages] avail_pagesize.sort() smallest = avail_pagesize[0] pages = [] for guest_cellid, inst_cell in enumerate(inst_topology.cells): if inst_cell.pagesize and inst_cell.pagesize > smallest: for memnode in numatune.memnodes: if guest_cellid == memnode.cellid: page = ( vconfig.LibvirtConfigGuestMemoryBackingPage()) page.nodeset = [guest_cellid] page.size_kb = inst_cell.pagesize pages.append(page) break # Quit early... return pages def _get_flavor(self, ctxt, instance, flavor): if flavor is not None: return flavor return instance.flavor def _has_uefi_support(self): # This means that the host can support uefi booting for guests supported_archs = [arch.X86_64, arch.AARCH64] caps = self._host.get_capabilities() return ((caps.host.cpu.arch in supported_archs) and self._host.has_min_version(MIN_LIBVIRT_UEFI_VERSION) and os.path.exists(DEFAULT_UEFI_LOADER_PATH[caps.host.cpu.arch])) def _get_supported_perf_events(self): if (len(CONF.libvirt.enabled_perf_events) == 0 or not self._host.has_min_version(MIN_LIBVIRT_PERF_VERSION)): return [] supported_events = [] host_cpu_info = self._get_cpu_info() for event in CONF.libvirt.enabled_perf_events: if self._supported_perf_event(event, host_cpu_info['features']): supported_events.append(event) return supported_events def _supported_perf_event(self, event, cpu_features): libvirt_perf_event_name = LIBVIRT_PERF_EVENT_PREFIX + event.upper() if not hasattr(libvirt, libvirt_perf_event_name): LOG.warning(_LW("Libvirt doesn't support event type %s."), event) return False if (event in PERF_EVENTS_CPU_FLAG_MAPPING and PERF_EVENTS_CPU_FLAG_MAPPING[event] not in cpu_features): LOG.warning(_LW("Host does not support event type %s."), event) return False return True def _configure_guest_by_virt_type(self, guest, virt_type, caps, instance, image_meta, flavor, root_device_name): if virt_type == "xen": if guest.os_type == vm_mode.HVM: guest.os_loader = CONF.libvirt.xen_hvmloader_path elif virt_type in ("kvm", "qemu"): if caps.host.cpu.arch in (arch.I686, arch.X86_64): guest.sysinfo = self._get_guest_config_sysinfo(instance) guest.os_smbios = vconfig.LibvirtConfigGuestSMBIOS() hw_firmware_type = image_meta.properties.get('hw_firmware_type') if hw_firmware_type == fields.FirmwareType.UEFI: if self._has_uefi_support(): global uefi_logged if not uefi_logged: LOG.warning(_LW("uefi support is without some kind of " "functional testing and therefore " "considered experimental.")) uefi_logged = True guest.os_loader = DEFAULT_UEFI_LOADER_PATH[ caps.host.cpu.arch] guest.os_loader_type = "pflash" else: raise exception.UEFINotSupported() guest.os_mach_type = self._get_machine_type(image_meta, caps) if image_meta.properties.get('hw_boot_menu') is None: guest.os_bootmenu = strutils.bool_from_string( flavor.extra_specs.get('hw:boot_menu', 'no')) else: guest.os_bootmenu = image_meta.properties.hw_boot_menu elif virt_type == "lxc": guest.os_init_path = "/sbin/init" guest.os_cmdline = CONSOLE elif virt_type == "uml": guest.os_kernel = "/usr/bin/linux" guest.os_root = root_device_name elif virt_type == "parallels": if guest.os_type == vm_mode.EXE: guest.os_init_path = "/sbin/init" def _conf_non_lxc_uml(self, virt_type, guest, root_device_name, rescue, instance, inst_path, image_meta, disk_info): if rescue: self._set_guest_for_rescue(rescue, guest, inst_path, virt_type, root_device_name) elif instance.kernel_id: self._set_guest_for_inst_kernel(instance, guest, inst_path, virt_type, root_device_name, image_meta) else: guest.os_boot_dev = blockinfo.get_boot_order(disk_info) def _create_consoles(self, virt_type, guest, instance, flavor, image_meta, caps): if virt_type in ("qemu", "kvm"): # Create the serial console char devices self._create_serial_console_devices(guest, instance, flavor, image_meta) if caps.host.cpu.arch in (arch.S390, arch.S390X): consolepty = vconfig.LibvirtConfigGuestConsole() consolepty.target_type = "sclp" else: consolepty = vconfig.LibvirtConfigGuestSerial() else: consolepty = vconfig.LibvirtConfigGuestConsole() return consolepty def _cpu_config_to_vcpu_model(self, cpu_config, vcpu_model): """Update VirtCPUModel object according to libvirt CPU config. :param:cpu_config: vconfig.LibvirtConfigGuestCPU presenting the instance's virtual cpu configuration. :param:vcpu_model: VirtCPUModel object. A new object will be created if None. :return: Updated VirtCPUModel object, or None if cpu_config is None """ if not cpu_config: return if not vcpu_model: vcpu_model = objects.VirtCPUModel() vcpu_model.arch = cpu_config.arch vcpu_model.vendor = cpu_config.vendor vcpu_model.model = cpu_config.model vcpu_model.mode = cpu_config.mode vcpu_model.match = cpu_config.match if cpu_config.sockets: vcpu_model.topology = objects.VirtCPUTopology( sockets=cpu_config.sockets, cores=cpu_config.cores, threads=cpu_config.threads) else: vcpu_model.topology = None features = [objects.VirtCPUFeature( name=f.name, policy=f.policy) for f in cpu_config.features] vcpu_model.features = features return vcpu_model def _vcpu_model_to_cpu_config(self, vcpu_model): """Create libvirt CPU config according to VirtCPUModel object. :param:vcpu_model: VirtCPUModel object. :return: vconfig.LibvirtConfigGuestCPU. """ cpu_config = vconfig.LibvirtConfigGuestCPU() cpu_config.arch = vcpu_model.arch cpu_config.model = vcpu_model.model cpu_config.mode = vcpu_model.mode cpu_config.match = vcpu_model.match cpu_config.vendor = vcpu_model.vendor if vcpu_model.topology: cpu_config.sockets = vcpu_model.topology.sockets cpu_config.cores = vcpu_model.topology.cores cpu_config.threads = vcpu_model.topology.threads if vcpu_model.features: for f in vcpu_model.features: xf = vconfig.LibvirtConfigGuestCPUFeature() xf.name = f.name xf.policy = f.policy cpu_config.features.add(xf) return cpu_config def _get_guest_config(self, instance, network_info, image_meta, disk_info, rescue=None, block_device_info=None, context=None): """Get config data for parameters. :param rescue: optional dictionary that should contain the key 'ramdisk_id' if a ramdisk is needed for the rescue image and 'kernel_id' if a kernel is needed for the rescue image. """ LOG.warn("_get_guest_config.............instance:%s" % instance) flavor = instance.flavor inst_path = libvirt_utils.get_instance_path(instance) disk_mapping = disk_info['mapping'] virt_type = CONF.libvirt.virt_type guest = vconfig.LibvirtConfigGuest() LOG.warn("guest----------------------%s" % guest) guest.virt_type = virt_type guest.name = instance.name guest.uuid = instance.uuid # We are using default unit for memory: KiB guest.memory = flavor.memory_mb * units.Ki guest.vcpus = flavor.vcpus allowed_cpus = hardware.get_vcpu_pin_set() pci_devs = pci_manager.get_instance_pci_devs(instance, 'all') guest_numa_config = self._get_guest_numa_config( instance.numa_topology, flavor, allowed_cpus, image_meta) guest.cpuset = guest_numa_config.cpuset guest.cputune = guest_numa_config.cputune guest.numatune = guest_numa_config.numatune guest.membacking = self._get_guest_memory_backing_config( instance.numa_topology, guest_numa_config.numatune, flavor) guest.metadata.append(self._get_guest_config_meta(context, instance)) guest.idmaps = self._get_guest_idmaps() for event in self._supported_perf_events: guest.add_perf_event(event) self._update_guest_cputune(guest, flavor, virt_type) guest.cpu = self._get_guest_cpu_config( flavor, image_meta, guest_numa_config.numaconfig, instance.numa_topology) # Notes(yjiang5): we always sync the instance's vcpu model with # the corresponding config file. instance.vcpu_model = self._cpu_config_to_vcpu_model( guest.cpu, instance.vcpu_model) if 'root' in disk_mapping: root_device_name = block_device.prepend_dev( disk_mapping['root']['dev']) else: root_device_name = None if root_device_name: # NOTE(yamahata): # for nova.api.ec2.cloud.CloudController.get_metadata() instance.root_device_name = root_device_name guest.os_type = (vm_mode.get_from_instance(instance) or self._get_guest_os_type(virt_type)) caps = self._host.get_capabilities() self._configure_guest_by_virt_type(guest, virt_type, caps, instance, image_meta, flavor, root_device_name) if virt_type not in ('lxc', 'uml'): self._conf_non_lxc_uml(virt_type, guest, root_device_name, rescue, instance, inst_path, image_meta, disk_info) self._set_features(guest, instance.os_type, caps, virt_type) self._set_clock(guest, instance.os_type, image_meta, virt_type) storage_configs = self._get_guest_storage_config( instance, image_meta, disk_info, rescue, block_device_info, flavor, guest.os_type) for config in storage_configs: guest.add_device(config) #import pdb #pdb.set_trace() if self.has_cdrom(instance,disk_info) is None: cdrom = vconfig.LibvirtConfigGuestDisk() cdrom.source_type = 'file' cdrom.source_device = 'cdrom' cdrom.target_bus = 'ide' cdrom.target_dev = 'hdc' cdrom.driver_name = 'qemu' cdrom.driver_format = 'raw' def is_iso_image_active(context, fake_image_id): active_iso_images, flug = libvirt_utils.get_active_images(context, 'iso') if flug: fake_active_iso_images = [] for image in active_iso_images: fake_active_iso_images.append( hashlib.sha1(image).hexdigest()) if fake_image_id in fake_active_iso_images: return True else: return False else: return True try: #exist_cdroms = self._list_cdrom(instance) exist_cdroms = self.cdrom_list(instance) found_instance = True except: found_instance = False if found_instance: if exist_cdroms: image_id = exist_cdroms[0].get('image_id', '') if image_id: if not imagecache.iso_base_file_exists(image_id): image_id = '' if (image_id and not is_iso_image_active(context, image_id)): imagecache.remove_base_image(image_id) image_id = '' else: image_id = '' else: disk_format = getattr(image_meta, 'disk_format', '') if disk_format == 'iso': image_id = image_meta.get('id', '') if not image_id: image_id = image_meta['properties'].get('base_image_ref', '') if image_id: image_info = {} image_info['image_id'] = image_id image_id = imagecache.get_cache_fname(image_info, 'image_id') else: image_id = '' if image_id != '': base_url = self.image_cache_manager._get_base() image_url = os.path.join(base_url, image_id) else: image_url = '' cdrom.source_path = image_url guest.add_device(cdrom) for vif in network_info: config = self.vif_driver.get_config( instance, vif, image_meta, flavor, virt_type, self._host) guest.add_device(config) consolepty = self._create_consoles(virt_type, guest, instance, flavor, image_meta, caps) if virt_type != 'parallels': consolepty.type = "pty" guest.add_device(consolepty) pointer = self._get_guest_pointer_model(guest.os_type, image_meta) if pointer: guest.add_device(pointer) if (CONF.spice.enabled and CONF.spice.agent_enabled and virt_type not in ('lxc', 'uml', 'xen')): channel = vconfig.LibvirtConfigGuestChannel() channel.target_name = "com.redhat.spice.0" guest.add_device(channel) # NB some versions of libvirt support both SPICE and VNC # at the same time. We're not trying to second guess which # those versions are. We'll just let libvirt report the # errors appropriately if the user enables both. add_video_driver = False if ((CONF.vnc.enabled and virt_type not in ('lxc', 'uml'))): graphics = vconfig.LibvirtConfigGuestGraphics() graphics.type = "vnc" graphics.passwd = "%s" % instance.get("cipher", "00000") graphics.keymap = CONF.vnc.keymap graphics.listen = CONF.vnc.vncserver_listen guest.add_device(graphics) add_video_driver = True if (CONF.spice.enabled and virt_type not in ('lxc', 'uml', 'xen')): graphics = vconfig.LibvirtConfigGuestGraphics() graphics.type = "spice" graphics.passwd = "%s" % instance.get("cipher", "00000") graphics.keymap = CONF.spice.keymap graphics.listen = CONF.spice.server_listen guest.add_device(graphics) add_video_driver = True if add_video_driver: self._add_video_driver(guest, image_meta, flavor) # Qemu guest agent only support 'qemu' and 'kvm' hypervisor if virt_type in ('qemu', 'kvm'): self._set_qemu_guest_agent(guest, flavor, instance, image_meta) if virt_type in ('xen', 'qemu', 'kvm'): for pci_dev in pci_manager.get_instance_pci_devs(instance): guest.add_device(self._get_guest_pci_device(pci_dev)) else: if len(pci_devs) > 0: raise exception.PciDeviceUnsupportedHypervisor( type=virt_type) if 'hw_watchdog_action' in flavor.extra_specs: LOG.warning(_LW('Old property name "hw_watchdog_action" is now ' 'deprecated and will be removed in the next release. ' 'Use updated property name ' '"hw:watchdog_action" instead'), instance=instance) # TODO(pkholkin): accepting old property name 'hw_watchdog_action' # should be removed in the next release watchdog_action = (flavor.extra_specs.get('hw_watchdog_action') or flavor.extra_specs.get('hw:watchdog_action') or 'disabled') watchdog_action = image_meta.properties.get('hw_watchdog_action', watchdog_action) # NB(sross): currently only actually supported by KVM/QEmu if watchdog_action != 'disabled': if watchdog_actions.is_valid_watchdog_action(watchdog_action): bark = vconfig.LibvirtConfigGuestWatchdog() bark.action = watchdog_action guest.add_device(bark) else: raise exception.InvalidWatchdogAction(action=watchdog_action) # Memory balloon device only support 'qemu/kvm' and 'xen' hypervisor if (virt_type in ('xen', 'qemu', 'kvm') and CONF.libvirt.mem_stats_period_seconds > 0): balloon = vconfig.LibvirtConfigMemoryBalloon() if virt_type in ('qemu', 'kvm'): balloon.model = 'virtio' else: balloon.model = 'xen' balloon.period = CONF.libvirt.mem_stats_period_seconds guest.add_device(balloon) return guest def _get_guest_pointer_model(self, os_type, image_meta): pointer_model = image_meta.properties.get( 'hw_pointer_model', CONF.pointer_model) if pointer_model is None and CONF.libvirt.use_usb_tablet: # TODO(sahid): We set pointer_model to keep compatibility # until the next release O*. It means operators can continue # to use the deprecated option "use_usb_tablet" or set a # specific device to use pointer_model = "usbtablet" LOG.warning(_LW('The option "use_usb_tablet" has been ' 'deprecated for Newton in favor of the more ' 'generic "pointer_model". Please update ' 'nova.conf to address this change.')) if pointer_model == "usbtablet": # We want a tablet if VNC is enabled, or SPICE is enabled and # the SPICE agent is disabled. If the SPICE agent is enabled # it provides a paravirt mouse which drastically reduces # overhead (by eliminating USB polling). if CONF.vnc.enabled or ( CONF.spice.enabled and not CONF.spice.agent_enabled): return self._get_guest_usb_tablet(os_type) else: if CONF.pointer_model or CONF.libvirt.use_usb_tablet: # For backward compatibility We don't want to break # process of booting an instance if host is configured # to use USB tablet without VNC or SPICE and SPICE # agent disable. LOG.warning(_LW('USB tablet requested for guests by host ' 'configuration. In order to accept this ' 'request VNC should be enabled or SPICE ' 'and SPICE agent disabled on host.')) else: raise exception.UnsupportedPointerModelRequested( model="usbtablet") def _get_guest_usb_tablet(self, os_type): tablet = None if os_type == vm_mode.HVM: tablet = vconfig.LibvirtConfigGuestInput() tablet.type = "tablet" tablet.bus = "usb" else: if CONF.pointer_model or CONF.libvirt.use_usb_tablet: # For backward compatibility We don't want to break # process of booting an instance if virtual machine mode # is not configured as HVM. LOG.warning(_LW('USB tablet requested for guests by host ' 'configuration. In order to accept this ' 'request the machine mode should be ' 'configured as HVM.')) else: raise exception.UnsupportedPointerModelRequested( model="usbtablet") return tablet def _get_guest_xml(self, context, instance, network_info, disk_info, image_meta, rescue=None, block_device_info=None, write_to_disk=False): # NOTE(danms): Stringifying a NetworkInfo will take a lock. Do # this ahead of time so that we don't acquire it while also # holding the logging lock. network_info_str = str(network_info) msg = ('Start _get_guest_xml ' 'network_info=%(network_info)s ' 'disk_info=%(disk_info)s ' 'image_meta=%(image_meta)s rescue=%(rescue)s ' 'block_device_info=%(block_device_info)s' % {'network_info': network_info_str, 'disk_info': disk_info, 'image_meta': image_meta, 'rescue': rescue, 'block_device_info': block_device_info}) # NOTE(mriedem): block_device_info can contain auth_password so we # need to sanitize the password in the message. LOG.debug(strutils.mask_password(msg), instance=instance) conf = self._get_guest_config(instance, network_info, image_meta, disk_info, rescue, block_device_info, context) xml = conf.to_xml() if write_to_disk: instance_dir = libvirt_utils.get_instance_path(instance) xml_path = os.path.join(instance_dir, 'libvirt.xml') libvirt_utils.write_to_file(xml_path, xml) LOG.debug('End _get_guest_xml xml=%(xml)s', {'xml': xml}, instance=instance) return xml def get_info(self, instance): """Retrieve information from libvirt for a specific instance name. If a libvirt error is encountered during lookup, we might raise a NotFound exception or Error exception depending on how severe the libvirt error is. """ guest = self._host.get_guest(instance) # Kind of ugly but we need to pass host to get_info as for a # workaround, see libvirt/compat.py return guest.get_info(self._host) def _create_domain_setup_lxc(self, instance, image_meta, block_device_info, disk_info): inst_path = libvirt_utils.get_instance_path(instance) disk_info = disk_info or {} disk_mapping = disk_info.get('mapping', {}) if self._is_booted_from_volume(instance, disk_mapping): block_device_mapping = driver.block_device_info_get_mapping( block_device_info) root_disk = block_device.get_root_bdm(block_device_mapping) disk_info = blockinfo.get_info_from_bdm( instance, CONF.libvirt.virt_type, image_meta, root_disk) self._connect_volume(root_disk['connection_info'], disk_info) disk_path = root_disk['connection_info']['data']['device_path'] # NOTE(apmelton) - Even though the instance is being booted from a # cinder volume, it is still presented as a local block device. # LocalBlockImage is used here to indicate that the instance's # disk is backed by a local block device. image_model = imgmodel.LocalBlockImage(disk_path) else: image = self.image_backend.image(instance, 'disk') image_model = image.get_model(self._conn) container_dir = os.path.join(inst_path, 'rootfs') fileutils.ensure_tree(container_dir) rootfs_dev = disk_api.setup_container(image_model, container_dir=container_dir) try: # Save rootfs device to disconnect it when deleting the instance if rootfs_dev: instance.system_metadata['rootfs_device_name'] = rootfs_dev if CONF.libvirt.uid_maps or CONF.libvirt.gid_maps: id_maps = self._get_guest_idmaps() libvirt_utils.chown_for_id_maps(container_dir, id_maps) except Exception: with excutils.save_and_reraise_exception(): self._create_domain_cleanup_lxc(instance) def _create_domain_cleanup_lxc(self, instance): inst_path = libvirt_utils.get_instance_path(instance) container_dir = os.path.join(inst_path, 'rootfs') try: state = self.get_info(instance).state except exception.InstanceNotFound: # The domain may not be present if the instance failed to start state = None if state == power_state.RUNNING: # NOTE(uni): Now the container is running with its own private # mount namespace and so there is no need to keep the container # rootfs mounted in the host namespace LOG.debug('Attempting to unmount container filesystem: %s', container_dir, instance=instance) disk_api.clean_lxc_namespace(container_dir=container_dir) else: disk_api.teardown_container(container_dir=container_dir) @contextlib.contextmanager def _lxc_disk_handler(self, instance, image_meta, block_device_info, disk_info): """Context manager to handle the pre and post instance boot, LXC specific disk operations. An image or a volume path will be prepared and setup to be used by the container, prior to starting it. The disk will be disconnected and unmounted if a container has failed to start. """ if CONF.libvirt.virt_type != 'lxc': yield return self._create_domain_setup_lxc(instance, image_meta, block_device_info, disk_info) try: yield finally: self._create_domain_cleanup_lxc(instance) # TODO(sahid): Consider renaming this to _create_guest. def _create_domain(self, xml=None, domain=None, power_on=True, pause=False, post_xml_callback=None): """Create a domain. Either domain or xml must be passed in. If both are passed, then the domain definition is overwritten from the xml. :returns guest.Guest: Guest just created """ if xml: guest = libvirt_guest.Guest.create(xml, self._host) if post_xml_callback is not None: post_xml_callback() else: guest = libvirt_guest.Guest(domain) if power_on or pause: guest.launch(pause=pause) if not utils.is_neutron(): guest.enable_hairpin() return guest def _neutron_failed_callback(self, event_name, instance): LOG.error(_LE('Neutron Reported failure on event ' '%(event)s for instance %(uuid)s'), {'event': event_name, 'uuid': instance.uuid}, instance=instance) if CONF.vif_plugging_is_fatal: raise exception.VirtualInterfaceCreateException() def _get_neutron_events(self, network_info): # NOTE(danms): We need to collect any VIFs that are currently # down that we expect a down->up event for. Anything that is # already up will not undergo that transition, and for # anything that might be stale (cache-wise) assume it's # already up so we don't block on it. return [('network-vif-plugged', vif['id']) for vif in network_info if vif.get('active', True) is False] def _create_domain_and_network(self, context, xml, instance, network_info, disk_info, block_device_info=None, power_on=True, reboot=False, vifs_already_plugged=False, post_xml_callback=None): """Do required network setup and create domain.""" block_device_mapping = driver.block_device_info_get_mapping( block_device_info) for vol in block_device_mapping: connection_info = vol['connection_info'] if (not reboot and 'data' in connection_info and 'volume_id' in connection_info['data']): volume_id = connection_info['data']['volume_id'] encryption = encryptors.get_encryption_metadata( context, self._volume_api, volume_id, connection_info) if encryption: encryptor = self._get_volume_encryptor(connection_info, encryption) encryptor.attach_volume(context, **encryption) timeout = CONF.vif_plugging_timeout if (self._conn_supports_start_paused and utils.is_neutron() and not vifs_already_plugged and power_on and timeout): events = self._get_neutron_events(network_info) else: events = [] pause = bool(events) guest = None try: with self.virtapi.wait_for_instance_event( instance, events, deadline=timeout, error_callback=self._neutron_failed_callback): self.plug_vifs(instance, network_info) self.firewall_driver.setup_basic_filtering(instance, network_info) self.firewall_driver.prepare_instance_filter(instance, network_info) with self._lxc_disk_handler(instance, instance.image_meta, block_device_info, disk_info): guest = self._create_domain( xml, pause=pause, power_on=power_on, post_xml_callback=post_xml_callback) self.firewall_driver.apply_instance_filter(instance, network_info) except exception.VirtualInterfaceCreateException: # Neutron reported failure and we didn't swallow it, so # bail here with excutils.save_and_reraise_exception(): if guest: guest.poweroff() self.cleanup(context, instance, network_info=network_info, block_device_info=block_device_info) except eventlet.timeout.Timeout: # We never heard from Neutron LOG.warning(_LW('Timeout waiting for vif plugging callback for ' 'instance %(uuid)s'), {'uuid': instance.uuid}, instance=instance) if CONF.vif_plugging_is_fatal: if guest: guest.poweroff() self.cleanup(context, instance, network_info=network_info, block_device_info=block_device_info) raise exception.VirtualInterfaceCreateException() # Resume only if domain has been paused if pause: guest.resume() return guest def _get_vcpu_total(self): """Get available vcpu number of physical computer. :returns: the number of cpu core instances can be used. """ try: total_pcpus = self._host.get_cpu_count() except libvirt.libvirtError: LOG.warning(_LW("Cannot get the number of cpu, because this " "function is not implemented for this platform. ")) return 0 if not CONF.vcpu_pin_set: return total_pcpus available_ids = hardware.get_vcpu_pin_set() # We get the list of online CPUs on the host and see if the requested # set falls under these. If not, we retain the old behavior. online_pcpus = None try: online_pcpus = self._host.get_online_cpus() except libvirt.libvirtError as ex: error_code = ex.get_error_code() LOG.warning( _LW("Couldn't retrieve the online CPUs due to a Libvirt " "error: %(error)s with error code: %(error_code)s"), {'error': ex, 'error_code': error_code}) if online_pcpus: if not (available_ids <= online_pcpus): msg = (_("Invalid vcpu_pin_set config, one or more of the " "specified cpuset is not online. Online cpuset(s): " "%(online)s, requested cpuset(s): %(req)s"), {'online': sorted(online_pcpus), 'req': sorted(available_ids)}) raise exception.Invalid(msg) elif sorted(available_ids)[-1] >= total_pcpus: raise exception.Invalid(_("Invalid vcpu_pin_set config, " "out of hypervisor cpu range.")) return len(available_ids) @staticmethod def _get_local_gb_info(): """Get local storage info of the compute node in GB. :returns: A dict containing: :total: How big the overall usable filesystem is (in gigabytes) :free: How much space is free (in gigabytes) :used: How much space is used (in gigabytes) """ if CONF.libvirt.images_type == 'lvm': info = lvm.get_volume_group_info( CONF.libvirt.images_volume_group) elif CONF.libvirt.images_type == 'rbd': info = LibvirtDriver._get_rbd_driver().get_pool_info() else: info = libvirt_utils.get_fs_info(CONF.instances_path) for (k, v) in six.iteritems(info): info[k] = v / units.Gi return info def _get_vcpu_used(self): """Get vcpu usage number of physical computer. :returns: The total number of vcpu(s) that are currently being used. """ total = 0 if CONF.libvirt.virt_type == 'lxc': return total + 1 for guest in self._host.list_guests(): try: vcpus = guest.get_vcpus_info() if vcpus is not None: total += len(list(vcpus)) except libvirt.libvirtError as e: LOG.warning( _LW("couldn't obtain the vcpu count from domain id:" " %(uuid)s, exception: %(ex)s"), {"uuid": guest.uuid, "ex": e}) # NOTE(gtt116): give other tasks a chance. greenthread.sleep(0) return total def _get_instance_capabilities(self): """Get hypervisor instance capabilities Returns a list of tuples that describe instances the hypervisor is capable of hosting. Each tuple consists of the triplet (arch, hypervisor_type, vm_mode). :returns: List of tuples describing instance capabilities """ caps = self._host.get_capabilities() instance_caps = list() for g in caps.guests: for dt in g.domtype: instance_cap = ( arch.canonicalize(g.arch), hv_type.canonicalize(dt), vm_mode.canonicalize(g.ostype)) instance_caps.append(instance_cap) return instance_caps def _get_cpu_info(self): """Get cpuinfo information. Obtains cpu feature from virConnect.getCapabilities. :return: see above description """ caps = self._host.get_capabilities() cpu_info = dict() cpu_info['arch'] = caps.host.cpu.arch cpu_info['model'] = caps.host.cpu.model cpu_info['vendor'] = caps.host.cpu.vendor topology = dict() topology['cells'] = len(getattr(caps.host.topology, 'cells', [1])) topology['sockets'] = caps.host.cpu.sockets topology['cores'] = caps.host.cpu.cores topology['threads'] = caps.host.cpu.threads cpu_info['topology'] = topology features = set() for f in caps.host.cpu.features: features.add(f.name) cpu_info['features'] = features return cpu_info def _get_pcidev_info(self, devname): """Returns a dict of PCI device.""" def _get_device_type(cfgdev, pci_address): """Get a PCI device's device type. An assignable PCI device can be a normal PCI device, a SR-IOV Physical Function (PF), or a SR-IOV Virtual Function (VF). Only normal PCI devices or SR-IOV VFs are assignable, while SR-IOV PFs are always owned by hypervisor. """ for fun_cap in cfgdev.pci_capability.fun_capability: if fun_cap.type == 'virt_functions': return { 'dev_type': fields.PciDeviceType.SRIOV_PF, } if (fun_cap.type == 'phys_function' and len(fun_cap.device_addrs) != 0): phys_address = "%04x:%02x:%02x.%01x" % ( fun_cap.device_addrs[0][0], fun_cap.device_addrs[0][1], fun_cap.device_addrs[0][2], fun_cap.device_addrs[0][3]) return { 'dev_type': fields.PciDeviceType.SRIOV_VF, 'parent_addr': phys_address, } # Note(moshele): libvirt < 1.3 reported virt_functions capability # only when VFs are enabled. The check below is a workaround # to get the correct report regardless of whether or not any # VFs are enabled for the device. if not self._host.has_min_version( MIN_LIBVIRT_PF_WITH_NO_VFS_CAP_VERSION): is_physical_function = pci_utils.is_physical_function( *pci_utils.get_pci_address_fields(pci_address)) if is_physical_function: return {'dev_type': fields.PciDeviceType.SRIOV_PF} return {'dev_type': fields.PciDeviceType.STANDARD} virtdev = self._host.device_lookup_by_name(devname) xmlstr = virtdev.XMLDesc(0) cfgdev = vconfig.LibvirtConfigNodeDevice() cfgdev.parse_str(xmlstr) address = "%04x:%02x:%02x.%1x" % ( cfgdev.pci_capability.domain, cfgdev.pci_capability.bus, cfgdev.pci_capability.slot, cfgdev.pci_capability.function) device = { "dev_id": cfgdev.name, "address": address, "product_id": "%04x" % cfgdev.pci_capability.product_id, "vendor_id": "%04x" % cfgdev.pci_capability.vendor_id, } device["numa_node"] = cfgdev.pci_capability.numa_node # requirement by DataBase Model device['label'] = 'label_%(vendor_id)s_%(product_id)s' % device device.update(_get_device_type(cfgdev, address)) return device def _get_pci_passthrough_devices(self): """Get host PCI devices information. Obtains pci devices information from libvirt, and returns as a JSON string. Each device information is a dictionary, with mandatory keys of 'address', 'vendor_id', 'product_id', 'dev_type', 'dev_id', 'label' and other optional device specific information. Refer to the objects/pci_device.py for more idea of these keys. :returns: a JSON string containing a list of the assignable PCI devices information """ # Bail early if we know we can't support `listDevices` to avoid # repeated warnings within a periodic task if not getattr(self, '_list_devices_supported', True): return jsonutils.dumps([]) try: dev_names = self._host.list_pci_devices() or [] except libvirt.libvirtError as ex: error_code = ex.get_error_code() if error_code == libvirt.VIR_ERR_NO_SUPPORT: self._list_devices_supported = False LOG.warning(_LW("URI %(uri)s does not support " "listDevices: %(error)s"), {'uri': self._uri(), 'error': ex}) return jsonutils.dumps([]) else: raise pci_info = [] for name in dev_names: pci_info.append(self._get_pcidev_info(name)) return jsonutils.dumps(pci_info) def _has_numa_support(self): # This means that the host can support LibvirtConfigGuestNUMATune # and the nodeset field in LibvirtConfigGuestMemoryBackingPage for ver in BAD_LIBVIRT_NUMA_VERSIONS: if self._host.has_version(ver): if not getattr(self, '_bad_libvirt_numa_version_warn', False): LOG.warning(_LW('You are running with libvirt version %s ' 'which is known to have broken NUMA support. ' 'Consider patching or updating libvirt on ' 'this host if you need NUMA support.'), self._version_to_string(ver)) self._bad_libvirt_numa_version_warn = True return False support_matrix = {(arch.I686, arch.X86_64): MIN_LIBVIRT_NUMA_VERSION, (arch.PPC64, arch.PPC64LE): MIN_LIBVIRT_NUMA_VERSION_PPC} caps = self._host.get_capabilities() is_supported = False for archs, libvirt_ver in support_matrix.items(): if ((caps.host.cpu.arch in archs) and self._host.has_min_version(libvirt_ver, MIN_QEMU_NUMA_HUGEPAGE_VERSION, host.HV_DRIVER_QEMU)): is_supported = True return is_supported def _has_hugepage_support(self): # This means that the host can support multiple values for the size # field in LibvirtConfigGuestMemoryBackingPage supported_archs = [arch.I686, arch.X86_64, arch.PPC64LE, arch.PPC64] caps = self._host.get_capabilities() return ((caps.host.cpu.arch in supported_archs) and self._host.has_min_version(MIN_LIBVIRT_HUGEPAGE_VERSION, MIN_QEMU_NUMA_HUGEPAGE_VERSION, host.HV_DRIVER_QEMU)) def _get_host_numa_topology(self): if not self._has_numa_support(): return caps = self._host.get_capabilities() topology = caps.host.topology if topology is None or not topology.cells: return cells = [] allowed_cpus = hardware.get_vcpu_pin_set() online_cpus = self._host.get_online_cpus() if allowed_cpus: allowed_cpus &= online_cpus else: allowed_cpus = online_cpus def _get_reserved_memory_for_cell(self, cell_id, page_size): cell = self._reserved_hugepages.get(cell_id, {}) return cell.get(page_size, 0) for cell in topology.cells: cpuset = set(cpu.id for cpu in cell.cpus) siblings = sorted(map(set, set(tuple(cpu.siblings) if cpu.siblings else () for cpu in cell.cpus) )) cpuset &= allowed_cpus siblings = [sib & allowed_cpus for sib in siblings] # Filter out singles and empty sibling sets that may be left siblings = [sib for sib in siblings if len(sib) > 1] mempages = [] if self._has_hugepage_support(): mempages = [ objects.NUMAPagesTopology( size_kb=pages.size, total=pages.total, used=0, reserved=_get_reserved_memory_for_cell( self, cell.id, pages.size)) for pages in cell.mempages] cell = objects.NUMACell(id=cell.id, cpuset=cpuset, memory=cell.memory / units.Ki, cpu_usage=0, memory_usage=0, siblings=siblings, pinned_cpus=set([]), mempages=mempages) cells.append(cell) return objects.NUMATopology(cells=cells) def get_all_volume_usage(self, context, compute_host_bdms): """Return usage info for volumes attached to vms on a given host. """ vol_usage = [] for instance_bdms in compute_host_bdms: instance = instance_bdms['instance'] for bdm in instance_bdms['instance_bdms']: mountpoint = bdm['device_name'] if mountpoint.startswith('/dev/'): mountpoint = mountpoint[5:] volume_id = bdm['volume_id'] LOG.debug("Trying to get stats for the volume %s", volume_id, instance=instance) vol_stats = self.block_stats(instance, mountpoint) if vol_stats: stats = dict(volume=volume_id, instance=instance, rd_req=vol_stats[0], rd_bytes=vol_stats[1], wr_req=vol_stats[2], wr_bytes=vol_stats[3]) LOG.debug( "Got volume usage stats for the volume=%(volume)s," " rd_req=%(rd_req)d, rd_bytes=%(rd_bytes)d, " "wr_req=%(wr_req)d, wr_bytes=%(wr_bytes)d", stats, instance=instance) vol_usage.append(stats) return vol_usage def block_stats(self, instance, disk_id): """Note that this function takes an instance name.""" try: guest = self._host.get_guest(instance) # TODO(sahid): We are converting all calls from a # virDomain object to use nova.virt.libvirt.Guest. # We should be able to remove domain at the end. domain = guest._domain return domain.blockStats(disk_id) except libvirt.libvirtError as e: errcode = e.get_error_code() LOG.info(_LI('Getting block stats failed, device might have ' 'been detached. Instance=%(instance_name)s ' 'Disk=%(disk)s Code=%(errcode)s Error=%(e)s'), {'instance_name': instance.name, 'disk': disk_id, 'errcode': errcode, 'e': e}, instance=instance) except exception.InstanceNotFound: LOG.info(_LI('Could not find domain in libvirt for instance %s. ' 'Cannot get block stats for device'), instance.name, instance=instance) def get_console_pool_info(self, console_type): # TODO(mdragon): console proxy should be implemented for libvirt, # in case someone wants to use it with kvm or # such. For now return fake data. return {'address': '127.0.0.1', 'username': 'fakeuser', 'password': 'fakepassword'} def refresh_security_group_rules(self, security_group_id): self.firewall_driver.refresh_security_group_rules(security_group_id) def refresh_instance_security_rules(self, instance): self.firewall_driver.refresh_instance_security_rules(instance) def get_available_resource(self, nodename): """Retrieve resource information. This method is called when nova-compute launches, and as part of a periodic task that records the results in the DB. :param nodename: unused in this driver :returns: dictionary containing resource info """ disk_info_dict = self._get_local_gb_info() data = {} # NOTE(dprince): calling capabilities before getVersion works around # an initialization issue with some versions of Libvirt (1.0.5.5). # See: https://bugzilla.redhat.com/show_bug.cgi?id=1000116 # See: https://bugs.launchpad.net/nova/+bug/1215593 data["supported_instances"] = self._get_instance_capabilities() data["vcpus"] = self._get_vcpu_total() data["memory_mb"] = self._host.get_memory_mb_total() data["local_gb"] = disk_info_dict['total'] data["vcpus_used"] = self._get_vcpu_used() data["memory_mb_used"] = self._host.get_memory_mb_used() data["local_gb_used"] = disk_info_dict['used'] data["hypervisor_type"] = self._host.get_driver_type() data["hypervisor_version"] = self._host.get_version() data["hypervisor_hostname"] = self._host.get_hostname() # TODO(berrange): why do we bother converting the # libvirt capabilities XML into a special JSON format ? # The data format is different across all the drivers # so we could just return the raw capabilities XML # which 'compare_cpu' could use directly # # That said, arch_filter.py now seems to rely on # the libvirt drivers format which suggests this # data format needs to be standardized across drivers data["cpu_info"] = jsonutils.dumps(self._get_cpu_info()) disk_free_gb = disk_info_dict['free'] disk_over_committed = self._get_disk_over_committed_size_total() available_least = disk_free_gb * units.Gi - disk_over_committed data['disk_available_least'] = available_least / units.Gi data['pci_passthrough_devices'] = \ self._get_pci_passthrough_devices() numa_topology = self._get_host_numa_topology() if numa_topology: data['numa_topology'] = numa_topology._to_json() else: data['numa_topology'] = None return data def check_instance_shared_storage_local(self, context, instance): """Check if instance files located on shared storage. This runs check on the destination host, and then calls back to the source host to check the results. :param context: security context :param instance: nova.objects.instance.Instance object :returns: - tempfile: A dict containing the tempfile info on the destination host - None: 1. If the instance path is not existing. 2. If the image backend is shared block storage type. """ if self.image_backend.backend().is_shared_block_storage(): return None dirpath = libvirt_utils.get_instance_path(instance) if not os.path.exists(dirpath): return None fd, tmp_file = tempfile.mkstemp(dir=dirpath) LOG.debug("Creating tmpfile %s to verify with other " "compute node that the instance is on " "the same shared storage.", tmp_file, instance=instance) os.close(fd) return {"filename": tmp_file} def check_instance_shared_storage_remote(self, context, data): return os.path.exists(data['filename']) def check_instance_shared_storage_cleanup(self, context, data): fileutils.delete_if_exists(data["filename"]) def check_can_live_migrate_destination(self, context, instance, src_compute_info, dst_compute_info, block_migration=False, disk_over_commit=False): """Check if it is possible to execute live migration. This runs checks on the destination host, and then calls back to the source host to check the results. :param context: security context :param instance: nova.db.sqlalchemy.models.Instance :param block_migration: if true, prepare for block migration :param disk_over_commit: if true, allow disk over commit :returns: a LibvirtLiveMigrateData object """ disk_available_gb = dst_compute_info['disk_available_least'] disk_available_mb = ( (disk_available_gb * units.Ki) - CONF.reserved_host_disk_mb) # Compare CPU if not instance.vcpu_model or not instance.vcpu_model.model: source_cpu_info = src_compute_info['cpu_info'] self._compare_cpu(None, source_cpu_info, instance) else: self._compare_cpu(instance.vcpu_model, None, instance) # Create file on storage, to be checked on source host filename = self._create_shared_storage_test_file(instance) data = objects.LibvirtLiveMigrateData() data.filename = filename data.image_type = CONF.libvirt.images_type # Notes(eliqiao): block_migration and disk_over_commit are not # nullable, so just don't set them if they are None if block_migration is not None: data.block_migration = block_migration if disk_over_commit is not None: data.disk_over_commit = disk_over_commit data.disk_available_mb = disk_available_mb return data def cleanup_live_migration_destination_check(self, context, dest_check_data): """Do required cleanup on dest host after check_can_live_migrate calls :param context: security context """ filename = dest_check_data.filename self._cleanup_shared_storage_test_file(filename) def check_can_live_migrate_source(self, context, instance, dest_check_data, block_device_info=None): """Check if it is possible to execute live migration. This checks if the live migration can succeed, based on the results from check_can_live_migrate_destination. :param context: security context :param instance: nova.db.sqlalchemy.models.Instance :param dest_check_data: result of check_can_live_migrate_destination :param block_device_info: result of _get_instance_block_device_info :returns: a LibvirtLiveMigrateData object """ if not isinstance(dest_check_data, migrate_data_obj.LiveMigrateData): md_obj = objects.LibvirtLiveMigrateData() md_obj.from_legacy_dict(dest_check_data) dest_check_data = md_obj # Checking shared storage connectivity # if block migration, instances_paths should not be on shared storage. source = CONF.host dest_check_data.is_shared_instance_path = ( self._check_shared_storage_test_file( dest_check_data.filename, instance)) dest_check_data.is_shared_block_storage = ( self._is_shared_block_storage(instance, dest_check_data, block_device_info)) disk_info_text = self.get_instance_disk_info( instance, block_device_info=block_device_info) booted_from_volume = self._is_booted_from_volume(instance, disk_info_text) has_local_disk = self._has_local_disk(instance, disk_info_text) if 'block_migration' not in dest_check_data: dest_check_data.block_migration = ( not dest_check_data.is_on_shared_storage()) if dest_check_data.block_migration: # TODO(eliqiao): Once block_migration flag is removed from the API # we can safely remove the if condition if dest_check_data.is_on_shared_storage(): reason = _("Block migration can not be used " "with shared storage.") raise exception.InvalidLocalStorage(reason=reason, path=source) if 'disk_over_commit' in dest_check_data: self._assert_dest_node_has_enough_disk(context, instance, dest_check_data.disk_available_mb, dest_check_data.disk_over_commit, block_device_info) if block_device_info: bdm = block_device_info.get('block_device_mapping') # NOTE(pkoniszewski): libvirt from version 1.2.17 upwards # supports selective block device migration. It means that it # is possible to define subset of block devices to be copied # during migration. If they are not specified - block devices # won't be migrated. However, it does not work when live # migration is tunnelled through libvirt. if bdm and not self._host.has_min_version( MIN_LIBVIRT_BLOCK_LM_WITH_VOLUMES_VERSION): # NOTE(stpierre): if this instance has mapped volumes, # we can't do a block migration, since that will result # in volumes being copied from themselves to themselves, # which is a recipe for disaster. ver = ".".join([str(x) for x in MIN_LIBVIRT_BLOCK_LM_WITH_VOLUMES_VERSION]) msg = (_('Cannot block migrate instance %(uuid)s with' ' mapped volumes. Selective block device' ' migration feature requires libvirt version' ' %(libvirt_ver)s') % {'uuid': instance.uuid, 'libvirt_ver': ver}) LOG.error(msg, instance=instance) raise exception.MigrationPreCheckError(reason=msg) # NOTE(eliqiao): Selective disk migrations are not supported # with tunnelled block migrations so we can block them early. if (bdm and (self._block_migration_flags & libvirt.VIR_MIGRATE_TUNNELLED != 0)): msg = (_('Cannot block migrate instance %(uuid)s with' ' mapped volumes. Selective block device' ' migration is not supported with tunnelled' ' block migrations.') % {'uuid': instance.uuid}) LOG.error(msg, instance=instance) raise exception.MigrationPreCheckError(reason=msg) elif not (dest_check_data.is_shared_block_storage or dest_check_data.is_shared_instance_path or (booted_from_volume and not has_local_disk)): reason = _("Live migration can not be used " "without shared storage except " "a booted from volume VM which " "does not have a local disk.") raise exception.InvalidSharedStorage(reason=reason, path=source) # NOTE(mikal): include the instance directory name here because it # doesn't yet exist on the destination but we want to force that # same name to be used instance_path = libvirt_utils.get_instance_path(instance, relative=True) dest_check_data.instance_relative_path = instance_path return dest_check_data def _is_shared_block_storage(self, instance, dest_check_data, block_device_info=None): """Check if all block storage of an instance can be shared between source and destination of a live migration. Returns true if the instance is volume backed and has no local disks, or if the image backend is the same on source and destination and the backend shares block storage between compute nodes. :param instance: nova.objects.instance.Instance object :param dest_check_data: dict with boolean fields image_type, is_shared_instance_path, and is_volume_backed """ if (dest_check_data.obj_attr_is_set('image_type') and CONF.libvirt.images_type == dest_check_data.image_type and self.image_backend.backend().is_shared_block_storage()): # NOTE(dgenin): currently true only for RBD image backend return True if (dest_check_data.is_shared_instance_path and self.image_backend.backend().is_file_in_instance_path()): # NOTE(angdraug): file based image backends (Flat, Qcow2) # place block device files under the instance path return True if (dest_check_data.is_volume_backed and not bool(jsonutils.loads( self.get_instance_disk_info(instance, block_device_info)))): return True return False def _assert_dest_node_has_enough_disk(self, context, instance, available_mb, disk_over_commit, block_device_info=None): """Checks if destination has enough disk for block migration.""" # Libvirt supports qcow2 disk format,which is usually compressed # on compute nodes. # Real disk image (compressed) may enlarged to "virtual disk size", # that is specified as the maximum disk size. # (See qemu-img -f path-to-disk) # Scheduler recognizes destination host still has enough disk space # if real disk size < available disk size # if disk_over_commit is True, # otherwise virtual disk size < available disk size. available = 0 if available_mb: available = available_mb * units.Mi ret = self.get_instance_disk_info(instance, block_device_info=block_device_info) disk_infos = jsonutils.loads(ret) necessary = 0 if disk_over_commit: for info in disk_infos: necessary += int(info['disk_size']) else: for info in disk_infos: necessary += int(info['virt_disk_size']) # Check that available disk > necessary disk if (available - necessary) < 0: reason = (_('Unable to migrate %(instance_uuid)s: ' 'Disk of instance is too large(available' ' on destination host:%(available)s ' '< need:%(necessary)s)') % {'instance_uuid': instance.uuid, 'available': available, 'necessary': necessary}) raise exception.MigrationPreCheckError(reason=reason) def _compare_cpu(self, guest_cpu, host_cpu_str, instance): """Check the host is compatible with the requested CPU :param guest_cpu: nova.objects.VirtCPUModel or None :param host_cpu_str: JSON from _get_cpu_info() method If the 'guest_cpu' parameter is not None, this will be validated for migration compatibility with the host. Otherwise the 'host_cpu_str' JSON string will be used for validation. :returns: None. if given cpu info is not compatible to this server, raise exception. """ # NOTE(kchamart): Comparing host to guest CPU model for emulated # guests (<domain type='qemu'>) should not matter -- in this # mode (QEMU "TCG") the CPU is fully emulated in software and no # hardware acceleration, like KVM, is involved. So, skip the CPU # compatibility check for the QEMU domain type, and retain it for # KVM guests. if CONF.libvirt.virt_type not in ['kvm']: return if guest_cpu is None: info = jsonutils.loads(host_cpu_str) LOG.info(_LI('Instance launched has CPU info: %s'), host_cpu_str) cpu = vconfig.LibvirtConfigCPU() cpu.arch = info['arch'] cpu.model = info['model'] cpu.vendor = info['vendor'] cpu.sockets = info['topology']['sockets'] cpu.cores = info['topology']['cores'] cpu.threads = info['topology']['threads'] for f in info['features']: cpu.add_feature(vconfig.LibvirtConfigCPUFeature(f)) else: cpu = self._vcpu_model_to_cpu_config(guest_cpu) u = ("http://libvirt.org/html/libvirt-libvirt-host.html#" "virCPUCompareResult") m = _("CPU doesn't have compatibility.\n\n%(ret)s\n\nRefer to %(u)s") # unknown character exists in xml, then libvirt complains try: cpu_xml = cpu.to_xml() LOG.debug("cpu compare xml: %s", cpu_xml, instance=instance) ret = self._host.compare_cpu(cpu_xml) except libvirt.libvirtError as e: error_code = e.get_error_code() if error_code == libvirt.VIR_ERR_NO_SUPPORT: LOG.debug("URI %(uri)s does not support cpu comparison. " "It will be proceeded though. Error: %(error)s", {'uri': self._uri(), 'error': e}) return else: LOG.error(m, {'ret': e, 'u': u}) raise exception.MigrationPreCheckError( reason=m % {'ret': e, 'u': u}) if ret <= 0: LOG.error(m, {'ret': ret, 'u': u}) raise exception.InvalidCPUInfo(reason=m % {'ret': ret, 'u': u}) def _create_shared_storage_test_file(self, instance): """Makes tmpfile under CONF.instances_path.""" dirpath = CONF.instances_path fd, tmp_file = tempfile.mkstemp(dir=dirpath) LOG.debug("Creating tmpfile %s to notify to other " "compute nodes that they should mount " "the same storage.", tmp_file, instance=instance) os.close(fd) return os.path.basename(tmp_file) def _check_shared_storage_test_file(self, filename, instance): """Confirms existence of the tmpfile under CONF.instances_path. Cannot confirm tmpfile return False. """ # NOTE(tpatzig): if instances_path is a shared volume that is # under heavy IO (many instances on many compute nodes), # then checking the existence of the testfile fails, # just because it takes longer until the client refreshes and new # content gets visible. # os.utime (like touch) on the directory forces the client to refresh. os.utime(CONF.instances_path, None) tmp_file = os.path.join(CONF.instances_path, filename) if not os.path.exists(tmp_file): exists = False else: exists = True LOG.debug('Check if temp file %s exists to indicate shared storage ' 'is being used for migration. Exists? %s', tmp_file, exists, instance=instance) return exists def _cleanup_shared_storage_test_file(self, filename): """Removes existence of the tmpfile under CONF.instances_path.""" tmp_file = os.path.join(CONF.instances_path, filename) os.remove(tmp_file) def ensure_filtering_rules_for_instance(self, instance, network_info): """Ensure that an instance's filtering rules are enabled. When migrating an instance, we need the filtering rules to be configured on the destination host before starting the migration. Also, when restarting the compute service, we need to ensure that filtering rules exist for all running services. """ self.firewall_driver.setup_basic_filtering(instance, network_info) self.firewall_driver.prepare_instance_filter(instance, network_info) # nwfilters may be defined in a separate thread in the case # of libvirt non-blocking mode, so we wait for completion timeout_count = list(range(CONF.live_migration_retry_count)) while timeout_count: if self.firewall_driver.instance_filter_exists(instance, network_info): break timeout_count.pop() if len(timeout_count) == 0: msg = _('The firewall filter for %s does not exist') raise exception.NovaException(msg % instance.name) greenthread.sleep(1) def filter_defer_apply_on(self): self.firewall_driver.filter_defer_apply_on() def filter_defer_apply_off(self): self.firewall_driver.filter_defer_apply_off() def live_migration(self, context, instance, dest, post_method, recover_method, block_migration=False, migrate_data=None): """Spawning live_migration operation for distributing high-load. :param context: security context :param instance: nova.db.sqlalchemy.models.Instance object instance object that is migrated. :param dest: destination host :param post_method: post operation method. expected nova.compute.manager._post_live_migration. :param recover_method: recovery method when any exception occurs. expected nova.compute.manager._rollback_live_migration. :param block_migration: if true, do block migration. :param migrate_data: a LibvirtLiveMigrateData object """ # 'dest' will be substituted into 'migration_uri' so ensure # it does't contain any characters that could be used to # exploit the URI accepted by libivrt if not libvirt_utils.is_valid_hostname(dest): raise exception.InvalidHostname(hostname=dest) self._live_migration(context, instance, dest, post_method, recover_method, block_migration, migrate_data) def live_migration_abort(self, instance): """Aborting a running live-migration. :param instance: instance object that is in migration """ guest = self._host.get_guest(instance) dom = guest._domain try: dom.abortJob() except libvirt.libvirtError as e: LOG.error(_LE("Failed to cancel migration %s"), e, instance=instance) raise def _check_graphics_addresses_can_live_migrate(self, listen_addrs): LOCAL_ADDRS = ('0.0.0.0', '127.0.0.1', '::', '::1') local_vnc = CONF.vnc.vncserver_listen in LOCAL_ADDRS local_spice = CONF.spice.server_listen in LOCAL_ADDRS if ((CONF.vnc.enabled and not local_vnc) or (CONF.spice.enabled and not local_spice)): msg = _('Your libvirt version does not support the' ' VIR_DOMAIN_XML_MIGRATABLE flag or your' ' destination node does not support' ' retrieving listen addresses. In order' ' for live migration to work properly, you' ' must configure the graphics (VNC and/or' ' SPICE) listen addresses to be either' ' the catch-all address (0.0.0.0 or ::) or' ' the local address (127.0.0.1 or ::1).') raise exception.MigrationError(reason=msg) if listen_addrs: dest_local_vnc = listen_addrs.get('vnc') in LOCAL_ADDRS dest_local_spice = listen_addrs.get('spice') in LOCAL_ADDRS if ((CONF.vnc.enabled and not dest_local_vnc) or (CONF.spice.enabled and not dest_local_spice)): LOG.warning(_LW('Your libvirt version does not support the' ' VIR_DOMAIN_XML_MIGRATABLE flag, and the' ' graphics (VNC and/or SPICE) listen' ' addresses on the destination node do not' ' match the addresses on the source node.' ' Since the source node has listen' ' addresses set to either the catch-all' ' address (0.0.0.0 or ::) or the local' ' address (127.0.0.1 or ::1), the live' ' migration will succeed, but the VM will' ' continue to listen on the current' ' addresses.')) def _verify_serial_console_is_disabled(self): if CONF.serial_console.enabled: msg = _('Your libvirt version does not support the' ' VIR_DOMAIN_XML_MIGRATABLE flag or your' ' destination node does not support' ' retrieving listen addresses. In order' ' for live migration to work properly you' ' must either disable serial console or' ' upgrade your libvirt version.') raise exception.MigrationError(reason=msg) def _live_migration_operation(self, context, instance, dest, block_migration, migrate_data, guest, device_names): """Invoke the live migration operation :param context: security context :param instance: nova.db.sqlalchemy.models.Instance object instance object that is migrated. :param dest: destination host :param block_migration: if true, do block migration. :param migrate_data: a LibvirtLiveMigrateData object :param guest: the guest domain object :param device_names: list of device names that are being migrated with instance This method is intended to be run in a background thread and will block that thread until the migration is finished or failed. """ try: if migrate_data.block_migration: migration_flags = self._block_migration_flags else: migration_flags = self._live_migration_flags listen_addrs = libvirt_migrate.graphics_listen_addrs( migrate_data) migratable_flag = self._host.is_migratable_xml_flag() if not migratable_flag or not listen_addrs: # In this context want to ensure we do not have to migrate # graphic or serial consoles since we can't update guest's # domain XML to make it handle destination host. # TODO(alexs-h): These checks could be moved to the # check_can_live_migrate_destination/source phase self._check_graphics_addresses_can_live_migrate(listen_addrs) self._verify_serial_console_is_disabled() if ('target_connect_addr' in migrate_data and migrate_data.target_connect_addr is not None): dest = migrate_data.target_connect_addr new_xml_str = None params = None if (self._host.is_migratable_xml_flag() and ( listen_addrs or migrate_data.bdms)): new_xml_str = libvirt_migrate.get_updated_guest_xml( # TODO(sahid): It's not a really well idea to pass # the method _get_volume_config and we should to find # a way to avoid this in future. guest, migrate_data, self._get_volume_config) if self._host.has_min_version( MIN_LIBVIRT_BLOCK_LM_WITH_VOLUMES_VERSION): params = { 'bandwidth': CONF.libvirt.live_migration_bandwidth, 'destination_xml': new_xml_str, 'migrate_disks': device_names, } # NOTE(pkoniszewski): Because of precheck which blocks # tunnelled block live migration with mapped volumes we # can safely remove migrate_disks when tunnelling is on. # Otherwise we will block all tunnelled block migrations, # even when an instance does not have volumes mapped. # This is because selective disk migration is not # supported in tunnelled block live migration. Also we # cannot fallback to migrateToURI2 in this case because of # bug #1398999 if (migration_flags & libvirt.VIR_MIGRATE_TUNNELLED != 0): params.pop('migrate_disks') guest.migrate(self._live_migration_uri(dest), flags=migration_flags, params=params, domain_xml=new_xml_str, bandwidth=CONF.libvirt.live_migration_bandwidth) except Exception as e: with excutils.save_and_reraise_exception(): LOG.error(_LE("Live Migration failure: %s"), e, instance=instance) # If 'migrateToURI' fails we don't know what state the # VM instances on each host are in. Possibilities include # # 1. src==running, dst==none # # Migration failed & rolled back, or never started # # 2. src==running, dst==paused # # Migration started but is still ongoing # # 3. src==paused, dst==paused # # Migration data transfer completed, but switchover # is still ongoing, or failed # # 4. src==paused, dst==running # # Migration data transfer completed, switchover # happened but cleanup on source failed # # 5. src==none, dst==running # # Migration fully succeeded. # # Libvirt will aim to complete any migration operation # or roll it back. So even if the migrateToURI call has # returned an error, if the migration was not finished # libvirt should clean up. # # So we take the error raise here with a pinch of salt # and rely on the domain job info status to figure out # what really happened to the VM, which is a much more # reliable indicator. # # In particular we need to try very hard to ensure that # Nova does not "forget" about the guest. ie leaving it # running on a different host to the one recorded in # the database, as that would be a serious resource leak LOG.debug("Migration operation thread has finished", instance=instance) @staticmethod def _migration_downtime_steps(data_gb): '''Calculate downtime value steps and time between increases. :param data_gb: total GB of RAM and disk to transfer This looks at the total downtime steps and upper bound downtime value and uses an exponential backoff. So initially max downtime is increased by small amounts, and as time goes by it is increased by ever larger amounts For example, with 10 steps, 30 second step delay, 3 GB of RAM and 400ms target maximum downtime, the downtime will be increased every 90 seconds in the following progression: - 0 seconds -> set downtime to 37ms - 90 seconds -> set downtime to 38ms - 180 seconds -> set downtime to 39ms - 270 seconds -> set downtime to 42ms - 360 seconds -> set downtime to 46ms - 450 seconds -> set downtime to 55ms - 540 seconds -> set downtime to 70ms - 630 seconds -> set downtime to 98ms - 720 seconds -> set downtime to 148ms - 810 seconds -> set downtime to 238ms - 900 seconds -> set downtime to 400ms This allows the guest a good chance to complete migration with a small downtime value. ''' downtime = CONF.libvirt.live_migration_downtime steps = CONF.libvirt.live_migration_downtime_steps delay = CONF.libvirt.live_migration_downtime_delay # TODO(hieulq): Need to move min/max value into the config option, # currently oslo_config will raise ValueError instead of setting # option value to its min/max. if downtime < nova.conf.libvirt.LIVE_MIGRATION_DOWNTIME_MIN: downtime = nova.conf.libvirt.LIVE_MIGRATION_DOWNTIME_MIN if steps < nova.conf.libvirt.LIVE_MIGRATION_DOWNTIME_STEPS_MIN: steps = nova.conf.libvirt.LIVE_MIGRATION_DOWNTIME_STEPS_MIN if delay < nova.conf.libvirt.LIVE_MIGRATION_DOWNTIME_DELAY_MIN: delay = nova.conf.libvirt.LIVE_MIGRATION_DOWNTIME_DELAY_MIN delay = int(delay * data_gb) offset = downtime / float(steps + 1) base = (downtime - offset) ** (1 / float(steps)) for i in range(steps + 1): yield (int(delay * i), int(offset + base ** i)) def _live_migration_copy_disk_paths(self, context, instance, guest): '''Get list of disks to copy during migration :param context: security context :param instance: the instance being migrated :param guest: the Guest instance being migrated Get the list of disks to copy during migration. :returns: a list of local source paths and a list of device names to copy ''' disk_paths = [] device_names = [] block_devices = [] # TODO(pkoniszewski): Remove version check when we bump min libvirt # version to >= 1.2.17. if (self._block_migration_flags & libvirt.VIR_MIGRATE_TUNNELLED == 0 and self._host.has_min_version( MIN_LIBVIRT_BLOCK_LM_WITH_VOLUMES_VERSION)): bdm_list = objects.BlockDeviceMappingList.get_by_instance_uuid( context, instance.uuid) block_device_info = driver.get_block_device_info(instance, bdm_list) block_device_mappings = driver.block_device_info_get_mapping( block_device_info) for bdm in block_device_mappings: device_name = str(bdm['mount_device'].rsplit('/', 1)[1]) block_devices.append(device_name) for dev in guest.get_all_disks(): if dev.readonly or dev.shareable: continue if dev.source_type not in ["file", "block"]: continue if dev.target_dev in block_devices: continue disk_paths.append(dev.source_path) device_names.append(dev.target_dev) return (disk_paths, device_names) def _live_migration_data_gb(self, instance, disk_paths): '''Calculate total amount of data to be transferred :param instance: the nova.objects.Instance being migrated :param disk_paths: list of disk paths that are being migrated with instance Calculates the total amount of data that needs to be transferred during the live migration. The actual amount copied will be larger than this, due to the guest OS continuing to dirty RAM while the migration is taking place. So this value represents the minimal data size possible. :returns: data size to be copied in GB ''' ram_gb = instance.flavor.memory_mb * units.Mi / units.Gi if ram_gb < 2: ram_gb = 2 disk_gb = 0 for path in disk_paths: try: size = os.stat(path).st_size size_gb = (size / units.Gi) if size_gb < 2: size_gb = 2 disk_gb += size_gb except OSError as e: LOG.warning(_LW("Unable to stat %(disk)s: %(ex)s"), {'disk': path, 'ex': e}) # Ignore error since we don't want to break # the migration monitoring thread operation return ram_gb + disk_gb def _get_migration_flags(self, is_block_migration): if is_block_migration: return self._block_migration_flags return self._live_migration_flags def _live_migration_monitor(self, context, instance, guest, dest, post_method, recover_method, block_migration, migrate_data, finish_event, disk_paths): on_migration_failure = deque() data_gb = self._live_migration_data_gb(instance, disk_paths) downtime_steps = list(self._migration_downtime_steps(data_gb)) migration = migrate_data.migration curdowntime = None migration_flags = self._get_migration_flags( migrate_data.block_migration) n = 0 start = time.time() progress_time = start progress_watermark = None previous_data_remaining = -1 is_post_copy_enabled = self._is_post_copy_enabled(migration_flags) while True: info = guest.get_job_info() if info.type == libvirt.VIR_DOMAIN_JOB_NONE: # Either still running, or failed or completed, # lets untangle the mess if not finish_event.ready(): LOG.debug("Operation thread is still running", instance=instance) else: info.type = libvirt_migrate.find_job_type(guest, instance) LOG.debug("Fixed incorrect job type to be %d", info.type, instance=instance) if info.type == libvirt.VIR_DOMAIN_JOB_NONE: # Migration is not yet started LOG.debug("Migration not running yet", instance=instance) elif info.type == libvirt.VIR_DOMAIN_JOB_UNBOUNDED: # Migration is still running # # This is where we wire up calls to change live # migration status. eg change max downtime, cancel # the operation, change max bandwidth libvirt_migrate.run_tasks(guest, instance, self.active_migrations, on_migration_failure, migration, is_post_copy_enabled) now = time.time() elapsed = now - start if ((progress_watermark is None) or (progress_watermark == 0) or (progress_watermark > info.data_remaining)): progress_watermark = info.data_remaining progress_time = now progress_timeout = CONF.libvirt.live_migration_progress_timeout completion_timeout = int( CONF.libvirt.live_migration_completion_timeout * data_gb) if libvirt_migrate.should_abort(instance, now, progress_time, progress_timeout, elapsed, completion_timeout, migration.status): try: guest.abort_job() except libvirt.libvirtError as e: LOG.warning(_LW("Failed to abort migration %s"), e, instance=instance) self._clear_empty_migration(instance) raise if (is_post_copy_enabled and libvirt_migrate.should_switch_to_postcopy( info.memory_iteration, info.data_remaining, previous_data_remaining, migration.status)): libvirt_migrate.trigger_postcopy_switch(guest, instance, migration) previous_data_remaining = info.data_remaining curdowntime = libvirt_migrate.update_downtime( guest, instance, curdowntime, downtime_steps, elapsed) # We loop every 500ms, so don't log on every # iteration to avoid spamming logs for long # running migrations. Just once every 5 secs # is sufficient for developers to debug problems. # We log once every 30 seconds at info to help # admins see slow running migration operations # when debug logs are off. if (n % 10) == 0: # Ignoring memory_processed, as due to repeated # dirtying of data, this can be way larger than # memory_total. Best to just look at what's # remaining to copy and ignore what's done already # # TODO(berrange) perhaps we could include disk # transfer stats in the progress too, but it # might make memory info more obscure as large # disk sizes might dwarf memory size remaining = 100 if info.memory_total != 0: remaining = round(info.memory_remaining * 100 / info.memory_total) libvirt_migrate.save_stats(instance, migration, info, remaining) lg = LOG.debug if (n % 60) == 0: lg = LOG.info lg(_LI("Migration running for %(secs)d secs, " "memory %(remaining)d%% remaining; " "(bytes processed=%(processed_memory)d, " "remaining=%(remaining_memory)d, " "total=%(total_memory)d)"), {"secs": n / 2, "remaining": remaining, "processed_memory": info.memory_processed, "remaining_memory": info.memory_remaining, "total_memory": info.memory_total}, instance=instance) if info.data_remaining > progress_watermark: lg(_LI("Data remaining %(remaining)d bytes, " "low watermark %(watermark)d bytes " "%(last)d seconds ago"), {"remaining": info.data_remaining, "watermark": progress_watermark, "last": (now - progress_time)}, instance=instance) n = n + 1 elif info.type == libvirt.VIR_DOMAIN_JOB_COMPLETED: # Migration is all done LOG.info(_LI("Migration operation has completed"), instance=instance) post_method(context, instance, dest, block_migration, migrate_data) break elif info.type == libvirt.VIR_DOMAIN_JOB_FAILED: # Migration did not succeed LOG.error(_LE("Migration operation has aborted"), instance=instance) libvirt_migrate.run_recover_tasks(self._host, guest, instance, on_migration_failure) recover_method(context, instance, dest, block_migration, migrate_data) break elif info.type == libvirt.VIR_DOMAIN_JOB_CANCELLED: # Migration was stopped by admin LOG.warning(_LW("Migration operation was cancelled"), instance=instance) libvirt_migrate.run_recover_tasks(self._host, guest, instance, on_migration_failure) recover_method(context, instance, dest, block_migration, migrate_data, migration_status='cancelled') break else: LOG.warning(_LW("Unexpected migration job type: %d"), info.type, instance=instance) time.sleep(0.5) self._clear_empty_migration(instance) def _clear_empty_migration(self, instance): try: del self.active_migrations[instance.uuid] except KeyError: LOG.warning(_LW("There are no records in active migrations " "for instance"), instance=instance) def _live_migration(self, context, instance, dest, post_method, recover_method, block_migration, migrate_data): """Do live migration. :param context: security context :param instance: nova.db.sqlalchemy.models.Instance object instance object that is migrated. :param dest: destination host :param post_method: post operation method. expected nova.compute.manager._post_live_migration. :param recover_method: recovery method when any exception occurs. expected nova.compute.manager._rollback_live_migration. :param block_migration: if true, do block migration. :param migrate_data: a LibvirtLiveMigrateData object This fires off a new thread to run the blocking migration operation, and then this thread monitors the progress of migration and controls its operation """ guest = self._host.get_guest(instance) disk_paths = [] device_names = [] if migrate_data.block_migration: disk_paths, device_names = self._live_migration_copy_disk_paths( context, instance, guest) opthread = utils.spawn(self._live_migration_operation, context, instance, dest, block_migration, migrate_data, guest, device_names) finish_event = eventlet.event.Event() self.active_migrations[instance.uuid] = deque() def thread_finished(thread, event): LOG.debug("Migration operation thread notification", instance=instance) event.send() opthread.link(thread_finished, finish_event) # Let eventlet schedule the new thread right away time.sleep(0) try: LOG.debug("Starting monitoring of live migration", instance=instance) self._live_migration_monitor(context, instance, guest, dest, post_method, recover_method, block_migration, migrate_data, finish_event, disk_paths) except Exception as ex: LOG.warning(_LW("Error monitoring migration: %(ex)s"), {"ex": ex}, instance=instance, exc_info=True) raise finally: LOG.debug("Live migration monitoring is all done", instance=instance) def _is_post_copy_enabled(self, migration_flags): if self._is_post_copy_available(): if (migration_flags & libvirt.VIR_MIGRATE_POSTCOPY) != 0: return True return False def live_migration_force_complete(self, instance): try: self.active_migrations[instance.uuid].append('force-complete') except KeyError: raise exception.NoActiveMigrationForInstance( instance_id=instance.uuid) def _try_fetch_image(self, context, path, image_id, instance, fallback_from_host=None): try: libvirt_utils.fetch_image(context, path, image_id) except exception.ImageNotFound: if not fallback_from_host: raise LOG.debug("Image %(image_id)s doesn't exist anymore on " "image service, attempting to copy image " "from %(host)s", {'image_id': image_id, 'host': fallback_from_host}) libvirt_utils.copy_image(src=path, dest=path, host=fallback_from_host, receive=True) def _fetch_instance_kernel_ramdisk(self, context, instance, fallback_from_host=None): """Download kernel and ramdisk for instance in instance directory.""" instance_dir = libvirt_utils.get_instance_path(instance) if instance.kernel_id: kernel_path = os.path.join(instance_dir, 'kernel') # NOTE(dsanders): only fetch image if it's not available at # kernel_path. This also avoids ImageNotFound exception if # the image has been deleted from glance if not os.path.exists(kernel_path): self._try_fetch_image(context, kernel_path, instance.kernel_id, instance, fallback_from_host) if instance.ramdisk_id: ramdisk_path = os.path.join(instance_dir, 'ramdisk') # NOTE(dsanders): only fetch image if it's not available at # ramdisk_path. This also avoids ImageNotFound exception if # the image has been deleted from glance if not os.path.exists(ramdisk_path): self._try_fetch_image(context, ramdisk_path, instance.ramdisk_id, instance, fallback_from_host) def rollback_live_migration_at_destination(self, context, instance, network_info, block_device_info, destroy_disks=True, migrate_data=None): """Clean up destination node after a failed live migration.""" try: self.destroy(context, instance, network_info, block_device_info, destroy_disks, migrate_data) finally: # NOTE(gcb): Failed block live migration may leave instance # directory at destination node, ensure it is always deleted. is_shared_instance_path = True if migrate_data: is_shared_instance_path = migrate_data.is_shared_instance_path if not is_shared_instance_path: instance_dir = libvirt_utils.get_instance_path_at_destination( instance, migrate_data) if os.path.exists(instance_dir): shutil.rmtree(instance_dir) def pre_live_migration(self, context, instance, block_device_info, network_info, disk_info, migrate_data): """Preparation live migration.""" if disk_info is not None: disk_info = jsonutils.loads(disk_info) LOG.debug('migrate_data in pre_live_migration: %s', migrate_data, instance=instance) is_shared_block_storage = migrate_data.is_shared_block_storage is_shared_instance_path = migrate_data.is_shared_instance_path is_block_migration = migrate_data.block_migration if not is_shared_instance_path: instance_dir = libvirt_utils.get_instance_path_at_destination( instance, migrate_data) if os.path.exists(instance_dir): raise exception.DestinationDiskExists(path=instance_dir) LOG.debug('Creating instance directory: %s', instance_dir, instance=instance) os.mkdir(instance_dir) # Recreate the disk.info file and in doing so stop the # imagebackend from recreating it incorrectly by inspecting the # contents of each file when using the Raw backend. if disk_info: image_disk_info = {} for info in disk_info: image_file = os.path.basename(info['path']) image_path = os.path.join(instance_dir, image_file) image_disk_info[image_path] = info['type'] LOG.debug('Creating disk.info with the contents: %s', image_disk_info, instance=instance) image_disk_info_path = os.path.join(instance_dir, 'disk.info') libvirt_utils.write_to_file(image_disk_info_path, jsonutils.dumps(image_disk_info)) if not is_shared_block_storage: # Ensure images and backing files are present. LOG.debug('Checking to make sure images and backing files are ' 'present before live migration.', instance=instance) self._create_images_and_backing( context, instance, instance_dir, disk_info, fallback_from_host=instance.host) if (configdrive.required_by(instance) and CONF.config_drive_format == 'iso9660'): # NOTE(pkoniszewski): Due to a bug in libvirt iso config # drive needs to be copied to destination prior to # migration when instance path is not shared and block # storage is not shared. Files that are already present # on destination are excluded from a list of files that # need to be copied to destination. If we don't do that # live migration will fail on copying iso config drive to # destination and writing to read-only device. # Please see bug/1246201 for more details. src = "%s:%s/disk.config" % (instance.host, instance_dir) self._remotefs.copy_file(src, instance_dir) if not is_block_migration: # NOTE(angdraug): when block storage is shared between source # and destination and instance path isn't (e.g. volume backed # or rbd backed instance), instance path on destination has to # be prepared # Required by Quobyte CI self._ensure_console_log_for_instance(instance) # if image has kernel and ramdisk, just download # following normal way. self._fetch_instance_kernel_ramdisk(context, instance) # Establishing connection to volume server. block_device_mapping = driver.block_device_info_get_mapping( block_device_info) if len(block_device_mapping): LOG.debug('Connecting volumes before live migration.', instance=instance) for bdm in block_device_mapping: connection_info = bdm['connection_info'] disk_info = blockinfo.get_info_from_bdm( instance, CONF.libvirt.virt_type, instance.image_meta, bdm) self._connect_volume(connection_info, disk_info) # We call plug_vifs before the compute manager calls # ensure_filtering_rules_for_instance, to ensure bridge is set up # Retry operation is necessary because continuously request comes, # concurrent request occurs to iptables, then it complains. LOG.debug('Plugging VIFs before live migration.', instance=instance) max_retry = CONF.live_migration_retry_count for cnt in range(max_retry): try: self.plug_vifs(instance, network_info) break except processutils.ProcessExecutionError: if cnt == max_retry - 1: raise else: LOG.warning(_LW('plug_vifs() failed %(cnt)d. Retry up to ' '%(max_retry)d.'), {'cnt': cnt, 'max_retry': max_retry}, instance=instance) greenthread.sleep(1) # Store vncserver_listen and latest disk device info if not migrate_data: migrate_data = objects.LibvirtLiveMigrateData(bdms=[]) else: migrate_data.bdms = [] migrate_data.graphics_listen_addr_vnc = CONF.vnc.vncserver_listen migrate_data.graphics_listen_addr_spice = CONF.spice.server_listen migrate_data.serial_listen_addr = \ CONF.serial_console.proxyclient_address # Store live_migration_inbound_addr migrate_data.target_connect_addr = \ CONF.libvirt.live_migration_inbound_addr migrate_data.supported_perf_events = self._supported_perf_events for vol in block_device_mapping: connection_info = vol['connection_info'] if connection_info.get('serial'): disk_info = blockinfo.get_info_from_bdm( instance, CONF.libvirt.virt_type, instance.image_meta, vol) bdmi = objects.LibvirtLiveMigrateBDMInfo() bdmi.serial = connection_info['serial'] bdmi.connection_info = connection_info bdmi.bus = disk_info['bus'] bdmi.dev = disk_info['dev'] bdmi.type = disk_info['type'] bdmi.format = disk_info.get('format') bdmi.boot_index = disk_info.get('boot_index') migrate_data.bdms.append(bdmi) return migrate_data def _try_fetch_image_cache(self, image, fetch_func, context, filename, image_id, instance, size, fallback_from_host=None): try: image.cache(fetch_func=fetch_func, context=context, filename=filename, image_id=image_id, size=size) except exception.ImageNotFound: if not fallback_from_host: raise LOG.debug("Image %(image_id)s doesn't exist anymore " "on image service, attempting to copy " "image from %(host)s", {'image_id': image_id, 'host': fallback_from_host}, instance=instance) def copy_from_host(target): libvirt_utils.copy_image(src=target, dest=target, host=fallback_from_host, receive=True) image.cache(fetch_func=copy_from_host, filename=filename) def _create_images_and_backing(self, context, instance, instance_dir, disk_info, fallback_from_host=None): """:param context: security context :param instance: nova.db.sqlalchemy.models.Instance object instance object that is migrated. :param instance_dir: instance path to use, calculated externally to handle block migrating an instance with an old style instance path :param disk_info: disk info specified in _get_instance_disk_info (list of dicts) :param fallback_from_host: host where we can retrieve images if the glance images are not available. """ if not disk_info: disk_info = [] for info in disk_info: base = os.path.basename(info['path']) # Get image type and create empty disk image, and # create backing file in case of qcow2. instance_disk = os.path.join(instance_dir, base) if not info['backing_file'] and not os.path.exists(instance_disk): libvirt_utils.create_image(info['type'], instance_disk, info['virt_disk_size']) elif info['backing_file']: # Creating backing file follows same way as spawning instances. cache_name = os.path.basename(info['backing_file']) image = self.image_backend.image(instance, instance_disk, CONF.libvirt.images_type) if cache_name.startswith('ephemeral'): # The argument 'size' is used by image.cache to # validate disk size retrieved from cache against # the instance disk size (should always return OK) # and ephemeral_size is used by _create_ephemeral # to build the image if the disk is not already # cached. image.cache( fetch_func=self._create_ephemeral, fs_label=cache_name, os_type=instance.os_type, filename=cache_name, size=info['virt_disk_size'], ephemeral_size=info['virt_disk_size'] / units.Gi) elif cache_name.startswith('swap'): inst_type = instance.get_flavor() swap_mb = inst_type.swap image.cache(fetch_func=self._create_swap, filename="swap_%s" % swap_mb, size=swap_mb * units.Mi, swap_mb=swap_mb) else: self._try_fetch_image_cache(image, libvirt_utils.fetch_image, context, cache_name, instance.image_ref, instance, info['virt_disk_size'], fallback_from_host) # if image has kernel and ramdisk, just download # following normal way. self._fetch_instance_kernel_ramdisk( context, instance, fallback_from_host=fallback_from_host) def post_live_migration(self, context, instance, block_device_info, migrate_data=None): # Disconnect from volume server block_device_mapping = driver.block_device_info_get_mapping( block_device_info) connector = self.get_volume_connector(instance) volume_api = self._volume_api for vol in block_device_mapping: # Retrieve connection info from Cinder's initialize_connection API. # The info returned will be accurate for the source server. volume_id = vol['connection_info']['serial'] connection_info = volume_api.initialize_connection(context, volume_id, connector) # TODO(leeantho) The following multipath_id logic is temporary # and will be removed in the future once os-brick is updated # to handle multipath for drivers in a more efficient way. # For now this logic is needed to ensure the connection info # data is correct. # Pull out multipath_id from the bdm information. The # multipath_id can be placed into the connection info # because it is based off of the volume and will be the # same on the source and destination hosts. if 'multipath_id' in vol['connection_info']['data']: multipath_id = vol['connection_info']['data']['multipath_id'] connection_info['data']['multipath_id'] = multipath_id disk_dev = vol['mount_device'].rpartition("/")[2] self._disconnect_volume(connection_info, disk_dev) def post_live_migration_at_source(self, context, instance, network_info): """Unplug VIFs from networks at source. :param context: security context :param instance: instance object reference :param network_info: instance network information """ self.unplug_vifs(instance, network_info) def post_live_migration_at_destination(self, context, instance, network_info, block_migration=False, block_device_info=None): """Post operation of live migration at destination host. :param context: security context :param instance: nova.db.sqlalchemy.models.Instance object instance object that is migrated. :param network_info: instance network information :param block_migration: if true, post operation of block_migration. """ # Define migrated instance, otherwise, suspend/destroy does not work. # In case of block migration, destination does not have # libvirt.xml disk_info = blockinfo.get_disk_info( CONF.libvirt.virt_type, instance, instance.image_meta, block_device_info) xml = self._get_guest_xml(context, instance, network_info, disk_info, instance.image_meta, block_device_info=block_device_info, write_to_disk=True) self._host.write_instance_config(xml) def _get_instance_disk_info(self, instance_name, xml, block_device_info=None): """Get the non-volume disk information from the domain xml :param str instance_name: the name of the instance (domain) :param str xml: the libvirt domain xml for the instance :param dict block_device_info: block device info for BDMs :returns disk_info: list of dicts with keys: * 'type': the disk type (str) * 'path': the disk path (str) * 'virt_disk_size': the virtual disk size (int) * 'backing_file': backing file of a disk image (str) * 'disk_size': physical disk size (int) * 'over_committed_disk_size': virt_disk_size - disk_size or 0 """ block_device_mapping = driver.block_device_info_get_mapping( block_device_info) volume_devices = set() for vol in block_device_mapping: disk_dev = vol['mount_device'].rpartition("/")[2] volume_devices.add(disk_dev) disk_info = [] doc = etree.fromstring(xml) def find_nodes(doc, device_type): return (doc.findall('.//devices/%s' % device_type), doc.findall('.//devices/%s/source' % device_type), doc.findall('.//devices/%s/driver' % device_type), doc.findall('.//devices/%s/target' % device_type)) if (CONF.libvirt.virt_type == 'parallels' and doc.find('os/type').text == vm_mode.EXE): node_type = 'filesystem' else: node_type = 'disk' (disk_nodes, path_nodes, driver_nodes, target_nodes) = find_nodes(doc, node_type) for cnt, path_node in enumerate(path_nodes): disk_type = disk_nodes[cnt].get('type') path = path_node.get('file') or path_node.get('dev') if (node_type == 'filesystem'): target = target_nodes[cnt].attrib['dir'] else: target = target_nodes[cnt].attrib['dev'] if not path: LOG.debug('skipping disk for %s as it does not have a path', instance_name) continue if disk_type not in ['file', 'block']: LOG.debug('skipping disk because it looks like a volume', path) continue if target in volume_devices: LOG.debug('skipping disk %(path)s (%(target)s) as it is a ' 'volume', {'path': path, 'target': target}) continue # get the real disk size or # raise a localized error if image is unavailable if disk_type == 'file': if driver_nodes[cnt].get('type') == 'ploop': dk_size = 0 for dirpath, dirnames, filenames in os.walk(path): for f in filenames: fp = os.path.join(dirpath, f) dk_size += os.path.getsize(fp) else: dk_size = int(os.path.getsize(path)) elif disk_type == 'block' and block_device_info: dk_size = lvm.get_volume_size(path) else: LOG.debug('skipping disk %(path)s (%(target)s) - unable to ' 'determine if volume', {'path': path, 'target': target}) continue disk_type = driver_nodes[cnt].get('type') if disk_type in ("qcow2", "ploop"): backing_file = libvirt_utils.get_disk_backing_file(path) virt_size = disk_api.get_disk_size(path) over_commit_size = int(virt_size) - dk_size else: backing_file = "" virt_size = dk_size over_commit_size = 0 disk_info.append({'type': disk_type, 'path': path, 'virt_disk_size': virt_size, 'backing_file': backing_file, 'disk_size': dk_size, 'over_committed_disk_size': over_commit_size}) return disk_info def get_instance_disk_info(self, instance, block_device_info=None): try: guest = self._host.get_guest(instance) xml = guest.get_xml_desc() except libvirt.libvirtError as ex: error_code = ex.get_error_code() LOG.warning(_LW('Error from libvirt while getting description of ' '%(instance_name)s: [Error Code %(error_code)s] ' '%(ex)s'), {'instance_name': instance.name, 'error_code': error_code, 'ex': ex}, instance=instance) raise exception.InstanceNotFound(instance_id=instance.uuid) return jsonutils.dumps( self._get_instance_disk_info(instance.name, xml, block_device_info)) def _get_disk_over_committed_size_total(self): """Return total over committed disk size for all instances.""" # Disk size that all instance uses : virtual_size - disk_size disk_over_committed_size = 0 instance_domains = self._host.list_instance_domains() if not instance_domains: return disk_over_committed_size # Get all instance uuids instance_uuids = [dom.UUIDString() for dom in instance_domains] ctx = nova_context.get_admin_context() # Get instance object list by uuid filter filters = {'uuid': instance_uuids} # NOTE(ankit): objects.InstanceList.get_by_filters method is # getting called twice one is here and another in the # _update_available_resource method of resource_tracker. Since # _update_available_resource method is synchronized, there is a # possibility the instances list retrieved here to calculate # disk_over_committed_size would differ to the list you would get # in _update_available_resource method for calculating usages based # on instance utilization. local_instance_list = objects.InstanceList.get_by_filters( ctx, filters, use_slave=True) # Convert instance list to dictionary with instace uuid as key. local_instances = {inst.uuid: inst for inst in local_instance_list} # Get bdms by instance uuids bdms = objects.BlockDeviceMappingList.bdms_by_instance_uuid( ctx, instance_uuids) for dom in instance_domains: try: guest = libvirt_guest.Guest(dom) xml = guest.get_xml_desc() block_device_info = None if guest.uuid in local_instances \ and (bdms and guest.uuid in bdms): # Get block device info for instance block_device_info = driver.get_block_device_info( local_instances[guest.uuid], bdms[guest.uuid]) disk_infos = self._get_instance_disk_info(guest.name, xml, block_device_info=block_device_info) if not disk_infos: continue for info in disk_infos: disk_over_committed_size += int( info['over_committed_disk_size']) except libvirt.libvirtError as ex: error_code = ex.get_error_code() LOG.warning(_LW( 'Error from libvirt while getting description of ' '%(instance_name)s: [Error Code %(error_code)s] %(ex)s' ), {'instance_name': guest.name, 'error_code': error_code, 'ex': ex}) except OSError as e: if e.errno in (errno.ENOENT, errno.ESTALE): LOG.warning(_LW('Periodic task is updating the host stat, ' 'it is trying to get disk %(i_name)s, ' 'but disk file was removed by concurrent ' 'operations such as resize.'), {'i_name': guest.name}) elif e.errno == errno.EACCES: LOG.warning(_LW('Periodic task is updating the host stat, ' 'it is trying to get disk %(i_name)s, ' 'but access is denied. It is most likely ' 'due to a VM that exists on the compute ' 'node but is not managed by Nova.'), {'i_name': guest.name}) else: raise except exception.VolumeBDMPathNotFound as e: LOG.warning(_LW('Periodic task is updating the host stats, ' 'it is trying to get disk info for %(i_name)s, ' 'but the backing volume block device was removed ' 'by concurrent operations such as resize. ' 'Error: %(error)s'), {'i_name': guest.name, 'error': e}) # NOTE(gtt116): give other tasks a chance. greenthread.sleep(0) return disk_over_committed_size def unfilter_instance(self, instance, network_info): """See comments of same method in firewall_driver.""" self.firewall_driver.unfilter_instance(instance, network_info=network_info) def get_available_nodes(self, refresh=False): return [self._host.get_hostname()] def get_host_cpu_stats(self): """Return the current CPU state of the host.""" return self._host.get_cpu_stats() def get_host_uptime(self): """Returns the result of calling "uptime".""" out, err = utils.execute('env', 'LANG=C', 'uptime') return out def manage_image_cache(self, context, all_instances): """Manage the local cache of images.""" self.image_cache_manager.update(context, all_instances) def _cleanup_remote_migration(self, dest, inst_base, inst_base_resize, shared_storage=False): """Used only for cleanup in case migrate_disk_and_power_off fails.""" try: if os.path.exists(inst_base_resize): utils.execute('rm', '-rf', inst_base) utils.execute('mv', inst_base_resize, inst_base) if not shared_storage: self._remotefs.remove_dir(dest, inst_base) except Exception: pass def _is_storage_shared_with(self, dest, inst_base): # NOTE (rmk): There are two methods of determining whether we are # on the same filesystem: the source and dest IP are the # same, or we create a file on the dest system via SSH # and check whether the source system can also see it. # NOTE (drwahl): Actually, there is a 3rd way: if images_type is rbd, # it will always be shared storage if CONF.libvirt.images_type == 'rbd': return True shared_storage = (dest == self.get_host_ip_addr()) if not shared_storage: tmp_file = uuid.uuid4().hex + '.tmp' tmp_path = os.path.join(inst_base, tmp_file) try: self._remotefs.create_file(dest, tmp_path) if os.path.exists(tmp_path): shared_storage = True os.unlink(tmp_path) else: self._remotefs.remove_file(dest, tmp_path) except Exception: pass return shared_storage def migrate_disk_and_power_off(self, context, instance, dest, flavor, network_info, block_device_info=None, timeout=0, retry_interval=0): LOG.debug("Starting migrate_disk_and_power_off", instance=instance) ephemerals = driver.block_device_info_get_ephemerals(block_device_info) # get_bdm_ephemeral_disk_size() will return 0 if the new # instance's requested block device mapping contain no # ephemeral devices. However, we still want to check if # the original instance's ephemeral_gb property was set and # ensure that the new requested flavor ephemeral size is greater eph_size = (block_device.get_bdm_ephemeral_disk_size(ephemerals) or instance.flavor.ephemeral_gb) # Checks if the migration needs a disk resize down. root_down = flavor.root_gb < instance.flavor.root_gb ephemeral_down = flavor.ephemeral_gb < eph_size disk_info_text = self.get_instance_disk_info( instance, block_device_info=block_device_info) booted_from_volume = self._is_booted_from_volume(instance, disk_info_text) if (root_down and not booted_from_volume) or ephemeral_down: reason = _("Unable to resize disk down.") raise exception.InstanceFaultRollback( exception.ResizeError(reason=reason)) disk_info = jsonutils.loads(disk_info_text) # NOTE(dgenin): Migration is not implemented for LVM backed instances. if CONF.libvirt.images_type == 'lvm' and not booted_from_volume: reason = _("Migration is not supported for LVM backed instances") raise exception.InstanceFaultRollback( exception.MigrationPreCheckError(reason=reason)) # copy disks to destination # rename instance dir to +_resize at first for using # shared storage for instance dir (eg. NFS). inst_base = libvirt_utils.get_instance_path(instance) inst_base_resize = inst_base + "_resize" shared_storage = self._is_storage_shared_with(dest, inst_base) # try to create the directory on the remote compute node # if this fails we pass the exception up the stack so we can catch # failures here earlier if not shared_storage: try: self._remotefs.create_dir(dest, inst_base) except processutils.ProcessExecutionError as e: reason = _("not able to execute ssh command: %s") % e raise exception.InstanceFaultRollback( exception.ResizeError(reason=reason)) self.power_off(instance, timeout, retry_interval) block_device_mapping = driver.block_device_info_get_mapping( block_device_info) for vol in block_device_mapping: connection_info = vol['connection_info'] disk_dev = vol['mount_device'].rpartition("/")[2] self._disconnect_volume(connection_info, disk_dev) try: utils.execute('mv', inst_base, inst_base_resize) # if we are migrating the instance with shared storage then # create the directory. If it is a remote node the directory # has already been created if shared_storage: dest = None utils.execute('mkdir', '-p', inst_base) on_execute = lambda process: \ self.job_tracker.add_job(instance, process.pid) on_completion = lambda process: \ self.job_tracker.remove_job(instance, process.pid) active_flavor = instance.get_flavor() for info in disk_info: # assume inst_base == dirname(info['path']) img_path = info['path'] fname = os.path.basename(img_path) from_path = os.path.join(inst_base_resize, fname) # To properly resize the swap partition, it must be # re-created with the proper size. This is acceptable # because when an OS is shut down, the contents of the # swap space are just garbage, the OS doesn't bother about # what is in it. # We will not copy over the swap disk here, and rely on # finish_migration/_create_image to re-create it for us. if not (fname == 'disk.swap' and active_flavor.get('swap', 0) != flavor.get('swap', 0)): compression = info['type'] not in NO_COMPRESSION_TYPES libvirt_utils.copy_image(from_path, img_path, host=dest, on_execute=on_execute, on_completion=on_completion, compression=compression) # Ensure disk.info is written to the new path to avoid disks being # reinspected and potentially changing format. src_disk_info_path = os.path.join(inst_base_resize, 'disk.info') if os.path.exists(src_disk_info_path): dst_disk_info_path = os.path.join(inst_base, 'disk.info') libvirt_utils.copy_image(src_disk_info_path, dst_disk_info_path, host=dest, on_execute=on_execute, on_completion=on_completion) except Exception: with excutils.save_and_reraise_exception(): self._cleanup_remote_migration(dest, inst_base, inst_base_resize, shared_storage) return disk_info_text def _wait_for_running(self, instance): state = self.get_info(instance).state if state == power_state.RUNNING: LOG.info(_LI("Instance running successfully."), instance=instance) raise loopingcall.LoopingCallDone() @staticmethod def _disk_size_from_instance(instance, disk_name): """Determines the disk size from instance properties Returns the disk size by using the disk name to determine whether it is a root or an ephemeral disk, then by checking properties of the instance returns the size converted to bytes. Returns 0 if the disk name not match (disk, disk.local). """ if disk_name == 'disk': size = instance.flavor.root_gb elif disk_name == 'disk.local': size = instance.flavor.ephemeral_gb # N.B. We don't handle ephemeral disks named disk.ephN here, # which is almost certainly a bug. It's not clear what this function # should return if an instance has multiple ephemeral disks. else: size = 0 return size * units.Gi @staticmethod def _disk_raw_to_qcow2(path): """Converts a raw disk to qcow2.""" path_qcow = path + '_qcow' utils.execute('qemu-img', 'convert', '-f', 'raw', '-O', 'qcow2', path, path_qcow) utils.execute('mv', path_qcow, path) @staticmethod def _disk_qcow2_to_raw(path): """Converts a qcow2 disk to raw.""" path_raw = path + '_raw' utils.execute('qemu-img', 'convert', '-f', 'qcow2', '-O', 'raw', path, path_raw) utils.execute('mv', path_raw, path) def _disk_resize(self, image, size): """Attempts to resize a disk to size :param image: an instance of nova.virt.image.model.Image Attempts to resize a disk by checking the capabilities and preparing the format, then calling disk.api.extend. Note: Currently only support disk extend. """ if not isinstance(image, imgmodel.LocalFileImage): LOG.debug("Skipping resize of non-local image") return # If we have a non partitioned image that we can extend # then ensure we're in 'raw' format so we can extend file system. converted = False if (size and image.format == imgmodel.FORMAT_QCOW2 and disk_api.can_resize_image(image.path, size) and disk_api.is_image_extendable(image)): self._disk_qcow2_to_raw(image.path) converted = True image = imgmodel.LocalFileImage(image.path, imgmodel.FORMAT_RAW) if size: disk_api.extend(image, size) if converted: # back to qcow2 (no backing_file though) so that snapshot # will be available self._disk_raw_to_qcow2(image.path) def finish_migration(self, context, migration, instance, disk_info, network_info, image_meta, resize_instance, block_device_info=None, power_on=True): LOG.debug("Starting finish_migration", instance=instance) block_disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance, image_meta, block_device_info) # assume _create_image does nothing if a target file exists. # NOTE: This has the intended side-effect of fetching a missing # backing file. self._create_image(context, instance, block_disk_info['mapping'], network_info=network_info, block_device_info=None, inject_files=False, fallback_from_host=migration.source_compute) # Required by Quobyte CI self._ensure_console_log_for_instance(instance) gen_confdrive = functools.partial(self._create_configdrive, context, instance, network_info=network_info) # Resize root disk and a single ephemeral disk called disk.local # Also convert raw disks to qcow2 if migrating to host which uses # qcow2 from host which uses raw. # TODO(mbooth): Handle resize of multiple ephemeral disks, and # ephemeral disks not called disk.local. disk_info = jsonutils.loads(disk_info) for info in disk_info: path = info['path'] disk_name = os.path.basename(path) size = self._disk_size_from_instance(instance, disk_name) if resize_instance: image = imgmodel.LocalFileImage(path, info['type']) self._disk_resize(image, size) # NOTE(mdbooth): The code below looks wrong, but is actually # required to prevent a security hole when migrating from a host # with use_cow_images=False to one with use_cow_images=True. # Imagebackend uses use_cow_images to select between the # atrociously-named-Raw and Qcow2 backends. The Qcow2 backend # writes to disk.info, but does not read it as it assumes qcow2. # Therefore if we don't convert raw to qcow2 here, a raw disk will # be incorrectly assumed to be qcow2, which is a severe security # flaw. The reverse is not true, because the atrociously-named-Raw # backend supports both qcow2 and raw disks, and will choose # appropriately between them as long as disk.info exists and is # correctly populated, which it is because Qcow2 writes to # disk.info. # # In general, we do not yet support format conversion during # migration. For example: # * Converting from use_cow_images=True to use_cow_images=False # isn't handled. This isn't a security bug, but is almost # certainly buggy in other cases, as the 'Raw' backend doesn't # expect a backing file. # * Converting to/from lvm and rbd backends is not supported. # # This behaviour is inconsistent, and therefore undesirable for # users. It is tightly-coupled to implementation quirks of 2 # out of 5 backends in imagebackend and defends against a severe # security flaw which is not at all obvious without deep analysis, # and is therefore undesirable to developers. We should aim to # remove it. This will not be possible, though, until we can # represent the storage layout of a specific instance # independent of the default configuration of the local compute # host. # Config disks are hard-coded to be raw even when # use_cow_images=True (see _get_disk_config_image_type),so don't # need to be converted. if (disk_name != 'disk.config' and info['type'] == 'raw' and CONF.use_cow_images): self._disk_raw_to_qcow2(info['path']) xml = self._get_guest_xml(context, instance, network_info, block_disk_info, image_meta, block_device_info=block_device_info, write_to_disk=True) # NOTE(mriedem): vifs_already_plugged=True here, regardless of whether # or not we've migrated to another host, because we unplug VIFs locally # and the status change in the port might go undetected by the neutron # L2 agent (or neutron server) so neutron may not know that the VIF was # unplugged in the first place and never send an event. self._create_domain_and_network(context, xml, instance, network_info, block_disk_info, block_device_info=block_device_info, power_on=power_on, vifs_already_plugged=True, post_xml_callback=gen_confdrive) if power_on: timer = loopingcall.FixedIntervalLoopingCall( self._wait_for_running, instance) timer.start(interval=0.5).wait() LOG.debug("finish_migration finished successfully.", instance=instance) def _cleanup_failed_migration(self, inst_base): """Make sure that a failed migrate doesn't prevent us from rolling back in a revert. """ try: shutil.rmtree(inst_base) except OSError as e: if e.errno != errno.ENOENT: raise def finish_revert_migration(self, context, instance, network_info, block_device_info=None, power_on=True): LOG.debug("Starting finish_revert_migration", instance=instance) inst_base = libvirt_utils.get_instance_path(instance) inst_base_resize = inst_base + "_resize" # NOTE(danms): if we're recovering from a failed migration, # make sure we don't have a left-over same-host base directory # that would conflict. Also, don't fail on the rename if the # failure happened early. if os.path.exists(inst_base_resize): self._cleanup_failed_migration(inst_base) utils.execute('mv', inst_base_resize, inst_base) root_disk = self.image_backend.image(instance, 'disk') # Once we rollback, the snapshot is no longer needed, so remove it # TODO(nic): Remove the try/except/finally in a future release # To avoid any upgrade issues surrounding instances being in pending # resize state when the software is updated, this portion of the # method logs exceptions rather than failing on them. Once it can be # reasonably assumed that no such instances exist in the wild # anymore, the try/except/finally should be removed, # and ignore_errors should be set back to False (the default) so # that problems throw errors, like they should. if root_disk.exists(): try: root_disk.rollback_to_snap(libvirt_utils.RESIZE_SNAPSHOT_NAME) except exception.SnapshotNotFound: LOG.warning(_LW("Failed to rollback snapshot (%s)"), libvirt_utils.RESIZE_SNAPSHOT_NAME) finally: root_disk.remove_snap(libvirt_utils.RESIZE_SNAPSHOT_NAME, ignore_errors=True) disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance, instance.image_meta, block_device_info) xml = self._get_guest_xml(context, instance, network_info, disk_info, instance.image_meta, block_device_info=block_device_info) self._create_domain_and_network(context, xml, instance, network_info, disk_info, block_device_info=block_device_info, power_on=power_on, vifs_already_plugged=True) if power_on: timer = loopingcall.FixedIntervalLoopingCall( self._wait_for_running, instance) timer.start(interval=0.5).wait() LOG.debug("finish_revert_migration finished successfully.", instance=instance) def confirm_migration(self, migration, instance, network_info): """Confirms a resize, destroying the source VM.""" self._cleanup_resize(instance, network_info) @staticmethod def _get_io_devices(xml_doc): """get the list of io devices from the xml document.""" result = {"volumes": [], "ifaces": []} try: doc = etree.fromstring(xml_doc) except Exception: return result blocks = [('./devices/disk', 'volumes'), ('./devices/interface', 'ifaces')] for block, key in blocks: section = doc.findall(block) for node in section: for child in node.getchildren(): if child.tag == 'target' and child.get('dev'): result[key].append(child.get('dev')) return result def get_diagnostics(self, instance): guest = self._host.get_guest(instance) # TODO(sahid): We are converting all calls from a # virDomain object to use nova.virt.libvirt.Guest. # We should be able to remove domain at the end. domain = guest._domain output = {} # get cpu time, might launch an exception if the method # is not supported by the underlying hypervisor being # used by libvirt try: for vcpu in guest.get_vcpus_info(): output["cpu" + str(vcpu.id) + "_time"] = vcpu.time except libvirt.libvirtError: pass # get io status xml = guest.get_xml_desc() dom_io = LibvirtDriver._get_io_devices(xml) for guest_disk in dom_io["volumes"]: try: # blockStats might launch an exception if the method # is not supported by the underlying hypervisor being # used by libvirt stats = domain.blockStats(guest_disk) output[guest_disk + "_read_req"] = stats[0] output[guest_disk + "_read"] = stats[1] output[guest_disk + "_write_req"] = stats[2] output[guest_disk + "_write"] = stats[3] output[guest_disk + "_errors"] = stats[4] except libvirt.libvirtError: pass for interface in dom_io["ifaces"]: try: # interfaceStats might launch an exception if the method # is not supported by the underlying hypervisor being # used by libvirt stats = domain.interfaceStats(interface) output[interface + "_rx"] = stats[0] output[interface + "_rx_packets"] = stats[1] output[interface + "_rx_errors"] = stats[2] output[interface + "_rx_drop"] = stats[3] output[interface + "_tx"] = stats[4] output[interface + "_tx_packets"] = stats[5] output[interface + "_tx_errors"] = stats[6] output[interface + "_tx_drop"] = stats[7] except libvirt.libvirtError: pass output["memory"] = domain.maxMemory() # memoryStats might launch an exception if the method # is not supported by the underlying hypervisor being # used by libvirt try: mem = domain.memoryStats() for key in mem.keys(): output["memory-" + key] = mem[key] except (libvirt.libvirtError, AttributeError): pass return output def get_instance_diagnostics(self, instance): guest = self._host.get_guest(instance) # TODO(sahid): We are converting all calls from a # virDomain object to use nova.virt.libvirt.Guest. # We should be able to remove domain at the end. domain = guest._domain xml = guest.get_xml_desc() xml_doc = etree.fromstring(xml) # TODO(sahid): Needs to use get_info but more changes have to # be done since a mapping STATE_MAP LIBVIRT_POWER_STATE is # needed. (state, max_mem, mem, num_cpu, cpu_time) = \ guest._get_domain_info(self._host) config_drive = configdrive.required_by(instance) launched_at = timeutils.normalize_time(instance.launched_at) uptime = timeutils.delta_seconds(launched_at, timeutils.utcnow()) diags = diagnostics.Diagnostics(state=power_state.STATE_MAP[state], driver='libvirt', config_drive=config_drive, hypervisor_os='linux', uptime=uptime) diags.memory_details.maximum = max_mem / units.Mi diags.memory_details.used = mem / units.Mi # get cpu time, might launch an exception if the method # is not supported by the underlying hypervisor being # used by libvirt try: for vcpu in guest.get_vcpus_info(): diags.add_cpu(time=vcpu.time) except libvirt.libvirtError: pass # get io status dom_io = LibvirtDriver._get_io_devices(xml) for guest_disk in dom_io["volumes"]: try: # blockStats might launch an exception if the method # is not supported by the underlying hypervisor being # used by libvirt stats = domain.blockStats(guest_disk) diags.add_disk(read_bytes=stats[1], read_requests=stats[0], write_bytes=stats[3], write_requests=stats[2]) except libvirt.libvirtError: pass for interface in dom_io["ifaces"]: try: # interfaceStats might launch an exception if the method # is not supported by the underlying hypervisor being # used by libvirt stats = domain.interfaceStats(interface) diags.add_nic(rx_octets=stats[0], rx_errors=stats[2], rx_drop=stats[3], rx_packets=stats[1], tx_octets=stats[4], tx_errors=stats[6], tx_drop=stats[7], tx_packets=stats[5]) except libvirt.libvirtError: pass # Update mac addresses of interface if stats have been reported if diags.nic_details: nodes = xml_doc.findall('./devices/interface/mac') for index, node in enumerate(nodes): diags.nic_details[index].mac_address = node.get('address') return diags @staticmethod def _prepare_device_bus(dev): """Determins the device bus and it's hypervisor assigned address """ bus = None address = (dev.device_addr.format_address() if dev.device_addr else None) if isinstance(dev.device_addr, vconfig.LibvirtConfigGuestDeviceAddressPCI): bus = objects.PCIDeviceBus() elif isinstance(dev, vconfig.LibvirtConfigGuestDisk): if dev.target_bus == 'scsi': bus = objects.SCSIDeviceBus() elif dev.target_bus == 'ide': bus = objects.IDEDeviceBus() elif dev.target_bus == 'usb': bus = objects.USBDeviceBus() if address is not None and bus is not None: bus.address = address return bus def _build_device_metadata(self, context, instance): """Builds a metadata object for instance devices, that maps the user provided tag to the hypervisor assigned device address. """ def _get_device_name(bdm): return block_device.strip_dev(bdm.device_name) vifs = objects.VirtualInterfaceList.get_by_instance_uuid(context, instance.uuid) tagged_vifs = {vif.address: vif for vif in vifs if vif.tag} # TODO(mriedem): We should be able to avoid the DB query here by using # block_device_info['block_device_mapping'] which is passed into most # methods that call this function. bdms = objects.BlockDeviceMappingList.get_by_instance_uuid( context, instance.uuid) tagged_bdms = {_get_device_name(bdm): bdm for bdm in bdms if bdm.tag} devices = [] guest = self._host.get_guest(instance) xml = guest.get_xml_desc() xml_dom = etree.fromstring(xml) guest_config = vconfig.LibvirtConfigGuest() guest_config.parse_dom(xml_dom) for dev in guest_config.devices: # Build network intefaces related metedata if isinstance(dev, vconfig.LibvirtConfigGuestInterface): vif = tagged_vifs.get(dev.mac_addr) if not vif: continue bus = self._prepare_device_bus(dev) device = objects.NetworkInterfaceMetadata( mac=vif.address, tags=[vif.tag] ) if bus: device.bus = bus devices.append(device) # Build disks related metedata if isinstance(dev, vconfig.LibvirtConfigGuestDisk): bdm = tagged_bdms.get(dev.target_dev) if not bdm: continue bus = self._prepare_device_bus(dev) device = objects.DiskMetadata(tags=[bdm.tag]) if bus: device.bus = bus devices.append(device) if devices: dev_meta = objects.InstanceDeviceMetadata(devices=devices) return dev_meta def instance_on_disk(self, instance): # ensure directories exist and are writable instance_path = libvirt_utils.get_instance_path(instance) LOG.debug('Checking instance files accessibility %s', instance_path, instance=instance) shared_instance_path = os.access(instance_path, os.W_OK) # NOTE(flwang): For shared block storage scenario, the file system is # not really shared by the two hosts, but the volume of evacuated # instance is reachable. shared_block_storage = (self.image_backend.backend(). is_shared_block_storage()) return shared_instance_path or shared_block_storage def inject_network_info(self, instance, nw_info): self.firewall_driver.setup_basic_filtering(instance, nw_info) def delete_instance_files(self, instance): target = libvirt_utils.get_instance_path(instance) # A resize may be in progress target_resize = target + '_resize' # Other threads may attempt to rename the path, so renaming the path # to target + '_del' (because it is atomic) and iterating through # twice in the unlikely event that a concurrent rename occurs between # the two rename attempts in this method. In general this method # should be fairly thread-safe without these additional checks, since # other operations involving renames are not permitted when the task # state is not None and the task state should be set to something # other than None by the time this method is invoked. target_del = target + '_del' for i in six.moves.range(2): try: utils.execute('mv', target, target_del) break except Exception: pass try: utils.execute('mv', target_resize, target_del) break except Exception: pass # Either the target or target_resize path may still exist if all # rename attempts failed. remaining_path = None for p in (target, target_resize): if os.path.exists(p): remaining_path = p break # A previous delete attempt may have been interrupted, so target_del # may exist even if all rename attempts during the present method # invocation failed due to the absence of both target and # target_resize. if not remaining_path and os.path.exists(target_del): self.job_tracker.terminate_jobs(instance) LOG.info(_LI('Deleting instance files %s'), target_del, instance=instance) remaining_path = target_del try: shutil.rmtree(target_del) except OSError as e: LOG.error(_LE('Failed to cleanup directory %(target)s: ' '%(e)s'), {'target': target_del, 'e': e}, instance=instance) # It is possible that the delete failed, if so don't mark the instance # as cleaned. if remaining_path and os.path.exists(remaining_path): LOG.info(_LI('Deletion of %s failed'), remaining_path, instance=instance) return False LOG.info(_LI('Deletion of %s complete'), target_del, instance=instance) return True @property def need_legacy_block_device_info(self): return False def default_root_device_name(self, instance, image_meta, root_bdm): disk_bus = blockinfo.get_disk_bus_for_device_type( instance, CONF.libvirt.virt_type, image_meta, "disk") cdrom_bus = blockinfo.get_disk_bus_for_device_type( instance, CONF.libvirt.virt_type, image_meta, "cdrom") root_info = blockinfo.get_root_info( instance, CONF.libvirt.virt_type, image_meta, root_bdm, disk_bus, cdrom_bus) return block_device.prepend_dev(root_info['dev']) def default_device_names_for_instance(self, instance, root_device_name, *block_device_lists): block_device_mapping = list(itertools.chain(*block_device_lists)) # NOTE(ndipanov): Null out the device names so that blockinfo code # will assign them for bdm in block_device_mapping: if bdm.device_name is not None: LOG.warning( _LW("Ignoring supplied device name: %(device_name)s. " "Libvirt can't honour user-supplied dev names"), {'device_name': bdm.device_name}, instance=instance) bdm.device_name = None block_device_info = driver.get_block_device_info(instance, block_device_mapping) blockinfo.default_device_names(CONF.libvirt.virt_type, nova_context.get_admin_context(), instance, block_device_info, instance.image_meta) def get_device_name_for_instance(self, instance, bdms, block_device_obj): block_device_info = driver.get_block_device_info(instance, bdms) instance_info = blockinfo.get_disk_info( CONF.libvirt.virt_type, instance, instance.image_meta, block_device_info=block_device_info) suggested_dev_name = block_device_obj.device_name if suggested_dev_name is not None: LOG.warning( _LW('Ignoring supplied device name: %(suggested_dev)s'), {'suggested_dev': suggested_dev_name}, instance=instance) # NOTE(ndipanov): get_info_from_bdm will generate the new device name # only when it's actually not set on the bd object block_device_obj.device_name = None disk_info = blockinfo.get_info_from_bdm( instance, CONF.libvirt.virt_type, instance.image_meta, block_device_obj, mapping=instance_info['mapping']) return block_device.prepend_dev(disk_info['dev']) def is_supported_fs_format(self, fs_type): return fs_type in [disk_api.FS_FORMAT_EXT2, disk_api.FS_FORMAT_EXT3, disk_api.FS_FORMAT_EXT4, disk_api.FS_FORMAT_XFS]
44.665839
105
0.575309
import string import collections from collections import deque import contextlib import errno import functools import glob import itertools import mmap import operator import os import shutil import tempfile import time import uuid import eventlet from eventlet import greenthread from eventlet import tpool from lxml import etree from os_brick.initiator import connector from oslo_concurrency import processutils from oslo_log import log as logging from oslo_serialization import jsonutils from oslo_service import loopingcall from oslo_utils import excutils from oslo_utils import fileutils from oslo_utils import importutils from oslo_utils import strutils from oslo_utils import timeutils from oslo_utils import units import six from six.moves import range from nova.api.metadata import base as instance_metadata from nova import block_device from nova.compute import arch from nova.compute import hv_type from nova.compute import power_state from nova.compute import task_states from nova.compute import utils as compute_utils from nova.compute import vm_mode import nova.conf from nova.console import serial as serial_console from nova.console import type as ctype from nova import context as nova_context from nova import exception from nova.i18n import _ from nova.i18n import _LE from nova.i18n import _LI from nova.i18n import _LW from nova import image from nova.network import model as network_model from nova import objects from nova.objects import fields from nova.objects import migrate_data as migrate_data_obj from nova.pci import manager as pci_manager from nova.pci import utils as pci_utils from nova import utils from nova import version from nova.virt import block_device as driver_block_device from nova.virt import configdrive from nova.virt import diagnostics from nova.virt.disk import api as disk_api from nova.virt.disk.vfs import guestfs from nova.virt import driver from nova.virt import firewall from nova.virt import hardware from nova.virt.image import model as imgmodel from nova.virt import images from nova.virt.libvirt import blockinfo from nova.virt.libvirt import config as vconfig from nova.virt.libvirt import firewall as libvirt_firewall from nova.virt.libvirt import guest as libvirt_guest from nova.virt.libvirt import host from nova.virt.libvirt import imagebackend from nova.virt.libvirt import imagecache from nova.virt.libvirt import instancejobtracker from nova.virt.libvirt import migration as libvirt_migrate from nova.virt.libvirt.storage import dmcrypt from nova.virt.libvirt.storage import lvm from nova.virt.libvirt.storage import rbd_utils from nova.virt.libvirt import utils as libvirt_utils from nova.virt.libvirt import vif as libvirt_vif from nova.virt.libvirt.volume import remotefs from nova.virt import netutils from nova.virt import watchdog_actions from nova.volume import cinder from nova.volume import encryptors libvirt = None uefi_logged = False LOG = logging.getLogger(__name__) CONF = nova.conf.CONF DEFAULT_FIREWALL_DRIVER = "%s.%s" % ( libvirt_firewall.__name__, libvirt_firewall.IptablesFirewallDriver.__name__) DEFAULT_UEFI_LOADER_PATH = { "x86_64": "/usr/share/OVMF/OVMF_CODE.fd", "aarch64": "/usr/share/AAVMF/AAVMF_CODE.fd" } MAX_CONSOLE_BYTES = 100 * units.Ki DISABLE_PREFIX = 'AUTO: ' DISABLE_REASON_UNDEFINED = None CONSOLE = "console=tty0 console=ttyS0" GuestNumaConfig = collections.namedtuple( 'GuestNumaConfig', ['cpuset', 'cputune', 'numaconfig', 'numatune']) libvirt_volume_drivers = [ 'iscsi=nova.virt.libvirt.volume.iscsi.LibvirtISCSIVolumeDriver', 'iser=nova.virt.libvirt.volume.iser.LibvirtISERVolumeDriver', 'local=nova.virt.libvirt.volume.volume.LibvirtVolumeDriver', 'fake=nova.virt.libvirt.volume.volume.LibvirtFakeVolumeDriver', 'rbd=nova.virt.libvirt.volume.net.LibvirtNetVolumeDriver', 'sheepdog=nova.virt.libvirt.volume.net.LibvirtNetVolumeDriver', 'nfs=nova.virt.libvirt.volume.nfs.LibvirtNFSVolumeDriver', 'smbfs=nova.virt.libvirt.volume.smbfs.LibvirtSMBFSVolumeDriver', 'aoe=nova.virt.libvirt.volume.aoe.LibvirtAOEVolumeDriver', 'glusterfs=' 'nova.virt.libvirt.volume.glusterfs.LibvirtGlusterfsVolumeDriver', 'fibre_channel=' 'nova.virt.libvirt.volume.fibrechannel.' 'LibvirtFibreChannelVolumeDriver', 'scality=nova.virt.libvirt.volume.scality.LibvirtScalityVolumeDriver', 'gpfs=nova.virt.libvirt.volume.gpfs.LibvirtGPFSVolumeDriver', 'quobyte=nova.virt.libvirt.volume.quobyte.LibvirtQuobyteVolumeDriver', 'hgst=nova.virt.libvirt.volume.hgst.LibvirtHGSTVolumeDriver', 'scaleio=nova.virt.libvirt.volume.scaleio.LibvirtScaleIOVolumeDriver', 'disco=nova.virt.libvirt.volume.disco.LibvirtDISCOVolumeDriver', 'vzstorage=' 'nova.virt.libvirt.volume.vzstorage.LibvirtVZStorageVolumeDriver', ] def patch_tpool_proxy(): def str_method(self): return str(self._obj) def repr_method(self): return repr(self._obj) tpool.Proxy.__str__ = str_method tpool.Proxy.__repr__ = repr_method patch_tpool_proxy() MIN_LIBVIRT_VERSION = (1, 2, 1) MIN_QEMU_VERSION = (1, 5, 3) NEXT_MIN_LIBVIRT_VERSION = (1, 2, 1) NEXT_MIN_QEMU_VERSION = (1, 5, 3) MIN_LIBVIRT_BLOCKJOB_RELATIVE_VERSION = (1, 2, 7) MIN_LIBVIRT_BLOCK_LM_WITH_VOLUMES_VERSION = (1, 2, 17) MIN_QEMU_DISCARD_VERSION = (1, 6, 0) MIN_LIBVIRT_NUMA_VERSION = (1, 2, 7) MIN_LIBVIRT_NUMA_VERSION_PPC = (1, 2, 19) VIRT_NUMA_VERSIONS = [(1, 2, 9, 2)] MIN_LIBVIRT_HUGEPAGE_VERSION = (1, 2, 8) VIRT_CPU_POLICY_VERSIONS = [(1, 2, 10)] MIN_QEMU_NUMA_HUGEPAGE_VERSION = (2, 1, 0) MIN_LIBVIRT_FSFREEZE_VERSION = (1, 2, 5) MIN_LIBVIRT_UEFI_VERSION = (1, 2, 9) MIN_LIBVIRT_HYPERV_TIMER_VERSION = (1, 2, 2) MIN_QEMU_HYPERV_TIMER_VERSION = (2, 0, 0) MIN_LIBVIRT_PARALLELS_VERSION = (1, 2, 12) MIN_LIBVIRT_SET_ADMIN_PASSWD = (1, 2, 16) MIN_LIBVIRT_KVM_S390_VERSION = (1, 2, 13) MIN_QEMU_S390_VERSION = (2, 3, 0) MIN_LIBVIRT_PF_WITH_NO_VFS_CAP_VERSION = (1, 3, 0) MIN_LIBVIRT_KVM_PPC64_VERSION = (1, 2, 12) MIN_QEMU_PPC64_VERSION = (2, 1, 0) MIN_LIBVIRT_AUTO_CONVERGE_VERSION = (1, 2, 3) MIN_QEMU_AUTO_CONVERGE = (1, 6, 0) NO_COMPRESSION_TYPES = ('qcow2',) QEMU_MAX_SERIAL_PORTS = 4 ALLOWED_QEMU_SERIAL_PORTS = QEMU_MAX_SERIAL_PORTS - 1 MIN_LIBVIRT_REALTIME_VERSION = (1, 2, 13) MIN_LIBVIRT_POSTCOPY_VERSION = (1, 3, 3) MIN_QEMU_POSTCOPY_VERSION = (2, 5, 0) MIN_LIBVIRT_OTHER_ARCH = {arch.S390: MIN_LIBVIRT_KVM_S390_VERSION, arch.S390X: MIN_LIBVIRT_KVM_S390_VERSION, arch.PPC: MIN_LIBVIRT_KVM_PPC64_VERSION, arch.PPC64: MIN_LIBVIRT_KVM_PPC64_VERSION, arch.PPC64LE: MIN_LIBVIRT_KVM_PPC64_VERSION, } MIN_QEMU_OTHER_ARCH = {arch.S390: MIN_QEMU_S390_VERSION, arch.S390X: MIN_QEMU_S390_VERSION, arch.PPC: MIN_QEMU_PPC64_VERSION, arch.PPC64: MIN_QEMU_PPC64_VERSION, arch.PPC64LE: MIN_QEMU_PPC64_VERSION, } MIN_LIBVIRT_PERF_VERSION = (2, 0, 0) LIBVIRT_PERF_EVENT_PREFIX = 'VIR_PERF_PARAM_' PERF_EVENTS_CPU_FLAG_MAPPING = {'cmt': 'cmt', 'mbml': 'mbm_local', 'mbmt': 'mbm_total', } class LibvirtDriver(driver.ComputeDriver): capabilities = { "has_imagecache": True, "supports_recreate": True, "supports_migrate_to_same_host": False, "supports_attach_interface": True, "supports_device_tagging": True, } def __init__(self, virtapi, read_only=False): super(LibvirtDriver, self).__init__(virtapi) global libvirt if libvirt is None: libvirt = importutils.import_module('libvirt') libvirt_migrate.libvirt = libvirt self._host = host.Host(self._uri(), read_only, lifecycle_event_handler=self.emit_event, conn_event_handler=self._handle_conn_event) self._initiator = None self._fc_wwnns = None self._fc_wwpns = None self._caps = None self._supported_perf_events = [] self.firewall_driver = firewall.load_driver( DEFAULT_FIREWALL_DRIVER, host=self._host) self.vif_driver = libvirt_vif.LibvirtGenericVIFDriver() self.volume_drivers = driver.driver_dict_from_config( self._get_volume_drivers(), self) self._disk_cachemode = None self.image_cache_manager = imagecache.ImageCacheManager() self.image_backend = imagebackend.Backend(CONF.use_cow_images) self.disk_cachemodes = {} self.valid_cachemodes = ["default", "none", "writethrough", "writeback", "directsync", "unsafe", ] self._conn_supports_start_paused = CONF.libvirt.virt_type in ('kvm', 'qemu') for mode_str in CONF.libvirt.disk_cachemodes: disk_type, sep, cache_mode = mode_str.partition('=') if cache_mode not in self.valid_cachemodes: LOG.warning(_LW('Invalid cachemode %(cache_mode)s specified ' 'for disk type %(disk_type)s.'), {'cache_mode': cache_mode, 'disk_type': disk_type}) continue self.disk_cachemodes[disk_type] = cache_mode self._volume_api = cinder.API() self._image_api = image.API() sysinfo_serial_funcs = { 'none': lambda: None, 'hardware': self._get_host_sysinfo_serial_hardware, 'os': self._get_host_sysinfo_serial_os, 'auto': self._get_host_sysinfo_serial_auto, } self._sysinfo_serial_func = sysinfo_serial_funcs.get( CONF.libvirt.sysinfo_serial) self.job_tracker = instancejobtracker.InstanceJobTracker() self._remotefs = remotefs.RemoteFilesystem() self._live_migration_flags = self._block_migration_flags = 0 self.active_migrations = {} self._reserved_hugepages = hardware.numa_get_reserved_huge_pages() def _get_volume_drivers(self): return libvirt_volume_drivers @property def disk_cachemode(self): if self._disk_cachemode is None: # O_DIRECT though. For those we fallback to 'writethrough' # which gives host crash safety, and is safe for migration # provided the filesystem is cache coherent (cluster filesystems # typically are, but things like NFS are not). self._disk_cachemode = "none" if not self._supports_direct_io(CONF.instances_path): self._disk_cachemode = "writethrough" return self._disk_cachemode def _set_cache_mode(self, conf): try: source_type = conf.source_type driver_cache = conf.driver_cache except AttributeError: return cache_mode = self.disk_cachemodes.get(source_type, driver_cache) conf.driver_cache = cache_mode def _do_quality_warnings(self): caps = self._host.get_capabilities() hostarch = caps.host.cpu.arch if (CONF.libvirt.virt_type not in ('qemu', 'kvm') or hostarch not in (arch.I686, arch.X86_64)): LOG.warning(_LW('The libvirt driver is not tested on ' '%(type)s/%(arch)s by the OpenStack project and ' 'thus its quality can not be ensured. For more ' 'information, see: http://docs.openstack.org/' 'developer/nova/support-matrix.html'), {'type': CONF.libvirt.virt_type, 'arch': hostarch}) def _handle_conn_event(self, enabled, reason): LOG.info(_LI("Connection event '%(enabled)d' reason '%(reason)s'"), {'enabled': enabled, 'reason': reason}) self._set_host_enabled(enabled, reason) def _version_to_string(self, version): return '.'.join([str(x) for x in version]) def init_host(self, host): self._host.initialize() self._do_quality_warnings() self._parse_migration_flags() self._supported_perf_events = self._get_supported_perf_events() if (CONF.libvirt.virt_type == 'lxc' and not (CONF.libvirt.uid_maps and CONF.libvirt.gid_maps)): LOG.warning(_LW("Running libvirt-lxc without user namespaces is " "dangerous. Containers spawned by Nova will be run " "as the host's root user. It is highly suggested " "that user namespaces be used in a public or " "multi-tenant environment.")) # to use this. This solves problem where people need to # stop Nova use of KVM because nested-virt is broken if CONF.libvirt.virt_type != "kvm": guestfs.force_tcg() if not self._host.has_min_version(MIN_LIBVIRT_VERSION): raise exception.NovaException( _('Nova requires libvirt version %s or greater.') % self._version_to_string(MIN_LIBVIRT_VERSION)) if (CONF.libvirt.virt_type in ("qemu", "kvm") and not self._host.has_min_version(hv_ver=MIN_QEMU_VERSION)): raise exception.NovaException( _('Nova requires QEMU version %s or greater.') % self._version_to_string(MIN_QEMU_VERSION)) if (CONF.libvirt.virt_type == 'parallels' and not self._host.has_min_version(MIN_LIBVIRT_PARALLELS_VERSION)): raise exception.NovaException( _('Running Nova with parallels virt_type requires ' 'libvirt version %s') % self._version_to_string(MIN_LIBVIRT_PARALLELS_VERSION)) # Give the cloud admin a heads up if we are intending to # change the MIN_LIBVIRT_VERSION in the next release. if not self._host.has_min_version(NEXT_MIN_LIBVIRT_VERSION): LOG.warning(_LW('Running Nova with a libvirt version less than ' '%(version)s is deprecated. The required minimum ' 'version of libvirt will be raised to %(version)s ' 'in the next release.'), {'version': self._version_to_string( NEXT_MIN_LIBVIRT_VERSION)}) if (CONF.libvirt.virt_type in ("qemu", "kvm") and not self._host.has_min_version(hv_ver=NEXT_MIN_QEMU_VERSION)): LOG.warning(_LW('Running Nova with a QEMU version less than ' '%(version)s is deprecated. The required minimum ' 'version of QEMU will be raised to %(version)s ' 'in the next release.'), {'version': self._version_to_string( NEXT_MIN_QEMU_VERSION)}) kvm_arch = arch.from_host() if (CONF.libvirt.virt_type in ('kvm', 'qemu') and kvm_arch in MIN_LIBVIRT_OTHER_ARCH and not self._host.has_min_version( MIN_LIBVIRT_OTHER_ARCH.get(kvm_arch), MIN_QEMU_OTHER_ARCH.get(kvm_arch))): raise exception.NovaException( _('Running Nova with qemu/kvm virt_type on %(arch)s ' 'requires libvirt version %(libvirt_ver)s and ' 'qemu version %(qemu_ver)s, or greater') % {'arch': kvm_arch, 'libvirt_ver': self._version_to_string( MIN_LIBVIRT_OTHER_ARCH.get(kvm_arch)), 'qemu_ver': self._version_to_string( MIN_QEMU_OTHER_ARCH.get(kvm_arch))}) def _prepare_migration_flags(self): migration_flags = 0 migration_flags |= libvirt.VIR_MIGRATE_LIVE # Adding p2p flag only if xen is not in use, because xen does not # support p2p migrations if CONF.libvirt.virt_type != 'xen': migration_flags |= libvirt.VIR_MIGRATE_PEER2PEER # Adding VIR_MIGRATE_UNDEFINE_SOURCE because, without it, migrated # instance will remain defined on the source host migration_flags |= libvirt.VIR_MIGRATE_UNDEFINE_SOURCE live_migration_flags = block_migration_flags = migration_flags # Adding VIR_MIGRATE_NON_SHARED_INC, otherwise all block-migrations # will be live-migrations instead block_migration_flags |= libvirt.VIR_MIGRATE_NON_SHARED_INC return (live_migration_flags, block_migration_flags) def _handle_live_migration_tunnelled(self, migration_flags): if (CONF.libvirt.live_migration_tunnelled is None or CONF.libvirt.live_migration_tunnelled): migration_flags |= libvirt.VIR_MIGRATE_TUNNELLED return migration_flags def _is_post_copy_available(self): if self._host.has_min_version(lv_ver=MIN_LIBVIRT_POSTCOPY_VERSION, hv_ver=MIN_QEMU_POSTCOPY_VERSION): return True return False def _handle_live_migration_post_copy(self, migration_flags): if CONF.libvirt.live_migration_permit_post_copy: if self._is_post_copy_available(): migration_flags |= libvirt.VIR_MIGRATE_POSTCOPY else: LOG.info(_LI('The live_migration_permit_post_copy is set ' 'to True, but it is not supported.')) return migration_flags def _handle_live_migration_auto_converge(self, migration_flags): if self._host.has_min_version(lv_ver=MIN_LIBVIRT_AUTO_CONVERGE_VERSION, hv_ver=MIN_QEMU_AUTO_CONVERGE): if (self._is_post_copy_available() and (migration_flags & libvirt.VIR_MIGRATE_POSTCOPY) != 0): LOG.info(_LI('The live_migration_permit_post_copy is set to ' 'True and post copy live migration is available ' 'so auto-converge will not be in use.')) elif CONF.libvirt.live_migration_permit_auto_converge: migration_flags |= libvirt.VIR_MIGRATE_AUTO_CONVERGE elif CONF.libvirt.live_migration_permit_auto_converge: LOG.info(_LI('The live_migration_permit_auto_converge is set ' 'to True, but it is not supported.')) return migration_flags def _parse_migration_flags(self): (live_migration_flags, block_migration_flags) = self._prepare_migration_flags() live_migration_flags = self._handle_live_migration_tunnelled( live_migration_flags) block_migration_flags = self._handle_live_migration_tunnelled( block_migration_flags) live_migration_flags = self._handle_live_migration_post_copy( live_migration_flags) block_migration_flags = self._handle_live_migration_post_copy( block_migration_flags) live_migration_flags = self._handle_live_migration_auto_converge( live_migration_flags) block_migration_flags = self._handle_live_migration_auto_converge( block_migration_flags) self._live_migration_flags = live_migration_flags self._block_migration_flags = block_migration_flags # TODO(sahid): This method is targeted for removal when the tests # have been updated to avoid its use # # All libvirt API calls on the libvirt.Connect object should be # encapsulated by methods on the nova.virt.libvirt.host.Host # object, rather than directly invoking the libvirt APIs. The goal # is to avoid a direct dependency on the libvirt API from the # driver.py file. def _get_connection(self): return self._host.get_connection() _conn = property(_get_connection) @staticmethod def _uri(): if CONF.libvirt.virt_type == 'uml': uri = CONF.libvirt.connection_uri or 'uml:///system' elif CONF.libvirt.virt_type == 'xen': uri = CONF.libvirt.connection_uri or 'xen:///' elif CONF.libvirt.virt_type == 'lxc': uri = CONF.libvirt.connection_uri or 'lxc:///' elif CONF.libvirt.virt_type == 'parallels': uri = CONF.libvirt.connection_uri or 'parallels:///system' else: uri = CONF.libvirt.connection_uri or 'qemu:///system' return uri @staticmethod def _live_migration_uri(dest): # Only Xen and QEMU support live migration, see # https://libvirt.org/migration.html#scenarios for reference uris = { 'kvm': 'qemu+tcp://%s/system', 'qemu': 'qemu+tcp://%s/system', 'xen': 'xenmigr://%s/system', } virt_type = CONF.libvirt.virt_type uri = CONF.libvirt.live_migration_uri or uris.get(virt_type) if uri is None: raise exception.LiveMigrationURINotAvailable(virt_type=virt_type) return uri % dest def instance_exists(self, instance): try: self._host.get_guest(instance) return True except exception.NovaException: return False def list_instances(self): names = [] for guest in self._host.list_guests(only_running=False): names.append(guest.name) return names def list_instance_uuids(self): uuids = [] for guest in self._host.list_guests(only_running=False): uuids.append(guest.uuid) return uuids def plug_vifs(self, instance, network_info): for vif in network_info: self.vif_driver.plug(instance, vif) def _unplug_vifs(self, instance, network_info, ignore_errors): for vif in network_info: try: self.vif_driver.unplug(instance, vif) except exception.NovaException: if not ignore_errors: raise def unplug_vifs(self, instance, network_info): self._unplug_vifs(instance, network_info, False) def _teardown_container(self, instance): inst_path = libvirt_utils.get_instance_path(instance) container_dir = os.path.join(inst_path, 'rootfs') rootfs_dev = instance.system_metadata.get('rootfs_device_name') LOG.debug('Attempting to teardown container at path %(dir)s with ' 'root device: %(rootfs_dev)s', {'dir': container_dir, 'rootfs_dev': rootfs_dev}, instance=instance) disk_api.teardown_container(container_dir, rootfs_dev) def _destroy(self, instance, attempt=1): try: guest = self._host.get_guest(instance) if CONF.serial_console.enabled: # This method is called for several events: destroy, # rebuild, hard-reboot, power-off - For all of these # events we want to release the serial ports acquired # for the guest before destroying it. serials = self._get_serial_ports_from_guest(guest) for hostname, port in serials: serial_console.release_port(host=hostname, port=port) except exception.InstanceNotFound: guest = None # If the instance is already terminated, we're still happy old_domid = -1 if guest is not None: try: old_domid = guest.id guest.poweroff() except libvirt.libvirtError as e: is_okay = False errcode = e.get_error_code() if errcode == libvirt.VIR_ERR_NO_DOMAIN: is_okay = True elif errcode == libvirt.VIR_ERR_OPERATION_INVALID: state = guest.get_power_state(self._host) if state == power_state.SHUTDOWN: is_okay = True elif errcode == libvirt.VIR_ERR_INTERNAL_ERROR: errmsg = e.get_error_message() if (CONF.libvirt.virt_type == 'lxc' and errmsg == 'internal error: ' 'Some processes refused to die'): # fast enough for libvirt. The container will # eventually die. For now, move on and let # the wait_for_destroy logic take over. is_okay = True elif errcode == libvirt.VIR_ERR_OPERATION_TIMEOUT: LOG.warning(_LW("Cannot destroy instance, operation time " "out"), instance=instance) reason = _("operation time out") raise exception.InstancePowerOffFailure(reason=reason) elif errcode == libvirt.VIR_ERR_SYSTEM_ERROR: if e.get_int1() == errno.EBUSY: # NOTE(danpb): When libvirt kills a process it sends it # SIGTERM first and waits 10 seconds. If it hasn't gone # Usually when a QEMU process fails to go away upon # SIGKILL it is because it is stuck in an # uninterruptible kernel sleep waiting on I/O from # some non-responsive server. # Given the CPU load of the gate tests though, it is # conceivable that the 15 second timeout is too short, # particularly if the VM running tempest has a high # steal time from the cloud host. ie 15 wallclock # seconds may have passed, but the VM might have only # have a few seconds of scheduled run time. LOG.warning(_LW('Error from libvirt during destroy. ' 'Code=%(errcode)s Error=%(e)s; ' 'attempt %(attempt)d of 3'), {'errcode': errcode, 'e': e, 'attempt': attempt}, instance=instance) with excutils.save_and_reraise_exception() as ctxt: # Try up to 3 times before giving up. if attempt < 3: ctxt.reraise = False self._destroy(instance, attempt + 1) return if not is_okay: with excutils.save_and_reraise_exception(): LOG.error(_LE('Error from libvirt during destroy. ' 'Code=%(errcode)s Error=%(e)s'), {'errcode': errcode, 'e': e}, instance=instance) def _wait_for_destroy(expected_domid): # NOTE(vish): If the instance disappears during the destroy # we ignore it so the cleanup can still be # attempted because we would prefer destroy to # never fail. try: dom_info = self.get_info(instance) state = dom_info.state new_domid = dom_info.id except exception.InstanceNotFound: LOG.info(_LI("During wait destroy, instance disappeared."), instance=instance) raise loopingcall.LoopingCallDone() if state == power_state.SHUTDOWN: LOG.info(_LI("Instance destroyed successfully."), instance=instance) raise loopingcall.LoopingCallDone() # NOTE(wangpan): If the instance was booted again after destroy, # this may be an endless loop, so check the id of # domain here, if it changed and the instance is # still running, we should destroy it again. # see https://bugs.launchpad.net/nova/+bug/1111213 for more details if new_domid != expected_domid: LOG.info(_LI("Instance may be started again."), instance=instance) kwargs['is_running'] = True raise loopingcall.LoopingCallDone() kwargs = {'is_running': False} timer = loopingcall.FixedIntervalLoopingCall(_wait_for_destroy, old_domid) timer.start(interval=0.5).wait() if kwargs['is_running']: LOG.info(_LI("Going to destroy instance again."), instance=instance) self._destroy(instance) else: # NOTE(GuanQiang): teardown container to avoid resource leak if CONF.libvirt.virt_type == 'lxc': self._teardown_container(instance) def destroy(self, context, instance, network_info, block_device_info=None, destroy_disks=True, migrate_data=None): self._destroy(instance) self.cleanup(context, instance, network_info, block_device_info, destroy_disks, migrate_data) def _undefine_domain(self, instance): try: guest = self._host.get_guest(instance) try: guest.delete_configuration() except libvirt.libvirtError as e: with excutils.save_and_reraise_exception(): errcode = e.get_error_code() LOG.error(_LE('Error from libvirt during undefine. ' 'Code=%(errcode)s Error=%(e)s'), {'errcode': errcode, 'e': e}, instance=instance) except exception.InstanceNotFound: pass def cleanup(self, context, instance, network_info, block_device_info=None, destroy_disks=True, migrate_data=None, destroy_vifs=True): if destroy_vifs: self._unplug_vifs(instance, network_info, True) retry = True while retry: try: self.unfilter_instance(instance, network_info) except libvirt.libvirtError as e: try: state = self.get_info(instance).state except exception.InstanceNotFound: state = power_state.SHUTDOWN if state != power_state.SHUTDOWN: LOG.warning(_LW("Instance may be still running, destroy " "it again."), instance=instance) self._destroy(instance) else: retry = False errcode = e.get_error_code() LOG.exception(_LE('Error from libvirt during unfilter. ' 'Code=%(errcode)s Error=%(e)s'), {'errcode': errcode, 'e': e}, instance=instance) reason = "Error unfiltering instance." raise exception.InstanceTerminationFailure(reason=reason) except Exception: retry = False raise else: retry = False # FIXME(wangpan): if the instance is booted again here, such as the # the soft reboot operation boot it here, it will # become "running deleted", should we check and destroy # it at the end of this method? # NOTE(vish): we disconnect from volumes regardless block_device_mapping = driver.block_device_info_get_mapping( block_device_info) for vol in block_device_mapping: connection_info = vol['connection_info'] disk_dev = vol['mount_device'] if disk_dev is not None: disk_dev = disk_dev.rpartition("/")[2] if ('data' in connection_info and 'volume_id' in connection_info['data']): volume_id = connection_info['data']['volume_id'] encryption = encryptors.get_encryption_metadata( context, self._volume_api, volume_id, connection_info) if encryption: # The volume must be detached from the VM before # disconnecting it from its encryptor. Otherwise, the # encryptor may report that the volume is still in use. encryptor = self._get_volume_encryptor(connection_info, encryption) encryptor.detach_volume(**encryption) try: self._disconnect_volume(connection_info, disk_dev) except Exception as exc: with excutils.save_and_reraise_exception() as ctxt: if destroy_disks: # Don't block on Volume errors if we're trying to # delete the instance as we may be partially created # or deleted ctxt.reraise = False LOG.warning( _LW("Ignoring Volume Error on vol %(vol_id)s " "during delete %(exc)s"), {'vol_id': vol.get('volume_id'), 'exc': exc}, instance=instance) if destroy_disks: # NOTE(haomai): destroy volumes if needed if CONF.libvirt.images_type == 'lvm': self._cleanup_lvm(instance, block_device_info) if CONF.libvirt.images_type == 'rbd': self._cleanup_rbd(instance) is_shared_block_storage = False if migrate_data and 'is_shared_block_storage' in migrate_data: is_shared_block_storage = migrate_data.is_shared_block_storage if destroy_disks or is_shared_block_storage: attempts = int(instance.system_metadata.get('clean_attempts', '0')) success = self.delete_instance_files(instance) # NOTE(mriedem): This is used in the _run_pending_deletes periodic # task in the compute manager. The tight coupling is not great... instance.system_metadata['clean_attempts'] = str(attempts + 1) if success: instance.cleaned = True instance.save() self._undefine_domain(instance) def _detach_encrypted_volumes(self, instance, block_device_info): disks = jsonutils.loads(self.get_instance_disk_info(instance, block_device_info)) encrypted_volumes = filter(dmcrypt.is_encrypted, [disk['path'] for disk in disks]) for path in encrypted_volumes: dmcrypt.delete_volume(path) def _get_serial_ports_from_guest(self, guest, mode=None): xml = guest.get_xml_desc() tree = etree.fromstring(xml) # The 'serial' device is the base for x86 platforms. Other platforms # (e.g. kvm on system z = arch.S390X) can only use 'console' devices. xpath_mode = "[@mode='%s']" % mode if mode else "" serial_tcp = "./devices/serial[@type='tcp']/source" + xpath_mode console_tcp = "./devices/console[@type='tcp']/source" + xpath_mode tcp_devices = tree.findall(serial_tcp) if len(tcp_devices) == 0: tcp_devices = tree.findall(console_tcp) for source in tcp_devices: yield (source.get("host"), int(source.get("service"))) @staticmethod def _get_rbd_driver(): return rbd_utils.RBDDriver( pool=CONF.libvirt.images_rbd_pool, ceph_conf=CONF.libvirt.images_rbd_ceph_conf, rbd_user=CONF.libvirt.rbd_user) def _cleanup_rbd(self, instance): # NOTE(nic): On revert_resize, the cleanup steps for the root # volume are handled with an "rbd snap rollback" command, # and none of this is needed (and is, in fact, harmful) so # filter out non-ephemerals from the list if instance.task_state == task_states.RESIZE_REVERTING: filter_fn = lambda disk: (disk.startswith(instance.uuid) and disk.endswith('disk.local')) else: filter_fn = lambda disk: disk.startswith(instance.uuid) LibvirtDriver._get_rbd_driver().cleanup_volumes(filter_fn) def _cleanup_lvm(self, instance, block_device_info): if instance.get('ephemeral_key_uuid') is not None: self._detach_encrypted_volumes(instance, block_device_info) disks = self._lvm_disks(instance) if disks: lvm.remove_volumes(disks) def _lvm_disks(self, instance): if CONF.libvirt.images_volume_group: vg = os.path.join('/dev', CONF.libvirt.images_volume_group) if not os.path.exists(vg): return [] pattern = '%s_' % instance.uuid def belongs_to_instance(disk): return disk.startswith(pattern) def fullpath(name): return os.path.join(vg, name) logical_volumes = lvm.list_volumes(vg) disk_names = filter(belongs_to_instance, logical_volumes) disks = map(fullpath, disk_names) return disks return [] def get_volume_connector(self, instance): root_helper = utils.get_root_helper() return connector.get_connector_properties( root_helper, CONF.my_block_storage_ip, CONF.libvirt.volume_use_multipath, enforce_multipath=True, host=CONF.host) def _cleanup_resize(self, instance, network_info): target = libvirt_utils.get_instance_path(instance) + '_resize' if os.path.exists(target): # Deletion can fail over NFS, so retry the deletion as required. # Set maximum attempt as 5, most test can remove the directory # for the second time. utils.execute('rm', '-rf', target, delay_on_retry=True, attempts=5) root_disk = self.image_backend.image(instance, 'disk') # TODO(nic): Set ignore_errors=False in a future release. # It is set to True here to avoid any upgrade issues surrounding # instances being in pending resize state when the software is updated; # in that case there will be no snapshot to remove. Once it can be # reasonably assumed that no such instances exist in the wild # anymore, it should be set back to False (the default) so it will # throw errors, like it should. if root_disk.exists(): root_disk.remove_snap(libvirt_utils.RESIZE_SNAPSHOT_NAME, ignore_errors=True) if instance.host != CONF.host: self._undefine_domain(instance) self.unplug_vifs(instance, network_info) self.unfilter_instance(instance, network_info) def _get_volume_driver(self, connection_info): driver_type = connection_info.get('driver_volume_type') if driver_type not in self.volume_drivers: raise exception.VolumeDriverNotFound(driver_type=driver_type) return self.volume_drivers[driver_type] def _connect_volume(self, connection_info, disk_info): vol_driver = self._get_volume_driver(connection_info) vol_driver.connect_volume(connection_info, disk_info) def _disconnect_volume(self, connection_info, disk_dev): vol_driver = self._get_volume_driver(connection_info) vol_driver.disconnect_volume(connection_info, disk_dev) def _get_volume_config(self, connection_info, disk_info): vol_driver = self._get_volume_driver(connection_info) return vol_driver.get_config(connection_info, disk_info) def _get_volume_encryptor(self, connection_info, encryption): encryptor = encryptors.get_volume_encryptor(connection_info, **encryption) return encryptor def _check_discard_for_attach_volume(self, conf, instance): if conf.driver_discard == 'unmap' and conf.target_bus == 'virtio': LOG.debug('Attempting to attach volume %(id)s with discard ' 'support enabled to an instance using an ' 'unsupported configuration. target_bus = ' '%(bus)s. Trim commands will not be issued to ' 'the storage device.', {'bus': conf.target_bus, 'id': conf.serial}, instance=instance) def attach_volume(self, context, connection_info, instance, mountpoint, disk_bus=None, device_type=None, encryption=None): guest = self._host.get_guest(instance) disk_dev = mountpoint.rpartition("/")[2] bdm = { 'device_name': disk_dev, 'disk_bus': disk_bus, 'device_type': device_type} # Note(cfb): If the volume has a custom block size, check that # that we are using QEMU/KVM and libvirt >= 0.10.2. The # presence of a block size is considered mandatory by # cinder so we fail if we can't honor the request. data = {} if ('data' in connection_info): data = connection_info['data'] if ('logical_block_size' in data or 'physical_block_size' in data): if ((CONF.libvirt.virt_type != "kvm" and CONF.libvirt.virt_type != "qemu")): msg = _("Volume sets block size, but the current " "libvirt hypervisor '%s' does not support custom " "block size") % CONF.libvirt.virt_type raise exception.InvalidHypervisorType(msg) disk_info = blockinfo.get_info_from_bdm( instance, CONF.libvirt.virt_type, instance.image_meta, bdm) self._connect_volume(connection_info, disk_info) conf = self._get_volume_config(connection_info, disk_info) self._set_cache_mode(conf) self._check_discard_for_attach_volume(conf, instance) try: state = guest.get_power_state(self._host) live = state in (power_state.RUNNING, power_state.PAUSED) if encryption: encryptor = self._get_volume_encryptor(connection_info, encryption) encryptor.attach_volume(context, **encryption) guest.attach_device(conf, persistent=True, live=live) except Exception as ex: LOG.exception(_LE('Failed to attach volume at mountpoint: %s'), mountpoint, instance=instance) if isinstance(ex, libvirt.libvirtError): errcode = ex.get_error_code() if errcode == libvirt.VIR_ERR_OPERATION_FAILED: self._disconnect_volume(connection_info, disk_dev) raise exception.DeviceIsBusy(device=disk_dev) with excutils.save_and_reraise_exception(): self._disconnect_volume(connection_info, disk_dev) def _swap_volume(self, guest, disk_path, new_path, resize_to): dev = guest.get_block_device(disk_path) xml = guest.get_xml_desc(dump_inactive=True, dump_sensitive=True) # Abort is an idempotent operation, so make sure any block # jobs which may have failed are ended. try: dev.abort_job() except Exception: pass try: # NOTE (rmk): blockRebase cannot be executed on persistent # domains, so we need to temporarily undefine it. # If any part of this block fails, the domain is # re-defined regardless. if guest.has_persistent_configuration(): guest.delete_configuration() # Start copy with VIR_DOMAIN_REBASE_REUSE_EXT flag to # allow writing to existing external volume file dev.rebase(new_path, copy=True, reuse_ext=True) while dev.wait_for_job(): time.sleep(0.5) dev.abort_job(pivot=True) if resize_to: # NOTE(alex_xu): domain.blockJobAbort isn't sync call. This while dev.wait_for_job(wait_for_job_clean=True): time.sleep(0.5) dev.resize(resize_to * units.Gi / units.Ki) finally: self._host.write_instance_config(xml) def swap_volume(self, old_connection_info, new_connection_info, instance, mountpoint, resize_to): guest = self._host.get_guest(instance) disk_dev = mountpoint.rpartition("/")[2] if not guest.get_disk(disk_dev): raise exception.DiskNotFound(location=disk_dev) disk_info = { 'dev': disk_dev, 'bus': blockinfo.get_disk_bus_for_disk_dev( CONF.libvirt.virt_type, disk_dev), 'type': 'disk', } self._connect_volume(new_connection_info, disk_info) conf = self._get_volume_config(new_connection_info, disk_info) if not conf.source_path: self._disconnect_volume(new_connection_info, disk_dev) raise NotImplementedError(_("Swap only supports host devices")) volume_id = new_connection_info.get('serial') bdm = objects.BlockDeviceMapping.get_by_volume_and_instance( nova_context.get_admin_context(), volume_id, instance.uuid) driver_bdm = driver_block_device.convert_volume(bdm) driver_bdm['connection_info'] = new_connection_info driver_bdm.save() self._swap_volume(guest, disk_dev, conf.source_path, resize_to) self._disconnect_volume(old_connection_info, disk_dev) def _get_existing_domain_xml(self, instance, network_info, block_device_info=None): try: guest = self._host.get_guest(instance) xml = guest.get_xml_desc() except exception.InstanceNotFound: disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance, instance.image_meta, block_device_info) xml = self._get_guest_xml(nova_context.get_admin_context(), instance, network_info, disk_info, instance.image_meta, block_device_info=block_device_info) return xml def detach_volume(self, connection_info, instance, mountpoint, encryption=None): disk_dev = mountpoint.rpartition("/")[2] try: guest = self._host.get_guest(instance) state = guest.get_power_state(self._host) live = state in (power_state.RUNNING, power_state.PAUSED) wait_for_detach = guest.detach_device_with_retry(guest.get_disk, disk_dev, persistent=True, live=live) if encryption: encryptor = self._get_volume_encryptor(connection_info, encryption) encryptor.detach_volume(**encryption) wait_for_detach() except exception.InstanceNotFound: LOG.warning(_LW("During detach_volume, instance disappeared."), instance=instance) except exception.DeviceNotFound: raise exception.DiskNotFound(location=disk_dev) except libvirt.libvirtError as ex: error_code = ex.get_error_code() if error_code == libvirt.VIR_ERR_NO_DOMAIN: # NOTE(vish): LOG.warning(_LW("During detach_volume, instance disappeared."), instance=instance) else: raise self._disconnect_volume(connection_info, disk_dev) def attach_interface(self, instance, image_meta, vif): guest = self._host.get_guest(instance) self.vif_driver.plug(instance, vif) self.firewall_driver.setup_basic_filtering(instance, [vif]) cfg = self.vif_driver.get_config(instance, vif, image_meta, instance.flavor, CONF.libvirt.virt_type, self._host) try: state = guest.get_power_state(self._host) live = state in (power_state.RUNNING, power_state.PAUSED) guest.attach_device(cfg, persistent=True, live=live) except libvirt.libvirtError: LOG.error(_LE('attaching network adapter failed.'), instance=instance, exc_info=True) self.vif_driver.unplug(instance, vif) raise exception.InterfaceAttachFailed( instance_uuid=instance.uuid) def detach_interface(self, instance, vif): guest = self._host.get_guest(instance) cfg = self.vif_driver.get_config(instance, vif, instance.image_meta, instance.flavor, CONF.libvirt.virt_type, self._host) try: self.vif_driver.unplug(instance, vif) state = guest.get_power_state(self._host) live = state in (power_state.RUNNING, power_state.PAUSED) guest.detach_device(cfg, persistent=True, live=live) except libvirt.libvirtError as ex: error_code = ex.get_error_code() if error_code == libvirt.VIR_ERR_NO_DOMAIN: LOG.warning(_LW("During detach_interface, " "instance disappeared."), instance=instance) else: # NOTE(mriedem): When deleting an instance and using Neutron, # we can be racing against Neutron deleting the port and # sending the vif-deleted event which then triggers a call to # detach the interface, so we might have failed because the # network device no longer exists. Libvirt will fail with # "operation failed: no matching network device was found" # which unfortunately does not have a unique error code so we # need to look up the interface by MAC and if it's not found mac = vif.get('address') interface = guest.get_interface_by_mac(mac) if interface: LOG.error(_LE('detaching network adapter failed.'), instance=instance, exc_info=True) raise exception.InterfaceDetachFailed( instance_uuid=instance.uuid) LOG.warning(_LW('Detaching interface %(mac)s failed because ' 'the device is no longer found on the guest.'), {'mac': mac}, instance=instance) def _create_snapshot_metadata(self, image_meta, instance, img_fmt, snp_name): metadata = {'is_public': False, 'status': 'active', 'name': snp_name, 'properties': { 'kernel_id': instance.kernel_id, 'image_location': 'snapshot', 'image_state': 'available', 'owner_id': instance.project_id, 'ramdisk_id': instance.ramdisk_id, } } if instance.os_type: metadata['properties']['os_type'] = instance.os_type if image_meta.disk_format == 'ami': metadata['disk_format'] = 'ami' else: metadata['disk_format'] = img_fmt if image_meta.obj_attr_is_set("container_format"): metadata['container_format'] = image_meta.container_format else: metadata['container_format'] = "bare" return metadata def snapshot(self, context, instance, image_id, update_task_state): try: guest = self._host.get_guest(instance) virt_dom = guest._domain except exception.InstanceNotFound: raise exception.InstanceNotRunning(instance_id=instance.uuid) snapshot = self._image_api.get(context, image_id) disk_path, source_format = libvirt_utils.find_disk(virt_dom) source_type = libvirt_utils.get_disk_type_from_path(disk_path) if source_type is None: source_type = source_format # (because we just gave libvirt the mounted filesystem), or the path, # so source_type is still going to be None. In this case, # snapshot_backend is going to default to CONF.libvirt.images_type # below, which is still safe. image_format = CONF.libvirt.snapshot_image_format or source_type # NOTE(bfilippov): save lvm and rbd as raw if image_format == 'lvm' or image_format == 'rbd': image_format = 'raw' metadata = self._create_snapshot_metadata(instance.image_meta, instance, image_format, snapshot['name']) snapshot_name = uuid.uuid4().hex state = guest.get_power_state(self._host) # NOTE(dgenin): Instances with LVM encrypted ephemeral storage require # cold snapshots. Currently, checking for encryption is # redundant because LVM supports only cold snapshots. # It is necessary in case this situation changes in the # future. if (self._host.has_min_version(hv_type=host.HV_DRIVER_QEMU) and source_type not in ('lvm') and not CONF.ephemeral_storage_encryption.enabled and not CONF.workarounds.disable_libvirt_livesnapshot): live_snapshot = True # Abort is an idempotent operation, so make sure any block # jobs which may have failed are ended. This operation also # confirms the running instance, as opposed to the system as a # whole, has a new enough version of the hypervisor (bug 1193146). try: guest.get_block_device(disk_path).abort_job() except libvirt.libvirtError as ex: error_code = ex.get_error_code() if error_code == libvirt.VIR_ERR_CONFIG_UNSUPPORTED: live_snapshot = False else: pass else: live_snapshot = False # NOTE(rmk): We cannot perform live snapshots when a managedSave # file is present, so we will use the cold/legacy method # for instances which are shutdown. if state == power_state.SHUTDOWN: live_snapshot = False self._prepare_domain_for_snapshot(context, live_snapshot, state, instance) snapshot_backend = self.image_backend.snapshot(instance, disk_path, image_type=source_type) if live_snapshot: LOG.info(_LI("Beginning live snapshot process"), instance=instance) else: LOG.info(_LI("Beginning cold snapshot process"), instance=instance) update_task_state(task_state=task_states.IMAGE_PENDING_UPLOAD) try: update_task_state(task_state=task_states.IMAGE_UPLOADING, expected_state=task_states.IMAGE_PENDING_UPLOAD) metadata['location'] = snapshot_backend.direct_snapshot( context, snapshot_name, image_format, image_id, instance.image_ref) self._snapshot_domain(context, live_snapshot, virt_dom, state, instance) self._image_api.update(context, image_id, metadata, purge_props=False) except (NotImplementedError, exception.ImageUnacceptable, exception.Forbidden) as e: if type(e) != NotImplementedError: LOG.warning(_LW('Performing standard snapshot because direct ' 'snapshot failed: %(error)s'), {'error': e}) failed_snap = metadata.pop('location', None) if failed_snap: failed_snap = {'url': str(failed_snap)} snapshot_backend.cleanup_direct_snapshot(failed_snap, also_destroy_volume=True, ignore_errors=True) update_task_state(task_state=task_states.IMAGE_PENDING_UPLOAD, expected_state=task_states.IMAGE_UPLOADING) # TODO(nic): possibly abstract this out to the snapshot_backend if source_type == 'rbd' and live_snapshot: # Standard snapshot uses qemu-img convert from RBD which is # not safe to run with live_snapshot. live_snapshot = False # Suspend the guest, so this is no longer a live snapshot self._prepare_domain_for_snapshot(context, live_snapshot, state, instance) snapshot_directory = CONF.libvirt.snapshots_directory fileutils.ensure_tree(snapshot_directory) with utils.tempdir(dir=snapshot_directory) as tmpdir: try: out_path = os.path.join(tmpdir, snapshot_name) if live_snapshot: # NOTE(xqueralt): libvirt needs o+x in the tempdir os.chmod(tmpdir, 0o701) self._live_snapshot(context, instance, guest, disk_path, out_path, source_format, image_format, instance.image_meta) else: snapshot_backend.snapshot_extract(out_path, image_format) finally: self._snapshot_domain(context, live_snapshot, virt_dom, state, instance) LOG.info(_LI("Snapshot extracted, beginning image upload"), instance=instance) # Upload that image to the image service update_task_state(task_state=task_states.IMAGE_UPLOADING, expected_state=task_states.IMAGE_PENDING_UPLOAD) with libvirt_utils.file_open(out_path) as image_file: self._image_api.update(context, image_id, metadata, image_file) except Exception: with excutils.save_and_reraise_exception(): LOG.exception(_LE("Failed to snapshot image")) failed_snap = metadata.pop('location', None) if failed_snap: failed_snap = {'url': str(failed_snap)} snapshot_backend.cleanup_direct_snapshot( failed_snap, also_destroy_volume=True, ignore_errors=True) LOG.info(_LI("Snapshot image upload complete"), instance=instance) def _prepare_domain_for_snapshot(self, context, live_snapshot, state, instance): # NOTE(dkang): managedSave does not work for LXC if CONF.libvirt.virt_type != 'lxc' and not live_snapshot: if state == power_state.RUNNING or state == power_state.PAUSED: self.suspend(context, instance) def _snapshot_domain(self, context, live_snapshot, virt_dom, state, instance): guest = None # NOTE(dkang): because previous managedSave is not called # for LXC, _create_domain must not be called. if CONF.libvirt.virt_type != 'lxc' and not live_snapshot: if state == power_state.RUNNING: guest = self._create_domain(domain=virt_dom) elif state == power_state.PAUSED: guest = self._create_domain(domain=virt_dom, pause=True) if guest is not None: self._attach_pci_devices( guest, pci_manager.get_instance_pci_devs(instance)) self._attach_sriov_ports(context, instance, guest) def _can_set_admin_password(self, image_meta): if (CONF.libvirt.virt_type not in ('kvm', 'qemu') or not self._host.has_min_version(MIN_LIBVIRT_SET_ADMIN_PASSWD)): raise exception.SetAdminPasswdNotSupported() hw_qga = image_meta.properties.get('hw_qemu_guest_agent', '') if not strutils.bool_from_string(hw_qga): raise exception.QemuGuestAgentNotEnabled() def set_admin_password(self, instance, new_pass): self._can_set_admin_password(instance.image_meta) guest = self._host.get_guest(instance) user = instance.image_meta.properties.get("os_admin_user") if not user: if instance.os_type == "windows": user = "Administrator" else: user = "root" try: guest.set_user_password(user, new_pass) except libvirt.libvirtError as ex: error_code = ex.get_error_code() msg = (_('Error from libvirt while set password for username ' '"%(user)s": [Error Code %(error_code)s] %(ex)s') % {'user': user, 'error_code': error_code, 'ex': ex}) raise exception.NovaException(msg) def _can_quiesce(self, instance, image_meta): if (CONF.libvirt.virt_type not in ('kvm', 'qemu') or not self._host.has_min_version(MIN_LIBVIRT_FSFREEZE_VERSION)): raise exception.InstanceQuiesceNotSupported( instance_id=instance.uuid) if not image_meta.properties.get('hw_qemu_guest_agent', False): raise exception.QemuGuestAgentNotEnabled() def _set_quiesced(self, context, instance, image_meta, quiesced): self._can_quiesce(instance, image_meta) try: guest = self._host.get_guest(instance) if quiesced: guest.freeze_filesystems() else: guest.thaw_filesystems() except libvirt.libvirtError as ex: error_code = ex.get_error_code() msg = (_('Error from libvirt while quiescing %(instance_name)s: ' '[Error Code %(error_code)s] %(ex)s') % {'instance_name': instance.name, 'error_code': error_code, 'ex': ex}) raise exception.NovaException(msg) def quiesce(self, context, instance, image_meta): self._set_quiesced(context, instance, image_meta, True) def unquiesce(self, context, instance, image_meta): self._set_quiesced(context, instance, image_meta, False) def _live_snapshot(self, context, instance, guest, disk_path, out_path, source_format, image_format, image_meta): dev = guest.get_block_device(disk_path) # Save a copy of the domain's persistent XML file xml = guest.get_xml_desc(dump_inactive=True, dump_sensitive=True) try: dev.abort_job() except Exception: pass src_disk_size = libvirt_utils.get_disk_size(disk_path, format=source_format) src_back_path = libvirt_utils.get_disk_backing_file(disk_path, format=source_format, basename=False) disk_delta = out_path + '.delta' libvirt_utils.create_cow_image(src_back_path, disk_delta, src_disk_size) quiesced = False try: self._set_quiesced(context, instance, image_meta, True) quiesced = True except exception.NovaException as err: if image_meta.properties.get('os_require_quiesce', False): raise LOG.info(_LI('Skipping quiescing instance: %(reason)s.'), {'reason': err}, instance=instance) try: if guest.has_persistent_configuration(): guest.delete_configuration() dev.rebase(disk_delta, copy=True, reuse_ext=True, shallow=True) while dev.wait_for_job(): time.sleep(0.5) dev.abort_job() libvirt_utils.chown(disk_delta, os.getuid()) finally: self._host.write_instance_config(xml) if quiesced: self._set_quiesced(context, instance, image_meta, False) libvirt_utils.extract_snapshot(disk_delta, 'qcow2', out_path, image_format) def cdrom_list(self, context, instance): cdroms = [] guest = self._host.get_guest(instance) domain = guest._domain xml = domain.XMLDesc(0) xml_doc = etree.fromstring(xml) disks = xml_doc.findall('devices/disk') for disk in disks: if disk.get('device') == 'cdrom': source = disk.find('source') target = disk.find('target') if target is not None: cdrom ={} device = target.get('dev') cdrom['device_name'] = device if source is not None: disk_path = source.get('file') image_id = os.path.basename(disk_path) else: image_id = '' cdrom['image_id'] = image_id cdroms.append(cdrom) return cdroms def attach_cdrom(self, context, instance, device, image_id): cdrom_device={} guest = self._host.get_guest(instance) domain = guest._domain cdrom_config = self._get_guest_cdrom_config(context, instance, image_id, device) is_updated = False is_active = domain.isActive() if is_active == 1: domain.updateDeviceFlags(cdrom_config.to_xml(), libvirt.VIR_DOMAIN_AFFECT_LIVE | libvirt.VIR_DOMAIN_AFFECT_CONFIG) is_updated = True elif is_active == 0: domain.updateDeviceFlags(cdrom_config.to_xml(), libvirt.VIR_DOMAIN_AFFECT_CONFIG) is_updated = True if is_updated: instance_dir = libvirt_utils.get_instance_path(instance) xml_path = os.path.join(instance_dir, 'libvirt.xml') xml = domain.XMLDesc(0) libvirt_utils.write_to_file(xml_path, xml) cdrom_device['device_name'] = device cdrom_device['image_id'] = image_id return cdrom_device def has_cdrom(self,instance, disk_info): disk_mapping = disk_info['mapping'] cdxml = None inst_type = objects.Flavor.get_by_id( nova_context.get_admin_context(read_deleted='yes'), instance['instance_type_id']) if 'disk' in disk_mapping: disk = disk_mapping['disk'] if disk['type'] == 'cdrom': image = self.image_backend.image(instance, 'disk', None) cdxml = image.libvirt_info(disk['bus'], disk['dev'], disk['type'], self.disk_cachemode, inst_type['extra_specs'], self._get_hypervisor_version()) if 'disk.local' in disk_mapping: disklocal = disk_mapping['disk.local'] if disklocal['type'] == 'cdrom': image = self.image_backend.image(instance, 'disk.local', None) cdxml = image.libvirt_info(disklocal['bus'], disklocal['dev'], disklocal['type'], self.disk_cachemode, inst_type['extra_specs'], self._get_hypervisor_version()) return cdxml def _get_guest_cdrom_config(self, context, instance, image_id, device, enable_cache_image=True): cdrom_config = vconfig.LibvirtConfigGuestDisk() cdrom_config.source_type = 'file' cdrom_config.source_device = 'cdrom' cdrom_config.target_bus = 'ide' if device: cdrom_config.target_dev = device cdrom_config.readonly = True cdrom_config.driver_name = 'qemu' cdrom_config.driver_format = 'raw' if image_id != '0': fake_image_id = imagecache.get_cache_fname(image_id) if enable_cache_image: imagecache.cache_image(libvirt_utils.fetch_image, fake_image_id, context=context, image_id=image_id) base_url = self.image_cache_manager._get_base() image_url = os.path.join(base_url, fake_image_id) else: image_url = '' cdrom_config.source_path = image_url return cdrom_config def dev_snapshot_create(self, context, instance, name): guest = self._host.get_guest(instance) domain = guest._domain xml = domain.XMLDesc(0) xml_doc = etree.fromstring(xml) device_info = vconfig.LibvirtConfigGuest() device_info.parse_dom(xml_doc) disks_to_snap = [] network_disks_to_snap = [] disks_to_skip = [] for guest_disk in device_info.devices: if (guest_disk.root_name != 'disk'): continue if (guest_disk.target_dev is None): continue disk_info = { 'dev': guest_disk.target_dev, 'serial': guest_disk.serial, 'current_file': guest_disk.source_path, 'source_protocol': guest_disk.source_protocol, 'source_name': guest_disk.source_name, 'source_hosts': guest_disk.source_hosts, 'source_ports': guest_disk.source_ports } if guest_disk.target_dev == 'vda': xwl_target_dev='vda' disks_to_snap.append(guest_disk.source_path) if guest_disk.target_dev == 'hda': xwl_target_dev='hda' disks_to_snap.append(guest_disk.source_path) if not disks_to_snap : msg = _('Found no disk to snapshot.') raise exception.NovaException(msg) snapshot = vconfig.LibvirtConfigGuestSnapshot() if name: uname = repr(name) snapshot_name =unicode(uname, 'unicode-escape') else: snapshot_name = None if xwl_target_dev == 'hda': for current_name in disks_to_snap: snap_disk = vconfig.LibvirtConfigGuestSnapshotDisk() if snapshot_name: snapshot.name = snapshot_name snap_disk.name = 'hda' snap_disk.snapshot = 'internal' snap_disk.driver_name = 'qcow2' snapshot.add_disk(snap_disk) for dev in disks_to_skip: snap_disk = vconfig.LibvirtConfigGuestSnapshotDisk() snap_disk.name = dev snap_disk.snapshot = 'no' snapshot.add_disk(snap_disk) else: for current_name in disks_to_snap: snap_disk = vconfig.LibvirtConfigGuestSnapshotDisk() if snapshot_name: snapshot.name = snapshot_name snap_disk.name = 'vda' snap_disk.snapshot = 'internal' snap_disk.driver_name = 'qcow2' snapshot.add_disk(snap_disk) for dev in disks_to_skip: snap_disk = vconfig.LibvirtConfigGuestSnapshotDisk() snap_disk.name = dev snap_disk.snapshot = 'no' snapshot.add_disk(snap_disk) snapshot_xml = snapshot.to_xml() snap_flags = 0 try: guest._domain.snapshotCreateXML(snapshot_xml, snap_flags) return except libvirt.libvirtError: LOG.exception(_LE('Unable to create quiesced dev_snapshot, ' 'attempting again with quiescing disabled.')) try: guest._domain.snapshotCreateXML(snapshot_xml, snap_flags ) except libvirt.libvirtError: LOG.exception(_LE('Unable to create dev_snapshot, ' 'failing dev_snapshot operation.')) raise def dev_snapshot_list(self, context, instance): snaps = [] try: guest = self._host.get_guest(instance) snapshotlist=guest._domain.listAllSnapshots(0) except exception.InstanceNotFound: return snaps for snapshot in snapshotlist: Desc = snapshot.getName() try: Desctime = time.strftime("%y-%m-%d %H:%M:%S", time.localtime(string.atof(Desc))) name = {} name['dev_snapshot_name'] = Desctime except: name = {} Desctime = Desc[2:-1] name['dev_snapshot_name'] = Desctime snaps.append(name) return snaps def dev_snapshot_delete(self, context, instance, name): try: guest = self._host.get_guest(instance) timeName = time.mktime(time.strptime(name, "%y-%m-%d %H:%M:%S")) tem='%.0f' % timeName snapshot = guest._domain.snapshotLookupByName(tem,0) snapshot.delete(0) except: stringName = repr(name) unicodeName = unicode(stringName,'unicode-escape') tem =unicodeName.encode('utf8') snapshot = guest._domain.snapshotLookupByName(tem,0) snapshot.delete(0) def dev_snapshot_revert(self, context, instance, name): try: guest = self._host.get_guest(instance) timeName = time.mktime(time.strptime(name, "%y-%m-%d %H:%M:%S")) tem='%.0f' % timeName snapshot = guest._domain.snapshotLookupByName(tem,0) guest._domain.revertToSnapshot(snapshot,0) except: stringName = repr(name) unicodeName = unicode(stringName,'unicode-escape') tem =unicodeName.encode('utf8') snapshot = guest._domain.snapshotLookupByName(tem,0) guest._domain.revertToSnapshot(snapshot,0) def _volume_snapshot_update_status(self, context, snapshot_id, status): try: self._volume_api.update_snapshot_status(context, snapshot_id, status) except Exception: LOG.exception(_LE('Failed to send updated snapshot status ' 'to volume service.')) def _volume_snapshot_create(self, context, instance, guest, volume_id, new_file): xml = guest.get_xml_desc() xml_doc = etree.fromstring(xml) device_info = vconfig.LibvirtConfigGuest() device_info.parse_dom(xml_doc) disks_to_snap = [] network_disks_to_snap = [] disks_to_skip = [] for guest_disk in device_info.devices: if (guest_disk.root_name != 'disk'): continue if (guest_disk.target_dev is None): continue if (guest_disk.serial is None or guest_disk.serial != volume_id): disks_to_skip.append(guest_disk.target_dev) continue disk_info = { 'dev': guest_disk.target_dev, 'serial': guest_disk.serial, 'current_file': guest_disk.source_path, 'source_protocol': guest_disk.source_protocol, 'source_name': guest_disk.source_name, 'source_hosts': guest_disk.source_hosts, 'source_ports': guest_disk.source_ports } if disk_info['current_file'] is not None: current_file = disk_info['current_file'] new_file_path = os.path.join(os.path.dirname(current_file), new_file) disks_to_snap.append((current_file, new_file_path)) elif disk_info['source_protocol'] in ('gluster', 'netfs'): network_disks_to_snap.append((disk_info, new_file)) if not disks_to_snap and not network_disks_to_snap: msg = _('Found no disk to snapshot.') raise exception.NovaException(msg) snapshot = vconfig.LibvirtConfigGuestSnapshot() for current_name, new_filename in disks_to_snap: snap_disk = vconfig.LibvirtConfigGuestSnapshotDisk() snap_disk.name = current_name snap_disk.source_path = new_filename snap_disk.source_type = 'file' snap_disk.snapshot = 'external' snap_disk.driver_name = 'qcow2' snapshot.add_disk(snap_disk) for disk_info, new_filename in network_disks_to_snap: snap_disk = vconfig.LibvirtConfigGuestSnapshotDisk() snap_disk.name = disk_info['dev'] snap_disk.source_type = 'network' snap_disk.source_protocol = disk_info['source_protocol'] snap_disk.snapshot = 'external' snap_disk.source_path = new_filename old_dir = disk_info['source_name'].split('/')[0] snap_disk.source_name = '%s/%s' % (old_dir, new_filename) snap_disk.source_hosts = disk_info['source_hosts'] snap_disk.source_ports = disk_info['source_ports'] snapshot.add_disk(snap_disk) for dev in disks_to_skip: snap_disk = vconfig.LibvirtConfigGuestSnapshotDisk() snap_disk.name = dev snap_disk.snapshot = 'no' snapshot.add_disk(snap_disk) snapshot_xml = snapshot.to_xml() LOG.debug("snap xml: %s", snapshot_xml, instance=instance) try: guest.snapshot(snapshot, no_metadata=True, disk_only=True, reuse_ext=True, quiesce=True) return except libvirt.libvirtError: LOG.exception(_LE('Unable to create quiesced VM snapshot, ' 'attempting again with quiescing disabled.'), instance=instance) try: guest.snapshot(snapshot, no_metadata=True, disk_only=True, reuse_ext=True, quiesce=False) except libvirt.libvirtError: LOG.exception(_LE('Unable to create VM snapshot, ' 'failing volume_snapshot operation.'), instance=instance) raise def _volume_refresh_connection_info(self, context, instance, volume_id): bdm = objects.BlockDeviceMapping.get_by_volume_and_instance( context, volume_id, instance.uuid) driver_bdm = driver_block_device.convert_volume(bdm) if driver_bdm: driver_bdm.refresh_connection_info(context, instance, self._volume_api, self) def volume_snapshot_create(self, context, instance, volume_id, create_info): LOG.debug("volume_snapshot_create: create_info: %(c_info)s", {'c_info': create_info}, instance=instance) try: guest = self._host.get_guest(instance) except exception.InstanceNotFound: raise exception.InstanceNotRunning(instance_id=instance.uuid) if create_info['type'] != 'qcow2': raise exception.NovaException(_('Unknown type: %s') % create_info['type']) snapshot_id = create_info.get('snapshot_id', None) if snapshot_id is None: raise exception.NovaException(_('snapshot_id required ' 'in create_info')) try: self._volume_snapshot_create(context, instance, guest, volume_id, create_info['new_file']) except Exception: with excutils.save_and_reraise_exception(): LOG.exception(_LE('Error occurred during ' 'volume_snapshot_create, ' 'sending error status to Cinder.'), instance=instance) self._volume_snapshot_update_status( context, snapshot_id, 'error') self._volume_snapshot_update_status( context, snapshot_id, 'creating') def _wait_for_snapshot(): snapshot = self._volume_api.get_snapshot(context, snapshot_id) if snapshot.get('status') != 'creating': self._volume_refresh_connection_info(context, instance, volume_id) raise loopingcall.LoopingCallDone() timer = loopingcall.FixedIntervalLoopingCall(_wait_for_snapshot) timer.start(interval=0.5).wait() @staticmethod def _rebase_with_qemu_img(guest, device, active_disk_object, rebase_base): # every protocol. So let's be safe. active_protocol = active_disk_object.source_protocol if active_protocol is not None: msg = _("Something went wrong when deleting a volume snapshot: " "rebasing a %(protocol)s network disk using qemu-img " "has not been fully tested") % {'protocol': active_protocol} LOG.error(msg) raise exception.NovaException(msg) if rebase_base is None: backing_file = "" qemu_img_extra_arg = [] else: backing_file = rebase_base b_file_fmt = images.qemu_img_info(backing_file).file_format qemu_img_extra_arg = ['-F', b_file_fmt] qemu_img_extra_arg.append(active_disk_object.source_path) utils.execute("qemu-img", "rebase", "-b", backing_file, *qemu_img_extra_arg) def _volume_snapshot_delete(self, context, instance, volume_id, snapshot_id, delete_info=None): LOG.debug('volume_snapshot_delete: delete_info: %s', delete_info, instance=instance) if delete_info['type'] != 'qcow2': msg = _('Unknown delete_info type %s') % delete_info['type'] raise exception.NovaException(msg) try: guest = self._host.get_guest(instance) except exception.InstanceNotFound: raise exception.InstanceNotRunning(instance_id=instance.uuid) my_dev = None active_disk = None xml = guest.get_xml_desc() xml_doc = etree.fromstring(xml) device_info = vconfig.LibvirtConfigGuest() device_info.parse_dom(xml_doc) active_disk_object = None for guest_disk in device_info.devices: if (guest_disk.root_name != 'disk'): continue if (guest_disk.target_dev is None or guest_disk.serial is None): continue if guest_disk.serial == volume_id: my_dev = guest_disk.target_dev active_disk = guest_disk.source_path active_protocol = guest_disk.source_protocol active_disk_object = guest_disk break if my_dev is None or (active_disk is None and active_protocol is None): msg = _('Disk with id: %s ' 'not found attached to instance.') % volume_id LOG.debug('Domain XML: %s', xml, instance=instance) raise exception.NovaException(msg) LOG.debug("found device at %s", my_dev, instance=instance) def _get_snap_dev(filename, backing_store): if filename is None: msg = _('filename cannot be None') raise exception.NovaException(msg) LOG.debug("XML: %s", xml) LOG.debug("active disk object: %s", active_disk_object) filename_to_merge = filename matched_name = None b = backing_store index = None current_filename = active_disk_object.source_name.split('/')[1] if current_filename == filename_to_merge: return my_dev + '[0]' while b is not None: source_filename = b.source_name.split('/')[1] if source_filename == filename_to_merge: LOG.debug('found match: %s', b.source_name) matched_name = b.source_name index = b.index break b = b.backing_store if matched_name is None: msg = _('no match found for %s') % (filename_to_merge) raise exception.NovaException(msg) LOG.debug('index of match (%s) is %s', b.source_name, index) my_snap_dev = '%s[%s]' % (my_dev, index) return my_snap_dev if delete_info['merge_target_file'] is None: rebase_disk = my_dev rebase_base = delete_info['file_to_merge'] if (active_protocol is not None) and (rebase_base is not None): rebase_base = _get_snap_dev(rebase_base, active_disk_object.backing_store) try: libvirt.VIR_DOMAIN_BLOCK_REBASE_RELATIVE relative = rebase_base is not None except AttributeError: LOG.warning(_LW( "Relative blockrebase support was not detected. " "Continuing with old behaviour.")) relative = False LOG.debug( 'disk: %(disk)s, base: %(base)s, ' 'bw: %(bw)s, relative: %(relative)s', {'disk': rebase_disk, 'base': rebase_base, 'bw': libvirt_guest.BlockDevice.REBASE_DEFAULT_BANDWIDTH, 'relative': str(relative)}, instance=instance) dev = guest.get_block_device(rebase_disk) if guest.is_active(): result = dev.rebase(rebase_base, relative=relative) if result == 0: LOG.debug('blockRebase started successfully', instance=instance) while dev.wait_for_job(abort_on_error=True): LOG.debug('waiting for blockRebase job completion', instance=instance) time.sleep(0.5) # In that case, let's ask qemu-img to rebase the disk. else: LOG.debug('Guest is not running so doing a block rebase ' 'using "qemu-img rebase"', instance=instance) self._rebase_with_qemu_img(guest, dev, active_disk_object, rebase_base) else: my_snap_base = None my_snap_top = None commit_disk = my_dev try: libvirt.VIR_DOMAIN_BLOCK_COMMIT_RELATIVE except AttributeError: ver = '.'.join( [str(x) for x in MIN_LIBVIRT_BLOCKJOB_RELATIVE_VERSION]) msg = _("Relative blockcommit support was not detected. " "Libvirt '%s' or later is required for online " "deletion of file/network storage-backed volume " "snapshots.") % ver raise exception.Invalid(msg) if active_protocol is not None: my_snap_base = _get_snap_dev(delete_info['merge_target_file'], active_disk_object.backing_store) my_snap_top = _get_snap_dev(delete_info['file_to_merge'], active_disk_object.backing_store) commit_base = my_snap_base or delete_info['merge_target_file'] commit_top = my_snap_top or delete_info['file_to_merge'] LOG.debug('will call blockCommit with commit_disk=%(commit_disk)s ' 'commit_base=%(commit_base)s ' 'commit_top=%(commit_top)s ', {'commit_disk': commit_disk, 'commit_base': commit_base, 'commit_top': commit_top}, instance=instance) dev = guest.get_block_device(commit_disk) result = dev.commit(commit_base, commit_top, relative=True) if result == 0: LOG.debug('blockCommit started successfully', instance=instance) while dev.wait_for_job(abort_on_error=True): LOG.debug('waiting for blockCommit job completion', instance=instance) time.sleep(0.5) def volume_snapshot_delete(self, context, instance, volume_id, snapshot_id, delete_info): try: self._volume_snapshot_delete(context, instance, volume_id, snapshot_id, delete_info=delete_info) except Exception: with excutils.save_and_reraise_exception(): LOG.exception(_LE('Error occurred during ' 'volume_snapshot_delete, ' 'sending error status to Cinder.'), instance=instance) self._volume_snapshot_update_status( context, snapshot_id, 'error_deleting') self._volume_snapshot_update_status(context, snapshot_id, 'deleting') self._volume_refresh_connection_info(context, instance, volume_id) def reboot(self, context, instance, network_info, reboot_type, block_device_info=None, bad_volumes_callback=None): if reboot_type == 'SOFT': try: soft_reboot_success = self._soft_reboot(instance) except libvirt.libvirtError as e: LOG.debug("Instance soft reboot failed: %s", e, instance=instance) soft_reboot_success = False if soft_reboot_success: LOG.info(_LI("Instance soft rebooted successfully."), instance=instance) return else: LOG.warning(_LW("Failed to soft reboot instance. " "Trying hard reboot."), instance=instance) return self._hard_reboot(context, instance, network_info, block_device_info) def _soft_reboot(self, instance): guest = self._host.get_guest(instance) state = guest.get_power_state(self._host) old_domid = guest.id if state == power_state.RUNNING: guest.shutdown() self._prepare_pci_devices_for_use( pci_manager.get_instance_pci_devs(instance, 'all')) for x in range(CONF.libvirt.wait_soft_reboot_seconds): guest = self._host.get_guest(instance) state = guest.get_power_state(self._host) new_domid = guest.id if old_domid != new_domid: if state in [power_state.SHUTDOWN, power_state.CRASHED]: LOG.info(_LI("Instance shutdown successfully."), instance=instance) self._create_domain(domain=guest._domain) timer = loopingcall.FixedIntervalLoopingCall( self._wait_for_running, instance) timer.start(interval=0.5).wait() return True else: LOG.info(_LI("Instance may have been rebooted during soft " "reboot, so return now."), instance=instance) return True greenthread.sleep(1) return False def _hard_reboot(self, context, instance, network_info, block_device_info=None): self._destroy(instance) # Domain XML will be redefined so we can safely undefine it # from libvirt. This ensure that such process as create serial # console for guest will run smoothly. self._undefine_domain(instance) # Convert the system metadata to image metadata instance_dir = libvirt_utils.get_instance_path(instance) fileutils.ensure_tree(instance_dir) disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance, instance.image_meta, block_device_info) # NOTE(vish): This could generate the wrong device_format if we are # using the raw backend and the images don't exist yet. # regenerate raw backend images, however, so when it # does we need to (re)generate the xml after the images # are in place. xml = self._get_guest_xml(context, instance, network_info, disk_info, instance.image_meta, block_device_info=block_device_info, write_to_disk=True) if context.auth_token is not None: # NOTE (rmk): Re-populate any missing backing files. backing_disk_info = self._get_instance_disk_info(instance.name, xml, block_device_info) self._create_images_and_backing(context, instance, instance_dir, backing_disk_info) # Initialize all the necessary networking, block devices and # start the instance. self._create_domain_and_network(context, xml, instance, network_info, disk_info, block_device_info=block_device_info, reboot=True, vifs_already_plugged=True) self._prepare_pci_devices_for_use( pci_manager.get_instance_pci_devs(instance, 'all')) def _wait_for_reboot(): state = self.get_info(instance).state if state == power_state.RUNNING: LOG.info(_LI("Instance rebooted successfully."), instance=instance) raise loopingcall.LoopingCallDone() timer = loopingcall.FixedIntervalLoopingCall(_wait_for_reboot) timer.start(interval=0.5).wait() def pause(self, instance): self._host.get_guest(instance).pause() def unpause(self, instance): self._host.get_guest(instance).resume() def _clean_shutdown(self, instance, timeout, retry_interval): # List of states that represent a shutdown instance SHUTDOWN_STATES = [power_state.SHUTDOWN, power_state.CRASHED] try: guest = self._host.get_guest(instance) except exception.InstanceNotFound: # If the instance has gone then we don't need to return True state = guest.get_power_state(self._host) if state in SHUTDOWN_STATES: LOG.info(_LI("Instance already shutdown."), instance=instance) return True LOG.debug("Shutting down instance from state %s", state, instance=instance) guest.shutdown() retry_countdown = retry_interval for sec in six.moves.range(timeout): guest = self._host.get_guest(instance) state = guest.get_power_state(self._host) if state in SHUTDOWN_STATES: LOG.info(_LI("Instance shutdown successfully after %d " "seconds."), sec, instance=instance) return True # any previous shutdown signal (for example it may # have still been startingup, so within the overall # timeout we re-trigger the shutdown every # retry_interval if retry_countdown == 0: retry_countdown = retry_interval # Instance could shutdown at any time, in which case we # will get an exception when we call shutdown try: LOG.debug("Instance in state %s after %d seconds - " "resending shutdown", state, sec, instance=instance) guest.shutdown() except libvirt.libvirtError: # Assume this is because its now shutdown, so loop # one more time to clean up. LOG.debug("Ignoring libvirt exception from shutdown " "request.", instance=instance) continue else: retry_countdown -= 1 time.sleep(1) LOG.info(_LI("Instance failed to shutdown in %d seconds."), timeout, instance=instance) return False def power_off(self, instance, timeout=0, retry_interval=0): if timeout: self._clean_shutdown(instance, timeout, retry_interval) self._destroy(instance) def power_on(self, context, instance, network_info, block_device_info=None): # We use _hard_reboot here to ensure that all backing files, # network, and block device connections, etc. are established # and available before we attempt to start the instance. self._hard_reboot(context, instance, network_info, block_device_info) def trigger_crash_dump(self, instance): try: self._host.get_guest(instance).inject_nmi() except libvirt.libvirtError as ex: error_code = ex.get_error_code() if error_code == libvirt.VIR_ERR_NO_SUPPORT: raise exception.TriggerCrashDumpNotSupported() elif error_code == libvirt.VIR_ERR_OPERATION_INVALID: raise exception.InstanceNotRunning(instance_id=instance.uuid) LOG.exception(_LE('Error from libvirt while injecting an NMI to ' '%(instance_uuid)s: ' '[Error Code %(error_code)s] %(ex)s'), {'instance_uuid': instance.uuid, 'error_code': error_code, 'ex': ex}) raise def suspend(self, context, instance): guest = self._host.get_guest(instance) self._detach_pci_devices(guest, pci_manager.get_instance_pci_devs(instance)) self._detach_sriov_ports(context, instance, guest) guest.save_memory_state() def resume(self, context, instance, network_info, block_device_info=None): disk_info = blockinfo.get_disk_info( CONF.libvirt.virt_type, instance, instance.image_meta, block_device_info=block_device_info) xml = self._get_existing_domain_xml(instance, network_info, block_device_info) guest = self._create_domain_and_network(context, xml, instance, network_info, disk_info, block_device_info=block_device_info, vifs_already_plugged=True) self._attach_pci_devices(guest, pci_manager.get_instance_pci_devs(instance)) self._attach_sriov_ports(context, instance, guest, network_info) def resume_state_on_host_boot(self, context, instance, network_info, block_device_info=None): # Check if the instance is running already and avoid doing # anything if it is. try: guest = self._host.get_guest(instance) state = guest.get_power_state(self._host) ignored_states = (power_state.RUNNING, power_state.SUSPENDED, power_state.NOSTATE, power_state.PAUSED) if state in ignored_states: return except exception.NovaException: pass # Instance is not up and could be in an unknown state. # Be as absolute as possible about getting it back into # a known and running state. self._hard_reboot(context, instance, network_info, block_device_info) def rescue(self, context, instance, network_info, image_meta, rescue_password): instance_dir = libvirt_utils.get_instance_path(instance) unrescue_xml = self._get_existing_domain_xml(instance, network_info) unrescue_xml_path = os.path.join(instance_dir, 'unrescue.xml') libvirt_utils.write_to_file(unrescue_xml_path, unrescue_xml) rescue_image_id = None if image_meta.obj_attr_is_set("id"): rescue_image_id = image_meta.id rescue_images = { 'image_id': (rescue_image_id or CONF.libvirt.rescue_image_id or instance.image_ref), 'kernel_id': (CONF.libvirt.rescue_kernel_id or instance.kernel_id), 'ramdisk_id': (CONF.libvirt.rescue_ramdisk_id or instance.ramdisk_id), } disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance, image_meta, rescue=True) gen_confdrive = functools.partial(self._create_configdrive, context, instance, admin_pass=rescue_password, network_info=network_info, suffix='.rescue') self._create_image(context, instance, disk_info['mapping'], suffix='.rescue', disk_images=rescue_images, network_info=network_info, admin_pass=rescue_password) xml = self._get_guest_xml(context, instance, network_info, disk_info, image_meta, rescue=rescue_images, write_to_disk=True) self._destroy(instance) self._create_domain(xml, post_xml_callback=gen_confdrive) def unrescue(self, instance, network_info): instance_dir = libvirt_utils.get_instance_path(instance) unrescue_xml_path = os.path.join(instance_dir, 'unrescue.xml') xml_path = os.path.join(instance_dir, 'libvirt.xml') xml = libvirt_utils.load_file(unrescue_xml_path) libvirt_utils.write_to_file(xml_path, xml) guest = self._host.get_guest(instance) # TODO(sahid): We are converting all calls from a # virDomain object to use nova.virt.libvirt.Guest. # We should be able to remove virt_dom at the end. virt_dom = guest._domain self._destroy(instance) self._create_domain(xml, virt_dom) libvirt_utils.file_delete(unrescue_xml_path) rescue_files = os.path.join(instance_dir, "*.rescue") for rescue_file in glob.iglob(rescue_files): if os.path.isdir(rescue_file): shutil.rmtree(rescue_file) else: libvirt_utils.file_delete(rescue_file) # cleanup rescue volume lvm.remove_volumes([lvmdisk for lvmdisk in self._lvm_disks(instance) if lvmdisk.endswith('.rescue')]) if CONF.libvirt.images_type == 'rbd': filter_fn = lambda disk: (disk.startswith(instance.uuid) and disk.endswith('.rescue')) LibvirtDriver._get_rbd_driver().cleanup_volumes(filter_fn) # def poll_rebooting_instances(self, timeout, instances): # pass # NOTE(ilyaalekseyev): Implementation like in multinics # for xenapi(tr3buchet) def spawn(self, context, instance, image_meta, injected_files, admin_password, network_info=None, block_device_info=None): disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance, image_meta, block_device_info) gen_confdrive = functools.partial(self._create_configdrive, context, instance, admin_pass=admin_password, files=injected_files, network_info=network_info) self._create_image(context, instance, disk_info['mapping'], network_info=network_info, block_device_info=block_device_info, files=injected_files, admin_pass=admin_password) # Required by Quobyte CI self._ensure_console_log_for_instance(instance) xml = self._get_guest_xml(context, instance, network_info, disk_info, image_meta, block_device_info=block_device_info, write_to_disk=True) self._create_domain_and_network( context, xml, instance, network_info, disk_info, block_device_info=block_device_info, post_xml_callback=gen_confdrive) LOG.debug("Instance is running", instance=instance) def _wait_for_boot(): state = self.get_info(instance).state if state == power_state.RUNNING: LOG.info(_LI("Instance spawned successfully."), instance=instance) raise loopingcall.LoopingCallDone() timer = loopingcall.FixedIntervalLoopingCall(_wait_for_boot) timer.start(interval=0.5).wait() def _flush_libvirt_console(self, pty): out, err = utils.execute('dd', 'if=%s' % pty, 'iflag=nonblock', run_as_root=True, check_exit_code=False) return out def _append_to_file(self, data, fpath): LOG.info(_LI('data: %(data)r, fpath: %(fpath)r'), {'data': data, 'fpath': fpath}) with open(fpath, 'a+') as fp: fp.write(data) return fpath def get_console_output(self, context, instance): guest = self._host.get_guest(instance) xml = guest.get_xml_desc() tree = etree.fromstring(xml) console_types = {} # NOTE(comstud): We want to try 'file' types first, then try 'pty' # types. We can't use Python 2.7 syntax of: console_nodes = tree.findall('./devices/console') for console_node in console_nodes: console_type = console_node.get('type') console_types.setdefault(console_type, []) console_types[console_type].append(console_node) if console_types.get('file'): for file_console in console_types.get('file'): source_node = file_console.find('./source') if source_node is None: continue path = source_node.get("path") if not path: continue if not os.path.exists(path): LOG.info(_LI('Instance is configured with a file console, ' 'but the backing file is not (yet?) present'), instance=instance) return "" libvirt_utils.chown(path, os.getuid()) with libvirt_utils.file_open(path, 'rb') as fp: log_data, remaining = utils.last_bytes(fp, MAX_CONSOLE_BYTES) if remaining > 0: LOG.info(_LI('Truncated console log returned, ' '%d bytes ignored'), remaining, instance=instance) return log_data if console_types.get('pty'): for pty_console in console_types.get('pty'): source_node = pty_console.find('./source') if source_node is None: continue pty = source_node.get("path") if not pty: continue break else: raise exception.ConsoleNotAvailable() console_log = self._get_console_log_path(instance) if os.path.exists(console_log): libvirt_utils.chown(console_log, os.getuid()) data = self._flush_libvirt_console(pty) fpath = self._append_to_file(data, console_log) with libvirt_utils.file_open(fpath, 'rb') as fp: log_data, remaining = utils.last_bytes(fp, MAX_CONSOLE_BYTES) if remaining > 0: LOG.info(_LI('Truncated console log returned, ' '%d bytes ignored'), remaining, instance=instance) return log_data def get_host_ip_addr(self): ips = compute_utils.get_machine_ips() if CONF.my_ip not in ips: LOG.warning(_LW('my_ip address (%(my_ip)s) was not found on ' 'any of the interfaces: %(ifaces)s'), {'my_ip': CONF.my_ip, 'ifaces': ", ".join(ips)}) return CONF.my_ip def get_vnc_console(self, context, instance): def get_vnc_port_for_instance(instance_name): guest = self._host.get_guest(instance) xml = guest.get_xml_desc() xml_dom = etree.fromstring(xml) graphic = xml_dom.find("./devices/graphics[@type='vnc']") if graphic is not None: return graphic.get('port') raise exception.ConsoleTypeUnavailable(console_type='vnc') port = get_vnc_port_for_instance(instance.name) host = CONF.vnc.vncserver_proxyclient_address return ctype.ConsoleVNC(host=host, port=port) def get_spice_console(self, context, instance): def get_spice_ports_for_instance(instance_name): guest = self._host.get_guest(instance) xml = guest.get_xml_desc() xml_dom = etree.fromstring(xml) graphic = xml_dom.find("./devices/graphics[@type='spice']") if graphic is not None: return (graphic.get('port'), graphic.get('tlsPort')) raise exception.ConsoleTypeUnavailable(console_type='spice') ports = get_spice_ports_for_instance(instance.name) host = CONF.spice.server_proxyclient_address return ctype.ConsoleSpice(host=host, port=ports[0], tlsPort=ports[1]) def get_serial_console(self, context, instance): guest = self._host.get_guest(instance) for hostname, port in self._get_serial_ports_from_guest( guest, mode='bind'): return ctype.ConsoleSerial(host=hostname, port=port) raise exception.ConsoleTypeUnavailable(console_type='serial') @staticmethod def _supports_direct_io(dirpath): if not hasattr(os, 'O_DIRECT'): LOG.debug("This python runtime does not support direct I/O") return False testfile = os.path.join(dirpath, ".directio.test") hasDirectIO = True fd = None try: fd = os.open(testfile, os.O_CREAT | os.O_WRONLY | os.O_DIRECT) align_size = 512 m = mmap.mmap(-1, align_size) m.write(r"x" * align_size) os.write(fd, m) LOG.debug("Path '%(path)s' supports direct I/O", {'path': dirpath}) except OSError as e: if e.errno == errno.EINVAL: LOG.debug("Path '%(path)s' does not support direct I/O: " "'%(ex)s'", {'path': dirpath, 'ex': e}) hasDirectIO = False else: with excutils.save_and_reraise_exception(): LOG.error(_LE("Error on '%(path)s' while checking " "direct I/O: '%(ex)s'"), {'path': dirpath, 'ex': e}) except Exception as e: with excutils.save_and_reraise_exception(): LOG.error(_LE("Error on '%(path)s' while checking direct I/O: " "'%(ex)s'"), {'path': dirpath, 'ex': e}) finally: if fd is not None: os.close(fd) try: os.unlink(testfile) except Exception: pass return hasDirectIO @staticmethod def _create_ephemeral(target, ephemeral_size, fs_label, os_type, is_block_dev=False, context=None, specified_fs=None): if not is_block_dev: libvirt_utils.create_image('raw', target, '%dG' % ephemeral_size) disk_api.mkfs(os_type, fs_label, target, run_as_root=is_block_dev, specified_fs=specified_fs) @staticmethod def _create_swap(target, swap_mb, context=None): libvirt_utils.create_image('raw', target, '%dM' % swap_mb) utils.mkfs('swap', target) @staticmethod def _get_console_log_path(instance): return os.path.join(libvirt_utils.get_instance_path(instance), 'console.log') def _ensure_console_log_for_instance(self, instance): # Consequently when the domain starts it is unable to write to its # console.log. See bug https://bugs.launchpad.net/nova/+bug/1597644 # # To work around this, we create the file manually before starting # the domain so it has the same ownership as Nova. This works # for Quobyte CI because it is also configured to run qemu as the same # user as the Nova service. Installations which don't set console_file = self._get_console_log_path(instance) LOG.debug('Ensure instance console log exists: %s', console_file, instance=instance) libvirt_utils.file_open(console_file, 'a').close() @staticmethod def _get_disk_config_path(instance, suffix=''): return os.path.join(libvirt_utils.get_instance_path(instance), 'disk.config' + suffix) @staticmethod def _get_disk_config_image_type(): return 'rbd' if CONF.libvirt.images_type == 'rbd' else 'raw' @staticmethod def _is_booted_from_volume(instance, disk_mapping): return ((not bool(instance.get('image_ref'))) or 'disk' not in disk_mapping) @staticmethod def _has_local_disk(instance, disk_mapping): if disk_mapping: if ('disk.local' in disk_mapping or 'disk.swap' in disk_mapping or 'disk.config' in disk_mapping): return True return False def _inject_data(self, injection_image, instance, network_info, admin_pass, files): target_partition = None if not instance.kernel_id: target_partition = CONF.libvirt.inject_partition if target_partition == 0: target_partition = None if CONF.libvirt.virt_type == 'lxc': target_partition = None if CONF.libvirt.inject_key and instance.get('key_data'): key = str(instance.key_data) else: key = None if not CONF.libvirt.inject_password: admin_pass = None net = netutils.get_injected_network_template( network_info, libvirt_virt_type=CONF.libvirt.virt_type) metadata = instance.get('metadata') if any((key, net, metadata, admin_pass, files)): img_id = instance.image_ref try: disk_api.inject_data(injection_image.get_model(self._conn), key, net, metadata, admin_pass, files, partition=target_partition, mandatory=('files',)) except Exception as e: with excutils.save_and_reraise_exception(): LOG.error(_LE('Error injecting data into image ' '%(img_id)s (%(e)s)'), {'img_id': img_id, 'e': e}, instance=instance) # think that it will be reused (ie: (live)-migration/resize) def _create_image(self, context, instance, disk_mapping, suffix='', disk_images=None, network_info=None, block_device_info=None, files=None, admin_pass=None, inject_files=True, fallback_from_host=None): booted_from_volume = self._is_booted_from_volume( instance, disk_mapping) def image(fname, image_type=CONF.libvirt.images_type): return self.image_backend.image(instance, fname + suffix, image_type) def raw(fname): return image(fname, image_type='raw') # ensure directories exist and are writable fileutils.ensure_tree(libvirt_utils.get_instance_path(instance)) LOG.info(_LI('Creating image'), instance=instance) if not disk_images: disk_images = {'image_id': instance.image_ref, 'kernel_id': instance.kernel_id, 'ramdisk_id': instance.ramdisk_id} if disk_images['kernel_id']: fname = imagecache.get_cache_fname(disk_images['kernel_id']) raw('kernel').cache(fetch_func=libvirt_utils.fetch_raw_image, context=context, filename=fname, image_id=disk_images['kernel_id']) if disk_images['ramdisk_id']: fname = imagecache.get_cache_fname(disk_images['ramdisk_id']) raw('ramdisk').cache(fetch_func=libvirt_utils.fetch_raw_image, context=context, filename=fname, image_id=disk_images['ramdisk_id']) inst_type = instance.get_flavor() if CONF.libvirt.virt_type == 'uml': libvirt_utils.chown(image('disk').path, 'root') self._create_and_inject_local_root(context, instance, booted_from_volume, suffix, disk_images, network_info, admin_pass, files, inject_files, fallback_from_host) # Lookup the filesystem type if required os_type_with_default = disk_api.get_fs_type_for_os_type( instance.os_type) # Generate a file extension based on the file system # type and the mkfs commands configured if any file_extension = disk_api.get_file_extension_for_os_type( os_type_with_default) ephemeral_gb = instance.flavor.ephemeral_gb if 'disk.local' in disk_mapping: disk_image = image('disk.local') fn = functools.partial(self._create_ephemeral, fs_label='ephemeral0', os_type=instance.os_type, is_block_dev=disk_image.is_block_dev) fname = "ephemeral_%s_%s" % (ephemeral_gb, file_extension) size = ephemeral_gb * units.Gi disk_image.cache(fetch_func=fn, context=context, filename=fname, size=size, ephemeral_size=ephemeral_gb) for idx, eph in enumerate(driver.block_device_info_get_ephemerals( block_device_info)): disk_image = image(blockinfo.get_eph_disk(idx)) specified_fs = eph.get('guest_format') if specified_fs and not self.is_supported_fs_format(specified_fs): msg = _("%s format is not supported") % specified_fs raise exception.InvalidBDMFormat(details=msg) fn = functools.partial(self._create_ephemeral, fs_label='ephemeral%d' % idx, os_type=instance.os_type, is_block_dev=disk_image.is_block_dev) size = eph['size'] * units.Gi fname = "ephemeral_%s_%s" % (eph['size'], file_extension) disk_image.cache(fetch_func=fn, context=context, filename=fname, size=size, ephemeral_size=eph['size'], specified_fs=specified_fs) if 'disk.swap' in disk_mapping: mapping = disk_mapping['disk.swap'] swap_mb = 0 swap = driver.block_device_info_get_swap(block_device_info) if driver.swap_is_usable(swap): swap_mb = swap['swap_size'] elif (inst_type['swap'] > 0 and not block_device.volume_in_mapping( mapping['dev'], block_device_info)): swap_mb = inst_type['swap'] if swap_mb > 0: size = swap_mb * units.Mi image('disk.swap').cache(fetch_func=self._create_swap, context=context, filename="swap_%s" % swap_mb, size=size, swap_mb=swap_mb) def _create_and_inject_local_root(self, context, instance, booted_from_volume, suffix, disk_images, network_info, admin_pass, files, inject_files, fallback_from_host): # File injection only if needed need_inject = (not configdrive.required_by(instance) and inject_files and CONF.libvirt.inject_partition != -2) # NOTE(ndipanov): Even if disk_mapping was passed in, which # currently happens only on rescue - we still don't want to if not booted_from_volume: root_fname = imagecache.get_cache_fname(disk_images['image_id']) size = instance.flavor.root_gb * units.Gi if size == 0 or suffix == '.rescue': size = None backend = self.image_backend.image(instance, 'disk' + suffix, CONF.libvirt.images_type) if instance.task_state == task_states.RESIZE_FINISH: backend.create_snap(libvirt_utils.RESIZE_SNAPSHOT_NAME) if backend.SUPPORTS_CLONE: def clone_fallback_to_fetch(*args, **kwargs): try: backend.clone(context, disk_images['image_id']) except exception.ImageUnacceptable: libvirt_utils.fetch_image(*args, **kwargs) fetch_func = clone_fallback_to_fetch else: fetch_func = libvirt_utils.fetch_image self._try_fetch_image_cache(backend, fetch_func, context, root_fname, disk_images['image_id'], instance, size, fallback_from_host) if need_inject: self._inject_data(backend, instance, network_info, admin_pass, files) elif need_inject: LOG.warning(_LW('File injection into a boot from volume ' 'instance is not supported'), instance=instance) def _create_configdrive(self, context, instance, admin_pass=None, files=None, network_info=None, suffix=''): instance.device_metadata = self._build_device_metadata(context, instance) config_drive_image = None if configdrive.required_by(instance): LOG.info(_LI('Using config drive'), instance=instance) config_drive_image = self.image_backend.image( instance, 'disk.config' + suffix, self._get_disk_config_image_type()) if not config_drive_image.exists(): extra_md = {} if admin_pass: extra_md['admin_pass'] = admin_pass inst_md = instance_metadata.InstanceMetadata( instance, content=files, extra_md=extra_md, network_info=network_info, request_context=context) cdb = configdrive.ConfigDriveBuilder(instance_md=inst_md) with cdb: config_drive_local_path = self._get_disk_config_path( instance, suffix) LOG.info(_LI('Creating config drive at %(path)s'), {'path': config_drive_local_path}, instance=instance) try: cdb.make_drive(config_drive_local_path) except processutils.ProcessExecutionError as e: with excutils.save_and_reraise_exception(): LOG.error(_LE('Creating config drive failed ' 'with error: %s'), e, instance=instance) try: config_drive_image.import_file( instance, config_drive_local_path, 'disk.config' + suffix) finally: # NOTE(mikal): if the config drive was imported into RBD, # then we no longer need the local copy if CONF.libvirt.images_type == 'rbd': os.unlink(config_drive_local_path) def _prepare_pci_devices_for_use(self, pci_devices): # kvm , qemu support managed mode # In managed mode, the configured device will be automatically # detached from the host OS drivers when the guest is started, # and then re-attached when the guest shuts down. if CONF.libvirt.virt_type != 'xen': # we do manual detach only for xen return try: for dev in pci_devices: libvirt_dev_addr = dev['hypervisor_name'] libvirt_dev = \ self._host.device_lookup_by_name(libvirt_dev_addr) # Note(yjiang5) Spelling for 'dettach' is correct, see # http://libvirt.org/html/libvirt-libvirt.html. libvirt_dev.dettach() # Note(yjiang5): A reset of one PCI device may impact other # devices on the same bus, thus we need two separated loops # to detach and then reset it. for dev in pci_devices: libvirt_dev_addr = dev['hypervisor_name'] libvirt_dev = \ self._host.device_lookup_by_name(libvirt_dev_addr) libvirt_dev.reset() except libvirt.libvirtError as exc: raise exception.PciDevicePrepareFailed(id=dev['id'], instance_uuid= dev['instance_uuid'], reason=six.text_type(exc)) def _detach_pci_devices(self, guest, pci_devs): try: for dev in pci_devs: guest.detach_device(self._get_guest_pci_device(dev), live=True) # after detachDeviceFlags returned, we should check the dom to # ensure the detaching is finished xml = guest.get_xml_desc() xml_doc = etree.fromstring(xml) guest_config = vconfig.LibvirtConfigGuest() guest_config.parse_dom(xml_doc) for hdev in [d for d in guest_config.devices if isinstance(d, vconfig.LibvirtConfigGuestHostdevPCI)]: hdbsf = [hdev.domain, hdev.bus, hdev.slot, hdev.function] dbsf = pci_utils.parse_address(dev.address) if [int(x, 16) for x in hdbsf] ==\ [int(x, 16) for x in dbsf]: raise exception.PciDeviceDetachFailed(reason= "timeout", dev=dev) except libvirt.libvirtError as ex: error_code = ex.get_error_code() if error_code == libvirt.VIR_ERR_NO_DOMAIN: LOG.warning(_LW("Instance disappeared while detaching " "a PCI device from it.")) else: raise def _attach_pci_devices(self, guest, pci_devs): try: for dev in pci_devs: guest.attach_device(self._get_guest_pci_device(dev)) except libvirt.libvirtError: LOG.error(_LE('Attaching PCI devices %(dev)s to %(dom)s failed.'), {'dev': pci_devs, 'dom': guest.id}) raise @staticmethod def _has_sriov_port(network_info): for vif in network_info: if vif['vnic_type'] == network_model.VNIC_TYPE_DIRECT: return True return False def _attach_sriov_ports(self, context, instance, guest, network_info=None): if network_info is None: network_info = instance.info_cache.network_info if network_info is None: return if self._has_sriov_port(network_info): for vif in network_info: if vif['vnic_type'] in network_model.VNIC_TYPES_SRIOV: cfg = self.vif_driver.get_config(instance, vif, instance.image_meta, instance.flavor, CONF.libvirt.virt_type, self._host) LOG.debug('Attaching SR-IOV port %(port)s to %(dom)s', {'port': vif, 'dom': guest.id}, instance=instance) guest.attach_device(cfg) def _detach_sriov_ports(self, context, instance, guest): network_info = instance.info_cache.network_info if network_info is None: return if self._has_sriov_port(network_info): # In case of SR-IOV vif types we create pci request per SR-IOV port # Therefore we can trust that pci_slot value in the vif is correct. sriov_pci_addresses = [ vif['profile']['pci_slot'] for vif in network_info if vif['vnic_type'] in network_model.VNIC_TYPES_SRIOV and vif['profile'].get('pci_slot') is not None ] # use detach_pci_devices to avoid failure in case of # multiple guest SRIOV ports with the same MAC # (protection use-case, ports are on different physical # interfaces) pci_devs = pci_manager.get_instance_pci_devs(instance, 'all') sriov_devs = [pci_dev for pci_dev in pci_devs if pci_dev.address in sriov_pci_addresses] self._detach_pci_devices(guest, sriov_devs) def _set_host_enabled(self, enabled, disable_reason=DISABLE_REASON_UNDEFINED): status_name = {True: 'disabled', False: 'enabled'} disable_service = not enabled ctx = nova_context.get_admin_context() try: service = objects.Service.get_by_compute_host(ctx, CONF.host) if service.disabled != disable_service: # Note(jang): this is a quick fix to stop operator- # disabled compute hosts from re-enabling themselves # automatically. We prefix any automatic reason code # with a fixed string. We only re-enable a host # automatically if we find that string in place. # This should probably be replaced with a separate flag. if not service.disabled or ( service.disabled_reason and service.disabled_reason.startswith(DISABLE_PREFIX)): service.disabled = disable_service service.disabled_reason = ( DISABLE_PREFIX + disable_reason if disable_service else DISABLE_REASON_UNDEFINED) service.save() LOG.debug('Updating compute service status to %s', status_name[disable_service]) else: LOG.debug('Not overriding manual compute service ' 'status with: %s', status_name[disable_service]) except exception.ComputeHostNotFound: LOG.warning(_LW('Cannot update service status on host "%s" ' 'since it is not registered.'), CONF.host) except Exception: LOG.warning(_LW('Cannot update service status on host "%s" ' 'due to an unexpected exception.'), CONF.host, exc_info=True) def _get_guest_cpu_model_config(self): mode = CONF.libvirt.cpu_mode model = CONF.libvirt.cpu_model if (CONF.libvirt.virt_type == "kvm" or CONF.libvirt.virt_type == "qemu"): if mode is None: mode = "host-model" if mode == "none": return vconfig.LibvirtConfigGuestCPU() else: if mode is None or mode == "none": return None if ((CONF.libvirt.virt_type != "kvm" and CONF.libvirt.virt_type != "qemu")): msg = _("Config requested an explicit CPU model, but " "the current libvirt hypervisor '%s' does not " "support selecting CPU models") % CONF.libvirt.virt_type raise exception.Invalid(msg) if mode == "custom" and model is None: msg = _("Config requested a custom CPU model, but no " "model name was provided") raise exception.Invalid(msg) elif mode != "custom" and model is not None: msg = _("A CPU model name should not be set when a " "host CPU model is requested") raise exception.Invalid(msg) LOG.debug("CPU mode '%(mode)s' model '%(model)s' was chosen", {'mode': mode, 'model': (model or "")}) cpu = vconfig.LibvirtConfigGuestCPU() cpu.mode = mode cpu.model = model return cpu def _get_guest_cpu_config(self, flavor, image_meta, guest_cpu_numa_config, instance_numa_topology): cpu = self._get_guest_cpu_model_config() if cpu is None: return None topology = hardware.get_best_cpu_topology( flavor, image_meta, numa_topology=instance_numa_topology) cpu.sockets = topology.sockets cpu.cores = topology.cores cpu.threads = topology.threads cpu.numa = guest_cpu_numa_config return cpu def _get_guest_disk_config(self, instance, name, disk_mapping, inst_type, image_type=None): if CONF.libvirt.hw_disk_discard: if not self._host.has_min_version(hv_ver=MIN_QEMU_DISCARD_VERSION, hv_type=host.HV_DRIVER_QEMU): msg = (_('Volume sets discard option, qemu %(qemu)s' ' or later is required.') % {'qemu': MIN_QEMU_DISCARD_VERSION}) raise exception.Invalid(msg) image = self.image_backend.image(instance, name, image_type) if (name == 'disk.config' and image_type == 'rbd' and not image.exists()): # This is likely an older config drive that has not been migrated # to rbd yet. Try to fall back on 'flat' image type. # TODO(melwitt): Add online migration of some sort so we can # remove this fall back once we know all config drives are in rbd. # NOTE(vladikr): make sure that the flat image exist, otherwise # the image will be created after the domain definition. flat_image = self.image_backend.image(instance, name, 'flat') if flat_image.exists(): image = flat_image LOG.debug('Config drive not found in RBD, falling back to the ' 'instance directory', instance=instance) disk_info = disk_mapping[name] return image.libvirt_info(disk_info['bus'], disk_info['dev'], disk_info['type'], self.disk_cachemode, inst_type['extra_specs'], self._host.get_version()) def _get_guest_fs_config(self, instance, name, image_type=None): image = self.image_backend.image(instance, name, image_type) return image.libvirt_fs_info("/", "ploop") def _get_guest_storage_config(self, instance, image_meta, disk_info, rescue, block_device_info, inst_type, os_type): devices = [] disk_mapping = disk_info['mapping'] block_device_mapping = driver.block_device_info_get_mapping( block_device_info) mount_rootfs = CONF.libvirt.virt_type == "lxc" if mount_rootfs: fs = vconfig.LibvirtConfigGuestFilesys() fs.source_type = "mount" fs.source_dir = os.path.join( libvirt_utils.get_instance_path(instance), 'rootfs') devices.append(fs) elif os_type == vm_mode.EXE and CONF.libvirt.virt_type == "parallels": if rescue: fsrescue = self._get_guest_fs_config(instance, "disk.rescue") devices.append(fsrescue) fsos = self._get_guest_fs_config(instance, "disk") fsos.target_dir = "/mnt/rescue" devices.append(fsos) else: if 'disk' in disk_mapping: fs = self._get_guest_fs_config(instance, "disk") devices.append(fs) else: if rescue: diskrescue = self._get_guest_disk_config(instance, 'disk.rescue', disk_mapping, inst_type) devices.append(diskrescue) diskos = self._get_guest_disk_config(instance, 'disk', disk_mapping, inst_type) devices.append(diskos) else: if 'disk' in disk_mapping: diskos = self._get_guest_disk_config(instance, 'disk', disk_mapping, inst_type) devices.append(diskos) if 'disk.local' in disk_mapping: disklocal = self._get_guest_disk_config(instance, 'disk.local', disk_mapping, inst_type) devices.append(disklocal) instance.default_ephemeral_device = ( block_device.prepend_dev(disklocal.target_dev)) for idx, eph in enumerate( driver.block_device_info_get_ephemerals( block_device_info)): diskeph = self._get_guest_disk_config( instance, blockinfo.get_eph_disk(idx), disk_mapping, inst_type) devices.append(diskeph) if 'disk.swap' in disk_mapping: diskswap = self._get_guest_disk_config(instance, 'disk.swap', disk_mapping, inst_type) devices.append(diskswap) instance.default_swap_device = ( block_device.prepend_dev(diskswap.target_dev)) if 'disk.config' in disk_mapping: diskconfig = self._get_guest_disk_config( instance, 'disk.config', disk_mapping, inst_type, self._get_disk_config_image_type()) devices.append(diskconfig) for vol in block_device.get_bdms_to_connect(block_device_mapping, mount_rootfs): connection_info = vol['connection_info'] vol_dev = block_device.prepend_dev(vol['mount_device']) info = disk_mapping[vol_dev] self._connect_volume(connection_info, info) cfg = self._get_volume_config(connection_info, info) devices.append(cfg) vol['connection_info'] = connection_info vol.save() for d in devices: self._set_cache_mode(d) if image_meta.properties.get('hw_scsi_model'): hw_scsi_model = image_meta.properties.hw_scsi_model scsi_controller = vconfig.LibvirtConfigGuestController() scsi_controller.type = 'scsi' scsi_controller.model = hw_scsi_model devices.append(scsi_controller) return devices def _get_host_sysinfo_serial_hardware(self): caps = self._host.get_capabilities() return caps.host.uuid def _get_host_sysinfo_serial_os(self): if not os.path.exists("/etc/machine-id"): msg = _("Unable to get host UUID: /etc/machine-id does not exist") raise exception.NovaException(msg) with open("/etc/machine-id") as f: # We want to have '-' in the right place # so we parse & reformat the value lines = f.read().split() if not lines: msg = _("Unable to get host UUID: /etc/machine-id is empty") raise exception.NovaException(msg) return str(uuid.UUID(lines[0])) def _get_host_sysinfo_serial_auto(self): if os.path.exists("/etc/machine-id"): return self._get_host_sysinfo_serial_os() else: return self._get_host_sysinfo_serial_hardware() def _get_guest_config_sysinfo(self, instance): sysinfo = vconfig.LibvirtConfigGuestSysinfo() sysinfo.system_manufacturer = version.vendor_string() sysinfo.system_product = version.product_string() sysinfo.system_version = version.version_string_with_package() sysinfo.system_serial = self._sysinfo_serial_func() sysinfo.system_uuid = instance.uuid sysinfo.system_family = "Virtual Machine" return sysinfo def _get_guest_pci_device(self, pci_device): dbsf = pci_utils.parse_address(pci_device.address) dev = vconfig.LibvirtConfigGuestHostdevPCI() dev.domain, dev.bus, dev.slot, dev.function = dbsf # only kvm support managed mode if CONF.libvirt.virt_type in ('xen', 'parallels',): dev.managed = 'no' if CONF.libvirt.virt_type in ('kvm', 'qemu'): dev.managed = 'yes' return dev def _get_guest_config_meta(self, context, instance): meta = vconfig.LibvirtConfigGuestMetaNovaInstance() meta.package = version.version_string_with_package() meta.name = instance.display_name meta.creationTime = time.time() if instance.image_ref not in ("", None): meta.roottype = "image" meta.rootid = instance.image_ref if context is not None: ometa = vconfig.LibvirtConfigGuestMetaNovaOwner() ometa.userid = context.user_id ometa.username = context.user_name ometa.projectid = context.project_id ometa.projectname = context.project_name meta.owner = ometa fmeta = vconfig.LibvirtConfigGuestMetaNovaFlavor() flavor = instance.flavor fmeta.name = flavor.name fmeta.memory = flavor.memory_mb fmeta.vcpus = flavor.vcpus fmeta.ephemeral = flavor.ephemeral_gb fmeta.disk = flavor.root_gb fmeta.swap = flavor.swap meta.flavor = fmeta return meta def _machine_type_mappings(self): mappings = {} for mapping in CONF.libvirt.hw_machine_type: host_arch, _, machine_type = mapping.partition('=') mappings[host_arch] = machine_type return mappings def _get_machine_type(self, image_meta, caps): # The underlying machine type can be set as an image attribute, # or otherwise based on some architecture specific defaults mach_type = None if image_meta.properties.get('hw_machine_type') is not None: mach_type = image_meta.properties.hw_machine_type else: # For ARM systems we will default to vexpress-a15 for armv7 # and virt for aarch64 if caps.host.cpu.arch == arch.ARMV7: mach_type = "vexpress-a15" if caps.host.cpu.arch == arch.AARCH64: mach_type = "virt" if caps.host.cpu.arch in (arch.S390, arch.S390X): mach_type = 's390-ccw-virtio' # If set in the config, use that as the default. if CONF.libvirt.hw_machine_type: mappings = self._machine_type_mappings() mach_type = mappings.get(caps.host.cpu.arch) return mach_type @staticmethod def _create_idmaps(klass, map_strings): idmaps = [] if len(map_strings) > 5: map_strings = map_strings[0:5] LOG.warning(_LW("Too many id maps, only included first five.")) for map_string in map_strings: try: idmap = klass() values = [int(i) for i in map_string.split(":")] idmap.start = values[0] idmap.target = values[1] idmap.count = values[2] idmaps.append(idmap) except (ValueError, IndexError): LOG.warning(_LW("Invalid value for id mapping %s"), map_string) return idmaps def _get_guest_idmaps(self): id_maps = [] if CONF.libvirt.virt_type == 'lxc' and CONF.libvirt.uid_maps: uid_maps = self._create_idmaps(vconfig.LibvirtConfigGuestUIDMap, CONF.libvirt.uid_maps) id_maps.extend(uid_maps) if CONF.libvirt.virt_type == 'lxc' and CONF.libvirt.gid_maps: gid_maps = self._create_idmaps(vconfig.LibvirtConfigGuestGIDMap, CONF.libvirt.gid_maps) id_maps.extend(gid_maps) return id_maps def _update_guest_cputune(self, guest, flavor, virt_type): is_able = self._host.is_cpu_control_policy_capable() cputuning = ['shares', 'period', 'quota'] wants_cputune = any([k for k in cputuning if "quota:cpu_" + k in flavor.extra_specs.keys()]) if wants_cputune and not is_able: raise exception.UnsupportedHostCPUControlPolicy() if not is_able or virt_type not in ('lxc', 'kvm', 'qemu'): return if guest.cputune is None: guest.cputune = vconfig.LibvirtConfigGuestCPUTune() # Setting the default cpu.shares value to be a value # dependent on the number of vcpus guest.cputune.shares = 1024 * guest.vcpus for name in cputuning: key = "quota:cpu_" + name if key in flavor.extra_specs: setattr(guest.cputune, name, int(flavor.extra_specs[key])) def _get_cpu_numa_config_from_instance(self, instance_numa_topology, wants_hugepages): if instance_numa_topology: guest_cpu_numa = vconfig.LibvirtConfigGuestCPUNUMA() for instance_cell in instance_numa_topology.cells: guest_cell = vconfig.LibvirtConfigGuestCPUNUMACell() guest_cell.id = instance_cell.id guest_cell.cpus = instance_cell.cpuset guest_cell.memory = instance_cell.memory * units.Ki # The vhost-user network backend requires file backed # guest memory (ie huge pages) to be marked as shared # access, not private, so an external process can read # and write the pages. # # You can't change the shared vs private flag for an # types of NIC may be hotplugged, we have no choice but # to unconditionally turn on the shared flag. This has # no real negative functional effect on the guest, so # is a reasonable approach to take if wants_hugepages: guest_cell.memAccess = "shared" guest_cpu_numa.cells.append(guest_cell) return guest_cpu_numa def _has_cpu_policy_support(self): for ver in BAD_LIBVIRT_CPU_POLICY_VERSIONS: if self._host.has_version(ver): ver_ = self._version_to_string(ver) raise exception.CPUPinningNotSupported(reason=_( 'Invalid libvirt version %(version)s') % {'version': ver_}) return True def _wants_hugepages(self, host_topology, instance_topology): if host_topology is None or instance_topology is None: return False avail_pagesize = [page.size_kb for page in host_topology.cells[0].mempages] avail_pagesize.sort() # Remove smallest page size as that's not classed as a largepage avail_pagesize = avail_pagesize[1:] for cell in instance_topology.cells: if (cell.pagesize is not None and cell.pagesize in avail_pagesize): return True return False def _get_guest_numa_config(self, instance_numa_topology, flavor, allowed_cpus=None, image_meta=None): if (not self._has_numa_support() and instance_numa_topology is not None): raise exception.NUMATopologyUnsupported() topology = self._get_host_numa_topology() guest_cpu_numa_config = self._get_cpu_numa_config_from_instance( instance_numa_topology, self._wants_hugepages(topology, instance_numa_topology)) if not guest_cpu_numa_config: return GuestNumaConfig(allowed_cpus, None, None, None) else: if topology: guest_cpu_tune = vconfig.LibvirtConfigGuestCPUTune() guest_numa_tune = vconfig.LibvirtConfigGuestNUMATune() allpcpus = [] numa_mem = vconfig.LibvirtConfigGuestNUMATuneMemory() numa_memnodes = [vconfig.LibvirtConfigGuestNUMATuneMemNode() for _ in guest_cpu_numa_config.cells] for host_cell in topology.cells: for guest_node_id, guest_config_cell in enumerate( guest_cpu_numa_config.cells): if guest_config_cell.id == host_cell.id: node = numa_memnodes[guest_node_id] node.cellid = guest_node_id node.nodeset = [host_cell.id] node.mode = "strict" numa_mem.nodeset.append(host_cell.id) object_numa_cell = ( instance_numa_topology.cells[guest_node_id] ) for cpu in guest_config_cell.cpus: pin_cpuset = ( vconfig.LibvirtConfigGuestCPUTuneVCPUPin()) pin_cpuset.id = cpu if (object_numa_cell.cpu_pinning and self._has_cpu_policy_support()): pcpu = object_numa_cell.cpu_pinning[cpu] pin_cpuset.cpuset = set([pcpu]) else: pin_cpuset.cpuset = host_cell.cpuset allpcpus.extend(pin_cpuset.cpuset) guest_cpu_tune.vcpupin.append(pin_cpuset) emulatorpin = vconfig.LibvirtConfigGuestCPUTuneEmulatorPin() emulatorpin.cpuset = set(allpcpus) guest_cpu_tune.emulatorpin = emulatorpin guest_cpu_tune.vcpupin.sort(key=operator.attrgetter("id")) if hardware.is_realtime_enabled(flavor): if not self._host.has_min_version( MIN_LIBVIRT_REALTIME_VERSION): raise exception.RealtimePolicyNotSupported() vcpus_rt, vcpus_em = hardware.vcpus_realtime_topology( set(cpu.id for cpu in guest_cpu_tune.vcpupin), flavor, image_meta) vcpusched = vconfig.LibvirtConfigGuestCPUTuneVCPUSched() vcpusched.vcpus = vcpus_rt vcpusched.scheduler = "fifo" vcpusched.priority = ( CONF.libvirt.realtime_scheduler_priority) guest_cpu_tune.vcpusched.append(vcpusched) guest_cpu_tune.emulatorpin.cpuset = vcpus_em guest_numa_tune.memory = numa_mem guest_numa_tune.memnodes = numa_memnodes for i, (cell, memnode) in enumerate( zip(guest_cpu_numa_config.cells, guest_numa_tune.memnodes)): cell.id = i memnode.cellid = i return GuestNumaConfig(None, guest_cpu_tune, guest_cpu_numa_config, guest_numa_tune) else: return GuestNumaConfig(allowed_cpus, None, guest_cpu_numa_config, None) def _get_guest_os_type(self, virt_type): if virt_type == "lxc": ret = vm_mode.EXE elif virt_type == "uml": ret = vm_mode.UML elif virt_type == "xen": ret = vm_mode.XEN else: ret = vm_mode.HVM return ret def _set_guest_for_rescue(self, rescue, guest, inst_path, virt_type, root_device_name): if rescue.get('kernel_id'): guest.os_kernel = os.path.join(inst_path, "kernel.rescue") if virt_type == "xen": guest.os_cmdline = "ro root=%s" % root_device_name else: guest.os_cmdline = ("root=%s %s" % (root_device_name, CONSOLE)) if virt_type == "qemu": guest.os_cmdline += " no_timer_check" if rescue.get('ramdisk_id'): guest.os_initrd = os.path.join(inst_path, "ramdisk.rescue") def _set_guest_for_inst_kernel(self, instance, guest, inst_path, virt_type, root_device_name, image_meta): guest.os_kernel = os.path.join(inst_path, "kernel") if virt_type == "xen": guest.os_cmdline = "ro root=%s" % root_device_name else: guest.os_cmdline = ("root=%s %s" % (root_device_name, CONSOLE)) if virt_type == "qemu": guest.os_cmdline += " no_timer_check" if instance.ramdisk_id: guest.os_initrd = os.path.join(inst_path, "ramdisk") if image_meta.properties.get("os_command_line"): guest.os_cmdline = image_meta.properties.os_command_line def _set_clock(self, guest, os_type, image_meta, virt_type): clk = vconfig.LibvirtConfigGuestClock() if os_type == 'windows': LOG.info(_LI('Configuring timezone for windows instance to ' 'localtime')) clk.offset = 'localtime' else: clk.offset = 'utc' guest.set_clock(clk) if virt_type == "kvm": self._set_kvm_timers(clk, os_type, image_meta) def _set_kvm_timers(self, clk, os_type, image_meta): tmpit = vconfig.LibvirtConfigGuestTimer() tmpit.name = "pit" tmpit.tickpolicy = "delay" tmrtc = vconfig.LibvirtConfigGuestTimer() tmrtc.name = "rtc" tmrtc.tickpolicy = "catchup" clk.add_timer(tmpit) clk.add_timer(tmrtc) guestarch = libvirt_utils.get_arch(image_meta) if guestarch in (arch.I686, arch.X86_64): tmhpet = vconfig.LibvirtConfigGuestTimer() tmhpet.name = "hpet" tmhpet.present = False clk.add_timer(tmhpet) if (os_type == 'windows' and self._host.has_min_version(MIN_LIBVIRT_HYPERV_TIMER_VERSION, MIN_QEMU_HYPERV_TIMER_VERSION)): tmhyperv = vconfig.LibvirtConfigGuestTimer() tmhyperv.name = "hypervclock" tmhyperv.present = True clk.add_timer(tmhyperv) def _set_features(self, guest, os_type, caps, virt_type): if virt_type == "xen": if caps.host.cpu.arch in (arch.I686, arch.X86_64): guest.features.append(vconfig.LibvirtConfigGuestFeaturePAE()) if (virt_type not in ("lxc", "uml", "parallels", "xen") or (virt_type == "xen" and guest.os_type == vm_mode.HVM)): guest.features.append(vconfig.LibvirtConfigGuestFeatureACPI()) guest.features.append(vconfig.LibvirtConfigGuestFeatureAPIC()) if (virt_type in ("qemu", "kvm") and os_type == 'windows'): hv = vconfig.LibvirtConfigGuestFeatureHyperV() hv.relaxed = True hv.spinlocks = True hv.spinlock_retries = 8191 hv.vapic = True guest.features.append(hv) def _check_number_of_serial_console(self, num_ports): virt_type = CONF.libvirt.virt_type if (virt_type in ("kvm", "qemu") and num_ports > ALLOWED_QEMU_SERIAL_PORTS): raise exception.SerialPortNumberLimitExceeded( allowed=ALLOWED_QEMU_SERIAL_PORTS, virt_type=virt_type) def _create_serial_console_devices(self, guest, instance, flavor, image_meta): guest_arch = libvirt_utils.get_arch(image_meta) if CONF.serial_console.enabled: num_ports = hardware.get_number_of_serial_ports( flavor, image_meta) if guest_arch in (arch.S390, arch.S390X): console_cls = vconfig.LibvirtConfigGuestConsole else: console_cls = vconfig.LibvirtConfigGuestSerial self._check_number_of_serial_console(num_ports) for port in six.moves.range(num_ports): console = console_cls() console.port = port console.type = "tcp" console.listen_host = ( CONF.serial_console.proxyclient_address) console.listen_port = ( serial_console.acquire_port( console.listen_host)) guest.add_device(console) else: # with a single type=pty console. Instead we have # to configure two separate consoles. if guest_arch in (arch.S390, arch.S390X): consolelog = vconfig.LibvirtConfigGuestConsole() consolelog.target_type = "sclplm" else: consolelog = vconfig.LibvirtConfigGuestSerial() consolelog.type = "file" consolelog.source_path = self._get_console_log_path(instance) guest.add_device(consolelog) def _add_video_driver(self, guest, image_meta, flavor): VALID_VIDEO_DEVICES = ("vga", "cirrus", "vmvga", "xen", "qxl") video = vconfig.LibvirtConfigGuestVideo() # NOTE(ldbragst): The following logic sets the video.type # depending on supported defaults given the architecture, # virtualization type, and features. The video.type attribute can # be overridden by the user with image_meta.properties, which # is carried out in the next if statement below this one. guestarch = libvirt_utils.get_arch(image_meta) if guest.os_type == vm_mode.XEN: video.type = 'xen' elif CONF.libvirt.virt_type == 'parallels': video.type = 'vga' elif guestarch in (arch.PPC, arch.PPC64, arch.PPC64LE): # NOTE(ldbragst): PowerKVM doesn't support 'cirrus' be default video.type = 'vga' elif CONF.spice.enabled: video.type = 'qxl' if image_meta.properties.get('hw_video_model'): video.type = image_meta.properties.hw_video_model if (video.type not in VALID_VIDEO_DEVICES): raise exception.InvalidVideoMode(model=video.type) video_ram = image_meta.properties.get('hw_video_ram', 0) max_vram = int(flavor.extra_specs.get('hw_video:ram_max_mb', 0)) if video_ram > max_vram: raise exception.RequestedVRamTooHigh(req_vram=video_ram, max_vram=max_vram) if max_vram and video_ram: video.vram = video_ram * units.Mi / units.Ki guest.add_device(video) def _add_qga_device(self, guest, instance): qga = vconfig.LibvirtConfigGuestChannel() qga.type = "unix" qga.target_name = "org.qemu.guest_agent.0" qga.source_path = ("/var/lib/libvirt/qemu/%s.%s.sock" % ("org.qemu.guest_agent.0", instance.name)) guest.add_device(qga) def _add_rng_device(self, guest, flavor): rng_device = vconfig.LibvirtConfigGuestRng() rate_bytes = flavor.extra_specs.get('hw_rng:rate_bytes', 0) period = flavor.extra_specs.get('hw_rng:rate_period', 0) if rate_bytes: rng_device.rate_bytes = int(rate_bytes) rng_device.rate_period = int(period) rng_path = CONF.libvirt.rng_dev_path if (rng_path and not os.path.exists(rng_path)): raise exception.RngDeviceNotExist(path=rng_path) rng_device.backend = rng_path guest.add_device(rng_device) def _set_qemu_guest_agent(self, guest, flavor, instance, image_meta): # Enable qga only if the 'hw_qemu_guest_agent' is equal to yes if image_meta.properties.get('hw_qemu_guest_agent', False): LOG.debug("Qemu guest agent is enabled through image " "metadata", instance=instance) self._add_qga_device(guest, instance) rng_is_virtio = image_meta.properties.get('hw_rng_model') == 'virtio' rng_allowed_str = flavor.extra_specs.get('hw_rng:allowed', '') rng_allowed = strutils.bool_from_string(rng_allowed_str) if rng_is_virtio and rng_allowed: self._add_rng_device(guest, flavor) def _get_guest_memory_backing_config( self, inst_topology, numatune, flavor): wantsmempages = False if inst_topology: for cell in inst_topology.cells: if cell.pagesize: wantsmempages = True break wantsrealtime = hardware.is_realtime_enabled(flavor) membacking = None if wantsmempages: pages = self._get_memory_backing_hugepages_support( inst_topology, numatune) if pages: membacking = vconfig.LibvirtConfigGuestMemoryBacking() membacking.hugepages = pages if wantsrealtime: if not membacking: membacking = vconfig.LibvirtConfigGuestMemoryBacking() membacking.locked = True membacking.sharedpages = False return membacking def _get_memory_backing_hugepages_support(self, inst_topology, numatune): if not self._has_hugepage_support(): # We should not get here, since we should have avoided # reporting NUMA topology from _get_host_numa_topology # in the first place. Just in case of a scheduler # mess up though, raise an exception raise exception.MemoryPagesUnsupported() host_topology = self._get_host_numa_topology() if host_topology is None: # As above, we should not get here but just in case... raise exception.MemoryPagesUnsupported() # Currently libvirt does not support the smallest # pagesize set as a backend memory. # https://bugzilla.redhat.com/show_bug.cgi?id=1173507 avail_pagesize = [page.size_kb for page in host_topology.cells[0].mempages] avail_pagesize.sort() smallest = avail_pagesize[0] pages = [] for guest_cellid, inst_cell in enumerate(inst_topology.cells): if inst_cell.pagesize and inst_cell.pagesize > smallest: for memnode in numatune.memnodes: if guest_cellid == memnode.cellid: page = ( vconfig.LibvirtConfigGuestMemoryBackingPage()) page.nodeset = [guest_cellid] page.size_kb = inst_cell.pagesize pages.append(page) break # Quit early... return pages def _get_flavor(self, ctxt, instance, flavor): if flavor is not None: return flavor return instance.flavor def _has_uefi_support(self): # This means that the host can support uefi booting for guests supported_archs = [arch.X86_64, arch.AARCH64] caps = self._host.get_capabilities() return ((caps.host.cpu.arch in supported_archs) and self._host.has_min_version(MIN_LIBVIRT_UEFI_VERSION) and os.path.exists(DEFAULT_UEFI_LOADER_PATH[caps.host.cpu.arch])) def _get_supported_perf_events(self): if (len(CONF.libvirt.enabled_perf_events) == 0 or not self._host.has_min_version(MIN_LIBVIRT_PERF_VERSION)): return [] supported_events = [] host_cpu_info = self._get_cpu_info() for event in CONF.libvirt.enabled_perf_events: if self._supported_perf_event(event, host_cpu_info['features']): supported_events.append(event) return supported_events def _supported_perf_event(self, event, cpu_features): libvirt_perf_event_name = LIBVIRT_PERF_EVENT_PREFIX + event.upper() if not hasattr(libvirt, libvirt_perf_event_name): LOG.warning(_LW("Libvirt doesn't support event type %s."), event) return False if (event in PERF_EVENTS_CPU_FLAG_MAPPING and PERF_EVENTS_CPU_FLAG_MAPPING[event] not in cpu_features): LOG.warning(_LW("Host does not support event type %s."), event) return False return True def _configure_guest_by_virt_type(self, guest, virt_type, caps, instance, image_meta, flavor, root_device_name): if virt_type == "xen": if guest.os_type == vm_mode.HVM: guest.os_loader = CONF.libvirt.xen_hvmloader_path elif virt_type in ("kvm", "qemu"): if caps.host.cpu.arch in (arch.I686, arch.X86_64): guest.sysinfo = self._get_guest_config_sysinfo(instance) guest.os_smbios = vconfig.LibvirtConfigGuestSMBIOS() hw_firmware_type = image_meta.properties.get('hw_firmware_type') if hw_firmware_type == fields.FirmwareType.UEFI: if self._has_uefi_support(): global uefi_logged if not uefi_logged: LOG.warning(_LW("uefi support is without some kind of " "functional testing and therefore " "considered experimental.")) uefi_logged = True guest.os_loader = DEFAULT_UEFI_LOADER_PATH[ caps.host.cpu.arch] guest.os_loader_type = "pflash" else: raise exception.UEFINotSupported() guest.os_mach_type = self._get_machine_type(image_meta, caps) if image_meta.properties.get('hw_boot_menu') is None: guest.os_bootmenu = strutils.bool_from_string( flavor.extra_specs.get('hw:boot_menu', 'no')) else: guest.os_bootmenu = image_meta.properties.hw_boot_menu elif virt_type == "lxc": guest.os_init_path = "/sbin/init" guest.os_cmdline = CONSOLE elif virt_type == "uml": guest.os_kernel = "/usr/bin/linux" guest.os_root = root_device_name elif virt_type == "parallels": if guest.os_type == vm_mode.EXE: guest.os_init_path = "/sbin/init" def _conf_non_lxc_uml(self, virt_type, guest, root_device_name, rescue, instance, inst_path, image_meta, disk_info): if rescue: self._set_guest_for_rescue(rescue, guest, inst_path, virt_type, root_device_name) elif instance.kernel_id: self._set_guest_for_inst_kernel(instance, guest, inst_path, virt_type, root_device_name, image_meta) else: guest.os_boot_dev = blockinfo.get_boot_order(disk_info) def _create_consoles(self, virt_type, guest, instance, flavor, image_meta, caps): if virt_type in ("qemu", "kvm"): self._create_serial_console_devices(guest, instance, flavor, image_meta) if caps.host.cpu.arch in (arch.S390, arch.S390X): consolepty = vconfig.LibvirtConfigGuestConsole() consolepty.target_type = "sclp" else: consolepty = vconfig.LibvirtConfigGuestSerial() else: consolepty = vconfig.LibvirtConfigGuestConsole() return consolepty def _cpu_config_to_vcpu_model(self, cpu_config, vcpu_model): if not cpu_config: return if not vcpu_model: vcpu_model = objects.VirtCPUModel() vcpu_model.arch = cpu_config.arch vcpu_model.vendor = cpu_config.vendor vcpu_model.model = cpu_config.model vcpu_model.mode = cpu_config.mode vcpu_model.match = cpu_config.match if cpu_config.sockets: vcpu_model.topology = objects.VirtCPUTopology( sockets=cpu_config.sockets, cores=cpu_config.cores, threads=cpu_config.threads) else: vcpu_model.topology = None features = [objects.VirtCPUFeature( name=f.name, policy=f.policy) for f in cpu_config.features] vcpu_model.features = features return vcpu_model def _vcpu_model_to_cpu_config(self, vcpu_model): cpu_config = vconfig.LibvirtConfigGuestCPU() cpu_config.arch = vcpu_model.arch cpu_config.model = vcpu_model.model cpu_config.mode = vcpu_model.mode cpu_config.match = vcpu_model.match cpu_config.vendor = vcpu_model.vendor if vcpu_model.topology: cpu_config.sockets = vcpu_model.topology.sockets cpu_config.cores = vcpu_model.topology.cores cpu_config.threads = vcpu_model.topology.threads if vcpu_model.features: for f in vcpu_model.features: xf = vconfig.LibvirtConfigGuestCPUFeature() xf.name = f.name xf.policy = f.policy cpu_config.features.add(xf) return cpu_config def _get_guest_config(self, instance, network_info, image_meta, disk_info, rescue=None, block_device_info=None, context=None): LOG.warn("_get_guest_config.............instance:%s" % instance) flavor = instance.flavor inst_path = libvirt_utils.get_instance_path(instance) disk_mapping = disk_info['mapping'] virt_type = CONF.libvirt.virt_type guest = vconfig.LibvirtConfigGuest() LOG.warn("guest----------------------%s" % guest) guest.virt_type = virt_type guest.name = instance.name guest.uuid = instance.uuid guest.memory = flavor.memory_mb * units.Ki guest.vcpus = flavor.vcpus allowed_cpus = hardware.get_vcpu_pin_set() pci_devs = pci_manager.get_instance_pci_devs(instance, 'all') guest_numa_config = self._get_guest_numa_config( instance.numa_topology, flavor, allowed_cpus, image_meta) guest.cpuset = guest_numa_config.cpuset guest.cputune = guest_numa_config.cputune guest.numatune = guest_numa_config.numatune guest.membacking = self._get_guest_memory_backing_config( instance.numa_topology, guest_numa_config.numatune, flavor) guest.metadata.append(self._get_guest_config_meta(context, instance)) guest.idmaps = self._get_guest_idmaps() for event in self._supported_perf_events: guest.add_perf_event(event) self._update_guest_cputune(guest, flavor, virt_type) guest.cpu = self._get_guest_cpu_config( flavor, image_meta, guest_numa_config.numaconfig, instance.numa_topology) # the corresponding config file. instance.vcpu_model = self._cpu_config_to_vcpu_model( guest.cpu, instance.vcpu_model) if 'root' in disk_mapping: root_device_name = block_device.prepend_dev( disk_mapping['root']['dev']) else: root_device_name = None if root_device_name: # NOTE(yamahata): # for nova.api.ec2.cloud.CloudController.get_metadata() instance.root_device_name = root_device_name guest.os_type = (vm_mode.get_from_instance(instance) or self._get_guest_os_type(virt_type)) caps = self._host.get_capabilities() self._configure_guest_by_virt_type(guest, virt_type, caps, instance, image_meta, flavor, root_device_name) if virt_type not in ('lxc', 'uml'): self._conf_non_lxc_uml(virt_type, guest, root_device_name, rescue, instance, inst_path, image_meta, disk_info) self._set_features(guest, instance.os_type, caps, virt_type) self._set_clock(guest, instance.os_type, image_meta, virt_type) storage_configs = self._get_guest_storage_config( instance, image_meta, disk_info, rescue, block_device_info, flavor, guest.os_type) for config in storage_configs: guest.add_device(config) #import pdb #pdb.set_trace() if self.has_cdrom(instance,disk_info) is None: cdrom = vconfig.LibvirtConfigGuestDisk() cdrom.source_type = 'file' cdrom.source_device = 'cdrom' cdrom.target_bus = 'ide' cdrom.target_dev = 'hdc' cdrom.driver_name = 'qemu' cdrom.driver_format = 'raw' def is_iso_image_active(context, fake_image_id): active_iso_images, flug = libvirt_utils.get_active_images(context, 'iso') if flug: fake_active_iso_images = [] for image in active_iso_images: fake_active_iso_images.append( hashlib.sha1(image).hexdigest()) if fake_image_id in fake_active_iso_images: return True else: return False else: return True try: #exist_cdroms = self._list_cdrom(instance) exist_cdroms = self.cdrom_list(instance) found_instance = True except: found_instance = False if found_instance: if exist_cdroms: image_id = exist_cdroms[0].get('image_id', '') if image_id: if not imagecache.iso_base_file_exists(image_id): image_id = '' if (image_id and not is_iso_image_active(context, image_id)): imagecache.remove_base_image(image_id) image_id = '' else: image_id = '' else: disk_format = getattr(image_meta, 'disk_format', '') if disk_format == 'iso': image_id = image_meta.get('id', '') if not image_id: image_id = image_meta['properties'].get('base_image_ref', '') if image_id: image_info = {} image_info['image_id'] = image_id image_id = imagecache.get_cache_fname(image_info, 'image_id') else: image_id = '' if image_id != '': base_url = self.image_cache_manager._get_base() image_url = os.path.join(base_url, image_id) else: image_url = '' cdrom.source_path = image_url guest.add_device(cdrom) for vif in network_info: config = self.vif_driver.get_config( instance, vif, image_meta, flavor, virt_type, self._host) guest.add_device(config) consolepty = self._create_consoles(virt_type, guest, instance, flavor, image_meta, caps) if virt_type != 'parallels': consolepty.type = "pty" guest.add_device(consolepty) pointer = self._get_guest_pointer_model(guest.os_type, image_meta) if pointer: guest.add_device(pointer) if (CONF.spice.enabled and CONF.spice.agent_enabled and virt_type not in ('lxc', 'uml', 'xen')): channel = vconfig.LibvirtConfigGuestChannel() channel.target_name = "com.redhat.spice.0" guest.add_device(channel) # NB some versions of libvirt support both SPICE and VNC # at the same time. We're not trying to second guess which # errors appropriately if the user enables both. add_video_driver = False if ((CONF.vnc.enabled and virt_type not in ('lxc', 'uml'))): graphics = vconfig.LibvirtConfigGuestGraphics() graphics.type = "vnc" graphics.passwd = "%s" % instance.get("cipher", "00000") graphics.keymap = CONF.vnc.keymap graphics.listen = CONF.vnc.vncserver_listen guest.add_device(graphics) add_video_driver = True if (CONF.spice.enabled and virt_type not in ('lxc', 'uml', 'xen')): graphics = vconfig.LibvirtConfigGuestGraphics() graphics.type = "spice" graphics.passwd = "%s" % instance.get("cipher", "00000") graphics.keymap = CONF.spice.keymap graphics.listen = CONF.spice.server_listen guest.add_device(graphics) add_video_driver = True if add_video_driver: self._add_video_driver(guest, image_meta, flavor) # Qemu guest agent only support 'qemu' and 'kvm' hypervisor if virt_type in ('qemu', 'kvm'): self._set_qemu_guest_agent(guest, flavor, instance, image_meta) if virt_type in ('xen', 'qemu', 'kvm'): for pci_dev in pci_manager.get_instance_pci_devs(instance): guest.add_device(self._get_guest_pci_device(pci_dev)) else: if len(pci_devs) > 0: raise exception.PciDeviceUnsupportedHypervisor( type=virt_type) if 'hw_watchdog_action' in flavor.extra_specs: LOG.warning(_LW('Old property name "hw_watchdog_action" is now ' 'deprecated and will be removed in the next release. ' 'Use updated property name ' '"hw:watchdog_action" instead'), instance=instance) # TODO(pkholkin): accepting old property name 'hw_watchdog_action' # should be removed in the next release watchdog_action = (flavor.extra_specs.get('hw_watchdog_action') or flavor.extra_specs.get('hw:watchdog_action') or 'disabled') watchdog_action = image_meta.properties.get('hw_watchdog_action', watchdog_action) # NB(sross): currently only actually supported by KVM/QEmu if watchdog_action != 'disabled': if watchdog_actions.is_valid_watchdog_action(watchdog_action): bark = vconfig.LibvirtConfigGuestWatchdog() bark.action = watchdog_action guest.add_device(bark) else: raise exception.InvalidWatchdogAction(action=watchdog_action) # Memory balloon device only support 'qemu/kvm' and 'xen' hypervisor if (virt_type in ('xen', 'qemu', 'kvm') and CONF.libvirt.mem_stats_period_seconds > 0): balloon = vconfig.LibvirtConfigMemoryBalloon() if virt_type in ('qemu', 'kvm'): balloon.model = 'virtio' else: balloon.model = 'xen' balloon.period = CONF.libvirt.mem_stats_period_seconds guest.add_device(balloon) return guest def _get_guest_pointer_model(self, os_type, image_meta): pointer_model = image_meta.properties.get( 'hw_pointer_model', CONF.pointer_model) if pointer_model is None and CONF.libvirt.use_usb_tablet: # TODO(sahid): We set pointer_model to keep compatibility # until the next release O*. It means operators can continue # to use the deprecated option "use_usb_tablet" or set a # specific device to use pointer_model = "usbtablet" LOG.warning(_LW('The option "use_usb_tablet" has been ' 'deprecated for Newton in favor of the more ' 'generic "pointer_model". Please update ' 'nova.conf to address this change.')) if pointer_model == "usbtablet": # We want a tablet if VNC is enabled, or SPICE is enabled and # the SPICE agent is disabled. If the SPICE agent is enabled # it provides a paravirt mouse which drastically reduces # overhead (by eliminating USB polling). if CONF.vnc.enabled or ( CONF.spice.enabled and not CONF.spice.agent_enabled): return self._get_guest_usb_tablet(os_type) else: if CONF.pointer_model or CONF.libvirt.use_usb_tablet: # For backward compatibility We don't want to break LOG.warning(_LW('USB tablet requested for guests by host ' 'configuration. In order to accept this ' 'request VNC should be enabled or SPICE ' 'and SPICE agent disabled on host.')) else: raise exception.UnsupportedPointerModelRequested( model="usbtablet") def _get_guest_usb_tablet(self, os_type): tablet = None if os_type == vm_mode.HVM: tablet = vconfig.LibvirtConfigGuestInput() tablet.type = "tablet" tablet.bus = "usb" else: if CONF.pointer_model or CONF.libvirt.use_usb_tablet: # process of booting an instance if virtual machine mode # is not configured as HVM. LOG.warning(_LW('USB tablet requested for guests by host ' 'configuration. In order to accept this ' 'request the machine mode should be ' 'configured as HVM.')) else: raise exception.UnsupportedPointerModelRequested( model="usbtablet") return tablet def _get_guest_xml(self, context, instance, network_info, disk_info, image_meta, rescue=None, block_device_info=None, write_to_disk=False): # NOTE(danms): Stringifying a NetworkInfo will take a lock. Do # this ahead of time so that we don't acquire it while also network_info_str = str(network_info) msg = ('Start _get_guest_xml ' 'network_info=%(network_info)s ' 'disk_info=%(disk_info)s ' 'image_meta=%(image_meta)s rescue=%(rescue)s ' 'block_device_info=%(block_device_info)s' % {'network_info': network_info_str, 'disk_info': disk_info, 'image_meta': image_meta, 'rescue': rescue, 'block_device_info': block_device_info}) LOG.debug(strutils.mask_password(msg), instance=instance) conf = self._get_guest_config(instance, network_info, image_meta, disk_info, rescue, block_device_info, context) xml = conf.to_xml() if write_to_disk: instance_dir = libvirt_utils.get_instance_path(instance) xml_path = os.path.join(instance_dir, 'libvirt.xml') libvirt_utils.write_to_file(xml_path, xml) LOG.debug('End _get_guest_xml xml=%(xml)s', {'xml': xml}, instance=instance) return xml def get_info(self, instance): guest = self._host.get_guest(instance) return guest.get_info(self._host) def _create_domain_setup_lxc(self, instance, image_meta, block_device_info, disk_info): inst_path = libvirt_utils.get_instance_path(instance) disk_info = disk_info or {} disk_mapping = disk_info.get('mapping', {}) if self._is_booted_from_volume(instance, disk_mapping): block_device_mapping = driver.block_device_info_get_mapping( block_device_info) root_disk = block_device.get_root_bdm(block_device_mapping) disk_info = blockinfo.get_info_from_bdm( instance, CONF.libvirt.virt_type, image_meta, root_disk) self._connect_volume(root_disk['connection_info'], disk_info) disk_path = root_disk['connection_info']['data']['device_path'] # disk is backed by a local block device. image_model = imgmodel.LocalBlockImage(disk_path) else: image = self.image_backend.image(instance, 'disk') image_model = image.get_model(self._conn) container_dir = os.path.join(inst_path, 'rootfs') fileutils.ensure_tree(container_dir) rootfs_dev = disk_api.setup_container(image_model, container_dir=container_dir) try: # Save rootfs device to disconnect it when deleting the instance if rootfs_dev: instance.system_metadata['rootfs_device_name'] = rootfs_dev if CONF.libvirt.uid_maps or CONF.libvirt.gid_maps: id_maps = self._get_guest_idmaps() libvirt_utils.chown_for_id_maps(container_dir, id_maps) except Exception: with excutils.save_and_reraise_exception(): self._create_domain_cleanup_lxc(instance) def _create_domain_cleanup_lxc(self, instance): inst_path = libvirt_utils.get_instance_path(instance) container_dir = os.path.join(inst_path, 'rootfs') try: state = self.get_info(instance).state except exception.InstanceNotFound: # The domain may not be present if the instance failed to start state = None if state == power_state.RUNNING: # NOTE(uni): Now the container is running with its own private # mount namespace and so there is no need to keep the container # rootfs mounted in the host namespace LOG.debug('Attempting to unmount container filesystem: %s', container_dir, instance=instance) disk_api.clean_lxc_namespace(container_dir=container_dir) else: disk_api.teardown_container(container_dir=container_dir) @contextlib.contextmanager def _lxc_disk_handler(self, instance, image_meta, block_device_info, disk_info): if CONF.libvirt.virt_type != 'lxc': yield return self._create_domain_setup_lxc(instance, image_meta, block_device_info, disk_info) try: yield finally: self._create_domain_cleanup_lxc(instance) # TODO(sahid): Consider renaming this to _create_guest. def _create_domain(self, xml=None, domain=None, power_on=True, pause=False, post_xml_callback=None): if xml: guest = libvirt_guest.Guest.create(xml, self._host) if post_xml_callback is not None: post_xml_callback() else: guest = libvirt_guest.Guest(domain) if power_on or pause: guest.launch(pause=pause) if not utils.is_neutron(): guest.enable_hairpin() return guest def _neutron_failed_callback(self, event_name, instance): LOG.error(_LE('Neutron Reported failure on event ' '%(event)s for instance %(uuid)s'), {'event': event_name, 'uuid': instance.uuid}, instance=instance) if CONF.vif_plugging_is_fatal: raise exception.VirtualInterfaceCreateException() def _get_neutron_events(self, network_info): # NOTE(danms): We need to collect any VIFs that are currently # down that we expect a down->up event for. Anything that is # already up will not undergo that transition, and for # anything that might be stale (cache-wise) assume it's return [('network-vif-plugged', vif['id']) for vif in network_info if vif.get('active', True) is False] def _create_domain_and_network(self, context, xml, instance, network_info, disk_info, block_device_info=None, power_on=True, reboot=False, vifs_already_plugged=False, post_xml_callback=None): block_device_mapping = driver.block_device_info_get_mapping( block_device_info) for vol in block_device_mapping: connection_info = vol['connection_info'] if (not reboot and 'data' in connection_info and 'volume_id' in connection_info['data']): volume_id = connection_info['data']['volume_id'] encryption = encryptors.get_encryption_metadata( context, self._volume_api, volume_id, connection_info) if encryption: encryptor = self._get_volume_encryptor(connection_info, encryption) encryptor.attach_volume(context, **encryption) timeout = CONF.vif_plugging_timeout if (self._conn_supports_start_paused and utils.is_neutron() and not vifs_already_plugged and power_on and timeout): events = self._get_neutron_events(network_info) else: events = [] pause = bool(events) guest = None try: with self.virtapi.wait_for_instance_event( instance, events, deadline=timeout, error_callback=self._neutron_failed_callback): self.plug_vifs(instance, network_info) self.firewall_driver.setup_basic_filtering(instance, network_info) self.firewall_driver.prepare_instance_filter(instance, network_info) with self._lxc_disk_handler(instance, instance.image_meta, block_device_info, disk_info): guest = self._create_domain( xml, pause=pause, power_on=power_on, post_xml_callback=post_xml_callback) self.firewall_driver.apply_instance_filter(instance, network_info) except exception.VirtualInterfaceCreateException: # Neutron reported failure and we didn't swallow it, so with excutils.save_and_reraise_exception(): if guest: guest.poweroff() self.cleanup(context, instance, network_info=network_info, block_device_info=block_device_info) except eventlet.timeout.Timeout: LOG.warning(_LW('Timeout waiting for vif plugging callback for ' 'instance %(uuid)s'), {'uuid': instance.uuid}, instance=instance) if CONF.vif_plugging_is_fatal: if guest: guest.poweroff() self.cleanup(context, instance, network_info=network_info, block_device_info=block_device_info) raise exception.VirtualInterfaceCreateException() if pause: guest.resume() return guest def _get_vcpu_total(self): try: total_pcpus = self._host.get_cpu_count() except libvirt.libvirtError: LOG.warning(_LW("Cannot get the number of cpu, because this " "function is not implemented for this platform. ")) return 0 if not CONF.vcpu_pin_set: return total_pcpus available_ids = hardware.get_vcpu_pin_set() online_pcpus = None try: online_pcpus = self._host.get_online_cpus() except libvirt.libvirtError as ex: error_code = ex.get_error_code() LOG.warning( _LW("Couldn't retrieve the online CPUs due to a Libvirt " "error: %(error)s with error code: %(error_code)s"), {'error': ex, 'error_code': error_code}) if online_pcpus: if not (available_ids <= online_pcpus): msg = (_("Invalid vcpu_pin_set config, one or more of the " "specified cpuset is not online. Online cpuset(s): " "%(online)s, requested cpuset(s): %(req)s"), {'online': sorted(online_pcpus), 'req': sorted(available_ids)}) raise exception.Invalid(msg) elif sorted(available_ids)[-1] >= total_pcpus: raise exception.Invalid(_("Invalid vcpu_pin_set config, " "out of hypervisor cpu range.")) return len(available_ids) @staticmethod def _get_local_gb_info(): if CONF.libvirt.images_type == 'lvm': info = lvm.get_volume_group_info( CONF.libvirt.images_volume_group) elif CONF.libvirt.images_type == 'rbd': info = LibvirtDriver._get_rbd_driver().get_pool_info() else: info = libvirt_utils.get_fs_info(CONF.instances_path) for (k, v) in six.iteritems(info): info[k] = v / units.Gi return info def _get_vcpu_used(self): total = 0 if CONF.libvirt.virt_type == 'lxc': return total + 1 for guest in self._host.list_guests(): try: vcpus = guest.get_vcpus_info() if vcpus is not None: total += len(list(vcpus)) except libvirt.libvirtError as e: LOG.warning( _LW("couldn't obtain the vcpu count from domain id:" " %(uuid)s, exception: %(ex)s"), {"uuid": guest.uuid, "ex": e}) greenthread.sleep(0) return total def _get_instance_capabilities(self): caps = self._host.get_capabilities() instance_caps = list() for g in caps.guests: for dt in g.domtype: instance_cap = ( arch.canonicalize(g.arch), hv_type.canonicalize(dt), vm_mode.canonicalize(g.ostype)) instance_caps.append(instance_cap) return instance_caps def _get_cpu_info(self): caps = self._host.get_capabilities() cpu_info = dict() cpu_info['arch'] = caps.host.cpu.arch cpu_info['model'] = caps.host.cpu.model cpu_info['vendor'] = caps.host.cpu.vendor topology = dict() topology['cells'] = len(getattr(caps.host.topology, 'cells', [1])) topology['sockets'] = caps.host.cpu.sockets topology['cores'] = caps.host.cpu.cores topology['threads'] = caps.host.cpu.threads cpu_info['topology'] = topology features = set() for f in caps.host.cpu.features: features.add(f.name) cpu_info['features'] = features return cpu_info def _get_pcidev_info(self, devname): def _get_device_type(cfgdev, pci_address): for fun_cap in cfgdev.pci_capability.fun_capability: if fun_cap.type == 'virt_functions': return { 'dev_type': fields.PciDeviceType.SRIOV_PF, } if (fun_cap.type == 'phys_function' and len(fun_cap.device_addrs) != 0): phys_address = "%04x:%02x:%02x.%01x" % ( fun_cap.device_addrs[0][0], fun_cap.device_addrs[0][1], fun_cap.device_addrs[0][2], fun_cap.device_addrs[0][3]) return { 'dev_type': fields.PciDeviceType.SRIOV_VF, 'parent_addr': phys_address, } if not self._host.has_min_version( MIN_LIBVIRT_PF_WITH_NO_VFS_CAP_VERSION): is_physical_function = pci_utils.is_physical_function( *pci_utils.get_pci_address_fields(pci_address)) if is_physical_function: return {'dev_type': fields.PciDeviceType.SRIOV_PF} return {'dev_type': fields.PciDeviceType.STANDARD} virtdev = self._host.device_lookup_by_name(devname) xmlstr = virtdev.XMLDesc(0) cfgdev = vconfig.LibvirtConfigNodeDevice() cfgdev.parse_str(xmlstr) address = "%04x:%02x:%02x.%1x" % ( cfgdev.pci_capability.domain, cfgdev.pci_capability.bus, cfgdev.pci_capability.slot, cfgdev.pci_capability.function) device = { "dev_id": cfgdev.name, "address": address, "product_id": "%04x" % cfgdev.pci_capability.product_id, "vendor_id": "%04x" % cfgdev.pci_capability.vendor_id, } device["numa_node"] = cfgdev.pci_capability.numa_node device['label'] = 'label_%(vendor_id)s_%(product_id)s' % device device.update(_get_device_type(cfgdev, address)) return device def _get_pci_passthrough_devices(self): # repeated warnings within a periodic task if not getattr(self, '_list_devices_supported', True): return jsonutils.dumps([]) try: dev_names = self._host.list_pci_devices() or [] except libvirt.libvirtError as ex: error_code = ex.get_error_code() if error_code == libvirt.VIR_ERR_NO_SUPPORT: self._list_devices_supported = False LOG.warning(_LW("URI %(uri)s does not support " "listDevices: %(error)s"), {'uri': self._uri(), 'error': ex}) return jsonutils.dumps([]) else: raise pci_info = [] for name in dev_names: pci_info.append(self._get_pcidev_info(name)) return jsonutils.dumps(pci_info) def _has_numa_support(self): # This means that the host can support LibvirtConfigGuestNUMATune # and the nodeset field in LibvirtConfigGuestMemoryBackingPage for ver in BAD_LIBVIRT_NUMA_VERSIONS: if self._host.has_version(ver): if not getattr(self, '_bad_libvirt_numa_version_warn', False): LOG.warning(_LW('You are running with libvirt version %s ' 'which is known to have broken NUMA support. ' 'Consider patching or updating libvirt on ' 'this host if you need NUMA support.'), self._version_to_string(ver)) self._bad_libvirt_numa_version_warn = True return False support_matrix = {(arch.I686, arch.X86_64): MIN_LIBVIRT_NUMA_VERSION, (arch.PPC64, arch.PPC64LE): MIN_LIBVIRT_NUMA_VERSION_PPC} caps = self._host.get_capabilities() is_supported = False for archs, libvirt_ver in support_matrix.items(): if ((caps.host.cpu.arch in archs) and self._host.has_min_version(libvirt_ver, MIN_QEMU_NUMA_HUGEPAGE_VERSION, host.HV_DRIVER_QEMU)): is_supported = True return is_supported def _has_hugepage_support(self): # This means that the host can support multiple values for the size # field in LibvirtConfigGuestMemoryBackingPage supported_archs = [arch.I686, arch.X86_64, arch.PPC64LE, arch.PPC64] caps = self._host.get_capabilities() return ((caps.host.cpu.arch in supported_archs) and self._host.has_min_version(MIN_LIBVIRT_HUGEPAGE_VERSION, MIN_QEMU_NUMA_HUGEPAGE_VERSION, host.HV_DRIVER_QEMU)) def _get_host_numa_topology(self): if not self._has_numa_support(): return caps = self._host.get_capabilities() topology = caps.host.topology if topology is None or not topology.cells: return cells = [] allowed_cpus = hardware.get_vcpu_pin_set() online_cpus = self._host.get_online_cpus() if allowed_cpus: allowed_cpus &= online_cpus else: allowed_cpus = online_cpus def _get_reserved_memory_for_cell(self, cell_id, page_size): cell = self._reserved_hugepages.get(cell_id, {}) return cell.get(page_size, 0) for cell in topology.cells: cpuset = set(cpu.id for cpu in cell.cpus) siblings = sorted(map(set, set(tuple(cpu.siblings) if cpu.siblings else () for cpu in cell.cpus) )) cpuset &= allowed_cpus siblings = [sib & allowed_cpus for sib in siblings] # Filter out singles and empty sibling sets that may be left siblings = [sib for sib in siblings if len(sib) > 1] mempages = [] if self._has_hugepage_support(): mempages = [ objects.NUMAPagesTopology( size_kb=pages.size, total=pages.total, used=0, reserved=_get_reserved_memory_for_cell( self, cell.id, pages.size)) for pages in cell.mempages] cell = objects.NUMACell(id=cell.id, cpuset=cpuset, memory=cell.memory / units.Ki, cpu_usage=0, memory_usage=0, siblings=siblings, pinned_cpus=set([]), mempages=mempages) cells.append(cell) return objects.NUMATopology(cells=cells) def get_all_volume_usage(self, context, compute_host_bdms): vol_usage = [] for instance_bdms in compute_host_bdms: instance = instance_bdms['instance'] for bdm in instance_bdms['instance_bdms']: mountpoint = bdm['device_name'] if mountpoint.startswith('/dev/'): mountpoint = mountpoint[5:] volume_id = bdm['volume_id'] LOG.debug("Trying to get stats for the volume %s", volume_id, instance=instance) vol_stats = self.block_stats(instance, mountpoint) if vol_stats: stats = dict(volume=volume_id, instance=instance, rd_req=vol_stats[0], rd_bytes=vol_stats[1], wr_req=vol_stats[2], wr_bytes=vol_stats[3]) LOG.debug( "Got volume usage stats for the volume=%(volume)s," " rd_req=%(rd_req)d, rd_bytes=%(rd_bytes)d, " "wr_req=%(wr_req)d, wr_bytes=%(wr_bytes)d", stats, instance=instance) vol_usage.append(stats) return vol_usage def block_stats(self, instance, disk_id): try: guest = self._host.get_guest(instance) # TODO(sahid): We are converting all calls from a # virDomain object to use nova.virt.libvirt.Guest. # We should be able to remove domain at the end. domain = guest._domain return domain.blockStats(disk_id) except libvirt.libvirtError as e: errcode = e.get_error_code() LOG.info(_LI('Getting block stats failed, device might have ' 'been detached. Instance=%(instance_name)s ' 'Disk=%(disk)s Code=%(errcode)s Error=%(e)s'), {'instance_name': instance.name, 'disk': disk_id, 'errcode': errcode, 'e': e}, instance=instance) except exception.InstanceNotFound: LOG.info(_LI('Could not find domain in libvirt for instance %s. ' 'Cannot get block stats for device'), instance.name, instance=instance) def get_console_pool_info(self, console_type): # TODO(mdragon): console proxy should be implemented for libvirt, # in case someone wants to use it with kvm or # such. For now return fake data. return {'address': '127.0.0.1', 'username': 'fakeuser', 'password': 'fakepassword'} def refresh_security_group_rules(self, security_group_id): self.firewall_driver.refresh_security_group_rules(security_group_id) def refresh_instance_security_rules(self, instance): self.firewall_driver.refresh_instance_security_rules(instance) def get_available_resource(self, nodename): disk_info_dict = self._get_local_gb_info() data = {} # NOTE(dprince): calling capabilities before getVersion works around # an initialization issue with some versions of Libvirt (1.0.5.5). # See: https://bugzilla.redhat.com/show_bug.cgi?id=1000116 # See: https://bugs.launchpad.net/nova/+bug/1215593 data["supported_instances"] = self._get_instance_capabilities() data["vcpus"] = self._get_vcpu_total() data["memory_mb"] = self._host.get_memory_mb_total() data["local_gb"] = disk_info_dict['total'] data["vcpus_used"] = self._get_vcpu_used() data["memory_mb_used"] = self._host.get_memory_mb_used() data["local_gb_used"] = disk_info_dict['used'] data["hypervisor_type"] = self._host.get_driver_type() data["hypervisor_version"] = self._host.get_version() data["hypervisor_hostname"] = self._host.get_hostname() # TODO(berrange): why do we bother converting the # libvirt capabilities XML into a special JSON format ? # The data format is different across all the drivers # so we could just return the raw capabilities XML # which 'compare_cpu' could use directly # # That said, arch_filter.py now seems to rely on # the libvirt drivers format which suggests this # data format needs to be standardized across drivers data["cpu_info"] = jsonutils.dumps(self._get_cpu_info()) disk_free_gb = disk_info_dict['free'] disk_over_committed = self._get_disk_over_committed_size_total() available_least = disk_free_gb * units.Gi - disk_over_committed data['disk_available_least'] = available_least / units.Gi data['pci_passthrough_devices'] = \ self._get_pci_passthrough_devices() numa_topology = self._get_host_numa_topology() if numa_topology: data['numa_topology'] = numa_topology._to_json() else: data['numa_topology'] = None return data def check_instance_shared_storage_local(self, context, instance): if self.image_backend.backend().is_shared_block_storage(): return None dirpath = libvirt_utils.get_instance_path(instance) if not os.path.exists(dirpath): return None fd, tmp_file = tempfile.mkstemp(dir=dirpath) LOG.debug("Creating tmpfile %s to verify with other " "compute node that the instance is on " "the same shared storage.", tmp_file, instance=instance) os.close(fd) return {"filename": tmp_file} def check_instance_shared_storage_remote(self, context, data): return os.path.exists(data['filename']) def check_instance_shared_storage_cleanup(self, context, data): fileutils.delete_if_exists(data["filename"]) def check_can_live_migrate_destination(self, context, instance, src_compute_info, dst_compute_info, block_migration=False, disk_over_commit=False): disk_available_gb = dst_compute_info['disk_available_least'] disk_available_mb = ( (disk_available_gb * units.Ki) - CONF.reserved_host_disk_mb) # Compare CPU if not instance.vcpu_model or not instance.vcpu_model.model: source_cpu_info = src_compute_info['cpu_info'] self._compare_cpu(None, source_cpu_info, instance) else: self._compare_cpu(instance.vcpu_model, None, instance) # Create file on storage, to be checked on source host filename = self._create_shared_storage_test_file(instance) data = objects.LibvirtLiveMigrateData() data.filename = filename data.image_type = CONF.libvirt.images_type # Notes(eliqiao): block_migration and disk_over_commit are not # nullable, so just don't set them if they are None if block_migration is not None: data.block_migration = block_migration if disk_over_commit is not None: data.disk_over_commit = disk_over_commit data.disk_available_mb = disk_available_mb return data def cleanup_live_migration_destination_check(self, context, dest_check_data): filename = dest_check_data.filename self._cleanup_shared_storage_test_file(filename) def check_can_live_migrate_source(self, context, instance, dest_check_data, block_device_info=None): if not isinstance(dest_check_data, migrate_data_obj.LiveMigrateData): md_obj = objects.LibvirtLiveMigrateData() md_obj.from_legacy_dict(dest_check_data) dest_check_data = md_obj source = CONF.host dest_check_data.is_shared_instance_path = ( self._check_shared_storage_test_file( dest_check_data.filename, instance)) dest_check_data.is_shared_block_storage = ( self._is_shared_block_storage(instance, dest_check_data, block_device_info)) disk_info_text = self.get_instance_disk_info( instance, block_device_info=block_device_info) booted_from_volume = self._is_booted_from_volume(instance, disk_info_text) has_local_disk = self._has_local_disk(instance, disk_info_text) if 'block_migration' not in dest_check_data: dest_check_data.block_migration = ( not dest_check_data.is_on_shared_storage()) if dest_check_data.block_migration: if dest_check_data.is_on_shared_storage(): reason = _("Block migration can not be used " "with shared storage.") raise exception.InvalidLocalStorage(reason=reason, path=source) if 'disk_over_commit' in dest_check_data: self._assert_dest_node_has_enough_disk(context, instance, dest_check_data.disk_available_mb, dest_check_data.disk_over_commit, block_device_info) if block_device_info: bdm = block_device_info.get('block_device_mapping') # migration is tunnelled through libvirt. if bdm and not self._host.has_min_version( MIN_LIBVIRT_BLOCK_LM_WITH_VOLUMES_VERSION): # NOTE(stpierre): if this instance has mapped volumes, # we can't do a block migration, since that will result ver = ".".join([str(x) for x in MIN_LIBVIRT_BLOCK_LM_WITH_VOLUMES_VERSION]) msg = (_('Cannot block migrate instance %(uuid)s with' ' mapped volumes. Selective block device' ' migration feature requires libvirt version' ' %(libvirt_ver)s') % {'uuid': instance.uuid, 'libvirt_ver': ver}) LOG.error(msg, instance=instance) raise exception.MigrationPreCheckError(reason=msg) if (bdm and (self._block_migration_flags & libvirt.VIR_MIGRATE_TUNNELLED != 0)): msg = (_('Cannot block migrate instance %(uuid)s with' ' mapped volumes. Selective block device' ' migration is not supported with tunnelled' ' block migrations.') % {'uuid': instance.uuid}) LOG.error(msg, instance=instance) raise exception.MigrationPreCheckError(reason=msg) elif not (dest_check_data.is_shared_block_storage or dest_check_data.is_shared_instance_path or (booted_from_volume and not has_local_disk)): reason = _("Live migration can not be used " "without shared storage except " "a booted from volume VM which " "does not have a local disk.") raise exception.InvalidSharedStorage(reason=reason, path=source) # same name to be used instance_path = libvirt_utils.get_instance_path(instance, relative=True) dest_check_data.instance_relative_path = instance_path return dest_check_data def _is_shared_block_storage(self, instance, dest_check_data, block_device_info=None): if (dest_check_data.obj_attr_is_set('image_type') and CONF.libvirt.images_type == dest_check_data.image_type and self.image_backend.backend().is_shared_block_storage()): # NOTE(dgenin): currently true only for RBD image backend return True if (dest_check_data.is_shared_instance_path and self.image_backend.backend().is_file_in_instance_path()): # NOTE(angdraug): file based image backends (Flat, Qcow2) # place block device files under the instance path return True if (dest_check_data.is_volume_backed and not bool(jsonutils.loads( self.get_instance_disk_info(instance, block_device_info)))): return True return False def _assert_dest_node_has_enough_disk(self, context, instance, available_mb, disk_over_commit, block_device_info=None): # Libvirt supports qcow2 disk format,which is usually compressed # on compute nodes. # Real disk image (compressed) may enlarged to "virtual disk size", # that is specified as the maximum disk size. # (See qemu-img -f path-to-disk) # Scheduler recognizes destination host still has enough disk space # if real disk size < available disk size # if disk_over_commit is True, # otherwise virtual disk size < available disk size. available = 0 if available_mb: available = available_mb * units.Mi ret = self.get_instance_disk_info(instance, block_device_info=block_device_info) disk_infos = jsonutils.loads(ret) necessary = 0 if disk_over_commit: for info in disk_infos: necessary += int(info['disk_size']) else: for info in disk_infos: necessary += int(info['virt_disk_size']) # Check that available disk > necessary disk if (available - necessary) < 0: reason = (_('Unable to migrate %(instance_uuid)s: ' 'Disk of instance is too large(available' ' on destination host:%(available)s ' '< need:%(necessary)s)') % {'instance_uuid': instance.uuid, 'available': available, 'necessary': necessary}) raise exception.MigrationPreCheckError(reason=reason) def _compare_cpu(self, guest_cpu, host_cpu_str, instance): # NOTE(kchamart): Comparing host to guest CPU model for emulated # guests (<domain type='qemu'>) should not matter -- in this # mode (QEMU "TCG") the CPU is fully emulated in software and no # hardware acceleration, like KVM, is involved. So, skip the CPU # compatibility check for the QEMU domain type, and retain it for # KVM guests. if CONF.libvirt.virt_type not in ['kvm']: return if guest_cpu is None: info = jsonutils.loads(host_cpu_str) LOG.info(_LI('Instance launched has CPU info: %s'), host_cpu_str) cpu = vconfig.LibvirtConfigCPU() cpu.arch = info['arch'] cpu.model = info['model'] cpu.vendor = info['vendor'] cpu.sockets = info['topology']['sockets'] cpu.cores = info['topology']['cores'] cpu.threads = info['topology']['threads'] for f in info['features']: cpu.add_feature(vconfig.LibvirtConfigCPUFeature(f)) else: cpu = self._vcpu_model_to_cpu_config(guest_cpu) u = ("http://libvirt.org/html/libvirt-libvirt-host.html#" "virCPUCompareResult") m = _("CPU doesn't have compatibility.\n\n%(ret)s\n\nRefer to %(u)s") try: cpu_xml = cpu.to_xml() LOG.debug("cpu compare xml: %s", cpu_xml, instance=instance) ret = self._host.compare_cpu(cpu_xml) except libvirt.libvirtError as e: error_code = e.get_error_code() if error_code == libvirt.VIR_ERR_NO_SUPPORT: LOG.debug("URI %(uri)s does not support cpu comparison. " "It will be proceeded though. Error: %(error)s", {'uri': self._uri(), 'error': e}) return else: LOG.error(m, {'ret': e, 'u': u}) raise exception.MigrationPreCheckError( reason=m % {'ret': e, 'u': u}) if ret <= 0: LOG.error(m, {'ret': ret, 'u': u}) raise exception.InvalidCPUInfo(reason=m % {'ret': ret, 'u': u}) def _create_shared_storage_test_file(self, instance): dirpath = CONF.instances_path fd, tmp_file = tempfile.mkstemp(dir=dirpath) LOG.debug("Creating tmpfile %s to notify to other " "compute nodes that they should mount " "the same storage.", tmp_file, instance=instance) os.close(fd) return os.path.basename(tmp_file) def _check_shared_storage_test_file(self, filename, instance): os.utime(CONF.instances_path, None) tmp_file = os.path.join(CONF.instances_path, filename) if not os.path.exists(tmp_file): exists = False else: exists = True LOG.debug('Check if temp file %s exists to indicate shared storage ' 'is being used for migration. Exists? %s', tmp_file, exists, instance=instance) return exists def _cleanup_shared_storage_test_file(self, filename): tmp_file = os.path.join(CONF.instances_path, filename) os.remove(tmp_file) def ensure_filtering_rules_for_instance(self, instance, network_info): self.firewall_driver.setup_basic_filtering(instance, network_info) self.firewall_driver.prepare_instance_filter(instance, network_info) timeout_count = list(range(CONF.live_migration_retry_count)) while timeout_count: if self.firewall_driver.instance_filter_exists(instance, network_info): break timeout_count.pop() if len(timeout_count) == 0: msg = _('The firewall filter for %s does not exist') raise exception.NovaException(msg % instance.name) greenthread.sleep(1) def filter_defer_apply_on(self): self.firewall_driver.filter_defer_apply_on() def filter_defer_apply_off(self): self.firewall_driver.filter_defer_apply_off() def live_migration(self, context, instance, dest, post_method, recover_method, block_migration=False, migrate_data=None): # exploit the URI accepted by libivrt if not libvirt_utils.is_valid_hostname(dest): raise exception.InvalidHostname(hostname=dest) self._live_migration(context, instance, dest, post_method, recover_method, block_migration, migrate_data) def live_migration_abort(self, instance): guest = self._host.get_guest(instance) dom = guest._domain try: dom.abortJob() except libvirt.libvirtError as e: LOG.error(_LE("Failed to cancel migration %s"), e, instance=instance) raise def _check_graphics_addresses_can_live_migrate(self, listen_addrs): LOCAL_ADDRS = ('0.0.0.0', '127.0.0.1', '::', '::1') local_vnc = CONF.vnc.vncserver_listen in LOCAL_ADDRS local_spice = CONF.spice.server_listen in LOCAL_ADDRS if ((CONF.vnc.enabled and not local_vnc) or (CONF.spice.enabled and not local_spice)): msg = _('Your libvirt version does not support the' ' VIR_DOMAIN_XML_MIGRATABLE flag or your' ' destination node does not support' ' retrieving listen addresses. In order' ' for live migration to work properly, you' ' must configure the graphics (VNC and/or' ' SPICE) listen addresses to be either' ' the catch-all address (0.0.0.0 or ::) or' ' the local address (127.0.0.1 or ::1).') raise exception.MigrationError(reason=msg) if listen_addrs: dest_local_vnc = listen_addrs.get('vnc') in LOCAL_ADDRS dest_local_spice = listen_addrs.get('spice') in LOCAL_ADDRS if ((CONF.vnc.enabled and not dest_local_vnc) or (CONF.spice.enabled and not dest_local_spice)): LOG.warning(_LW('Your libvirt version does not support the' ' VIR_DOMAIN_XML_MIGRATABLE flag, and the' ' graphics (VNC and/or SPICE) listen' ' addresses on the destination node do not' ' match the addresses on the source node.' ' Since the source node has listen' ' addresses set to either the catch-all' ' address (0.0.0.0 or ::) or the local' ' address (127.0.0.1 or ::1), the live' ' migration will succeed, but the VM will' ' continue to listen on the current' ' addresses.')) def _verify_serial_console_is_disabled(self): if CONF.serial_console.enabled: msg = _('Your libvirt version does not support the' ' VIR_DOMAIN_XML_MIGRATABLE flag or your' ' destination node does not support' ' retrieving listen addresses. In order' ' for live migration to work properly you' ' must either disable serial console or' ' upgrade your libvirt version.') raise exception.MigrationError(reason=msg) def _live_migration_operation(self, context, instance, dest, block_migration, migrate_data, guest, device_names): try: if migrate_data.block_migration: migration_flags = self._block_migration_flags else: migration_flags = self._live_migration_flags listen_addrs = libvirt_migrate.graphics_listen_addrs( migrate_data) migratable_flag = self._host.is_migratable_xml_flag() if not migratable_flag or not listen_addrs: # In this context want to ensure we do not have to migrate # graphic or serial consoles since we can't update guest's # domain XML to make it handle destination host. # TODO(alexs-h): These checks could be moved to the # check_can_live_migrate_destination/source phase self._check_graphics_addresses_can_live_migrate(listen_addrs) self._verify_serial_console_is_disabled() if ('target_connect_addr' in migrate_data and migrate_data.target_connect_addr is not None): dest = migrate_data.target_connect_addr new_xml_str = None params = None if (self._host.is_migratable_xml_flag() and ( listen_addrs or migrate_data.bdms)): new_xml_str = libvirt_migrate.get_updated_guest_xml( # TODO(sahid): It's not a really well idea to pass guest, migrate_data, self._get_volume_config) if self._host.has_min_version( MIN_LIBVIRT_BLOCK_LM_WITH_VOLUMES_VERSION): params = { 'bandwidth': CONF.libvirt.live_migration_bandwidth, 'destination_xml': new_xml_str, 'migrate_disks': device_names, } if (migration_flags & libvirt.VIR_MIGRATE_TUNNELLED != 0): params.pop('migrate_disks') guest.migrate(self._live_migration_uri(dest), flags=migration_flags, params=params, domain_xml=new_xml_str, bandwidth=CONF.libvirt.live_migration_bandwidth) except Exception as e: with excutils.save_and_reraise_exception(): LOG.error(_LE("Live Migration failure: %s"), e, instance=instance) # VM instances on each host are in. Possibilities include # # 1. src==running, dst==none # # Migration failed & rolled back, or never started # # 2. src==running, dst==paused # # Migration started but is still ongoing # # 3. src==paused, dst==paused # # Migration data transfer completed, but switchover # is still ongoing, or failed # # 4. src==paused, dst==running # # Migration data transfer completed, switchover # happened but cleanup on source failed # # 5. src==none, dst==running # # Migration fully succeeded. # # Libvirt will aim to complete any migration operation # or roll it back. So even if the migrateToURI call has # returned an error, if the migration was not finished # libvirt should clean up. # # So we take the error raise here with a pinch of salt # and rely on the domain job info status to figure out # what really happened to the VM, which is a much more # reliable indicator. # # In particular we need to try very hard to ensure that # Nova does not "forget" about the guest. ie leaving it # running on a different host to the one recorded in # the database, as that would be a serious resource leak LOG.debug("Migration operation thread has finished", instance=instance) @staticmethod def _migration_downtime_steps(data_gb): downtime = CONF.libvirt.live_migration_downtime steps = CONF.libvirt.live_migration_downtime_steps delay = CONF.libvirt.live_migration_downtime_delay # TODO(hieulq): Need to move min/max value into the config option, # currently oslo_config will raise ValueError instead of setting # option value to its min/max. if downtime < nova.conf.libvirt.LIVE_MIGRATION_DOWNTIME_MIN: downtime = nova.conf.libvirt.LIVE_MIGRATION_DOWNTIME_MIN if steps < nova.conf.libvirt.LIVE_MIGRATION_DOWNTIME_STEPS_MIN: steps = nova.conf.libvirt.LIVE_MIGRATION_DOWNTIME_STEPS_MIN if delay < nova.conf.libvirt.LIVE_MIGRATION_DOWNTIME_DELAY_MIN: delay = nova.conf.libvirt.LIVE_MIGRATION_DOWNTIME_DELAY_MIN delay = int(delay * data_gb) offset = downtime / float(steps + 1) base = (downtime - offset) ** (1 / float(steps)) for i in range(steps + 1): yield (int(delay * i), int(offset + base ** i)) def _live_migration_copy_disk_paths(self, context, instance, guest): disk_paths = [] device_names = [] block_devices = [] # TODO(pkoniszewski): Remove version check when we bump min libvirt # version to >= 1.2.17. if (self._block_migration_flags & libvirt.VIR_MIGRATE_TUNNELLED == 0 and self._host.has_min_version( MIN_LIBVIRT_BLOCK_LM_WITH_VOLUMES_VERSION)): bdm_list = objects.BlockDeviceMappingList.get_by_instance_uuid( context, instance.uuid) block_device_info = driver.get_block_device_info(instance, bdm_list) block_device_mappings = driver.block_device_info_get_mapping( block_device_info) for bdm in block_device_mappings: device_name = str(bdm['mount_device'].rsplit('/', 1)[1]) block_devices.append(device_name) for dev in guest.get_all_disks(): if dev.readonly or dev.shareable: continue if dev.source_type not in ["file", "block"]: continue if dev.target_dev in block_devices: continue disk_paths.append(dev.source_path) device_names.append(dev.target_dev) return (disk_paths, device_names) def _live_migration_data_gb(self, instance, disk_paths): ram_gb = instance.flavor.memory_mb * units.Mi / units.Gi if ram_gb < 2: ram_gb = 2 disk_gb = 0 for path in disk_paths: try: size = os.stat(path).st_size size_gb = (size / units.Gi) if size_gb < 2: size_gb = 2 disk_gb += size_gb except OSError as e: LOG.warning(_LW("Unable to stat %(disk)s: %(ex)s"), {'disk': path, 'ex': e}) # Ignore error since we don't want to break return ram_gb + disk_gb def _get_migration_flags(self, is_block_migration): if is_block_migration: return self._block_migration_flags return self._live_migration_flags def _live_migration_monitor(self, context, instance, guest, dest, post_method, recover_method, block_migration, migrate_data, finish_event, disk_paths): on_migration_failure = deque() data_gb = self._live_migration_data_gb(instance, disk_paths) downtime_steps = list(self._migration_downtime_steps(data_gb)) migration = migrate_data.migration curdowntime = None migration_flags = self._get_migration_flags( migrate_data.block_migration) n = 0 start = time.time() progress_time = start progress_watermark = None previous_data_remaining = -1 is_post_copy_enabled = self._is_post_copy_enabled(migration_flags) while True: info = guest.get_job_info() if info.type == libvirt.VIR_DOMAIN_JOB_NONE: if not finish_event.ready(): LOG.debug("Operation thread is still running", instance=instance) else: info.type = libvirt_migrate.find_job_type(guest, instance) LOG.debug("Fixed incorrect job type to be %d", info.type, instance=instance) if info.type == libvirt.VIR_DOMAIN_JOB_NONE: LOG.debug("Migration not running yet", instance=instance) elif info.type == libvirt.VIR_DOMAIN_JOB_UNBOUNDED: libvirt_migrate.run_tasks(guest, instance, self.active_migrations, on_migration_failure, migration, is_post_copy_enabled) now = time.time() elapsed = now - start if ((progress_watermark is None) or (progress_watermark == 0) or (progress_watermark > info.data_remaining)): progress_watermark = info.data_remaining progress_time = now progress_timeout = CONF.libvirt.live_migration_progress_timeout completion_timeout = int( CONF.libvirt.live_migration_completion_timeout * data_gb) if libvirt_migrate.should_abort(instance, now, progress_time, progress_timeout, elapsed, completion_timeout, migration.status): try: guest.abort_job() except libvirt.libvirtError as e: LOG.warning(_LW("Failed to abort migration %s"), e, instance=instance) self._clear_empty_migration(instance) raise if (is_post_copy_enabled and libvirt_migrate.should_switch_to_postcopy( info.memory_iteration, info.data_remaining, previous_data_remaining, migration.status)): libvirt_migrate.trigger_postcopy_switch(guest, instance, migration) previous_data_remaining = info.data_remaining curdowntime = libvirt_migrate.update_downtime( guest, instance, curdowntime, downtime_steps, elapsed) # iteration to avoid spamming logs for long # running migrations. Just once every 5 secs # is sufficient for developers to debug problems. # We log once every 30 seconds at info to help # admins see slow running migration operations # when debug logs are off. if (n % 10) == 0: # Ignoring memory_processed, as due to repeated # dirtying of data, this can be way larger than # memory_total. Best to just look at what's # # TODO(berrange) perhaps we could include disk # transfer stats in the progress too, but it # might make memory info more obscure as large # disk sizes might dwarf memory size remaining = 100 if info.memory_total != 0: remaining = round(info.memory_remaining * 100 / info.memory_total) libvirt_migrate.save_stats(instance, migration, info, remaining) lg = LOG.debug if (n % 60) == 0: lg = LOG.info lg(_LI("Migration running for %(secs)d secs, " "memory %(remaining)d%% remaining; " "(bytes processed=%(processed_memory)d, " "remaining=%(remaining_memory)d, " "total=%(total_memory)d)"), {"secs": n / 2, "remaining": remaining, "processed_memory": info.memory_processed, "remaining_memory": info.memory_remaining, "total_memory": info.memory_total}, instance=instance) if info.data_remaining > progress_watermark: lg(_LI("Data remaining %(remaining)d bytes, " "low watermark %(watermark)d bytes " "%(last)d seconds ago"), {"remaining": info.data_remaining, "watermark": progress_watermark, "last": (now - progress_time)}, instance=instance) n = n + 1 elif info.type == libvirt.VIR_DOMAIN_JOB_COMPLETED: # Migration is all done LOG.info(_LI("Migration operation has completed"), instance=instance) post_method(context, instance, dest, block_migration, migrate_data) break elif info.type == libvirt.VIR_DOMAIN_JOB_FAILED: # Migration did not succeed LOG.error(_LE("Migration operation has aborted"), instance=instance) libvirt_migrate.run_recover_tasks(self._host, guest, instance, on_migration_failure) recover_method(context, instance, dest, block_migration, migrate_data) break elif info.type == libvirt.VIR_DOMAIN_JOB_CANCELLED: # Migration was stopped by admin LOG.warning(_LW("Migration operation was cancelled"), instance=instance) libvirt_migrate.run_recover_tasks(self._host, guest, instance, on_migration_failure) recover_method(context, instance, dest, block_migration, migrate_data, migration_status='cancelled') break else: LOG.warning(_LW("Unexpected migration job type: %d"), info.type, instance=instance) time.sleep(0.5) self._clear_empty_migration(instance) def _clear_empty_migration(self, instance): try: del self.active_migrations[instance.uuid] except KeyError: LOG.warning(_LW("There are no records in active migrations " "for instance"), instance=instance) def _live_migration(self, context, instance, dest, post_method, recover_method, block_migration, migrate_data): guest = self._host.get_guest(instance) disk_paths = [] device_names = [] if migrate_data.block_migration: disk_paths, device_names = self._live_migration_copy_disk_paths( context, instance, guest) opthread = utils.spawn(self._live_migration_operation, context, instance, dest, block_migration, migrate_data, guest, device_names) finish_event = eventlet.event.Event() self.active_migrations[instance.uuid] = deque() def thread_finished(thread, event): LOG.debug("Migration operation thread notification", instance=instance) event.send() opthread.link(thread_finished, finish_event) # Let eventlet schedule the new thread right away time.sleep(0) try: LOG.debug("Starting monitoring of live migration", instance=instance) self._live_migration_monitor(context, instance, guest, dest, post_method, recover_method, block_migration, migrate_data, finish_event, disk_paths) except Exception as ex: LOG.warning(_LW("Error monitoring migration: %(ex)s"), {"ex": ex}, instance=instance, exc_info=True) raise finally: LOG.debug("Live migration monitoring is all done", instance=instance) def _is_post_copy_enabled(self, migration_flags): if self._is_post_copy_available(): if (migration_flags & libvirt.VIR_MIGRATE_POSTCOPY) != 0: return True return False def live_migration_force_complete(self, instance): try: self.active_migrations[instance.uuid].append('force-complete') except KeyError: raise exception.NoActiveMigrationForInstance( instance_id=instance.uuid) def _try_fetch_image(self, context, path, image_id, instance, fallback_from_host=None): try: libvirt_utils.fetch_image(context, path, image_id) except exception.ImageNotFound: if not fallback_from_host: raise LOG.debug("Image %(image_id)s doesn't exist anymore on " "image service, attempting to copy image " "from %(host)s", {'image_id': image_id, 'host': fallback_from_host}) libvirt_utils.copy_image(src=path, dest=path, host=fallback_from_host, receive=True) def _fetch_instance_kernel_ramdisk(self, context, instance, fallback_from_host=None): instance_dir = libvirt_utils.get_instance_path(instance) if instance.kernel_id: kernel_path = os.path.join(instance_dir, 'kernel') # kernel_path. This also avoids ImageNotFound exception if # the image has been deleted from glance if not os.path.exists(kernel_path): self._try_fetch_image(context, kernel_path, instance.kernel_id, instance, fallback_from_host) if instance.ramdisk_id: ramdisk_path = os.path.join(instance_dir, 'ramdisk') # NOTE(dsanders): only fetch image if it's not available at if not os.path.exists(ramdisk_path): self._try_fetch_image(context, ramdisk_path, instance.ramdisk_id, instance, fallback_from_host) def rollback_live_migration_at_destination(self, context, instance, network_info, block_device_info, destroy_disks=True, migrate_data=None): try: self.destroy(context, instance, network_info, block_device_info, destroy_disks, migrate_data) finally: is_shared_instance_path = True if migrate_data: is_shared_instance_path = migrate_data.is_shared_instance_path if not is_shared_instance_path: instance_dir = libvirt_utils.get_instance_path_at_destination( instance, migrate_data) if os.path.exists(instance_dir): shutil.rmtree(instance_dir) def pre_live_migration(self, context, instance, block_device_info, network_info, disk_info, migrate_data): if disk_info is not None: disk_info = jsonutils.loads(disk_info) LOG.debug('migrate_data in pre_live_migration: %s', migrate_data, instance=instance) is_shared_block_storage = migrate_data.is_shared_block_storage is_shared_instance_path = migrate_data.is_shared_instance_path is_block_migration = migrate_data.block_migration if not is_shared_instance_path: instance_dir = libvirt_utils.get_instance_path_at_destination( instance, migrate_data) if os.path.exists(instance_dir): raise exception.DestinationDiskExists(path=instance_dir) LOG.debug('Creating instance directory: %s', instance_dir, instance=instance) os.mkdir(instance_dir) if disk_info: image_disk_info = {} for info in disk_info: image_file = os.path.basename(info['path']) image_path = os.path.join(instance_dir, image_file) image_disk_info[image_path] = info['type'] LOG.debug('Creating disk.info with the contents: %s', image_disk_info, instance=instance) image_disk_info_path = os.path.join(instance_dir, 'disk.info') libvirt_utils.write_to_file(image_disk_info_path, jsonutils.dumps(image_disk_info)) if not is_shared_block_storage: LOG.debug('Checking to make sure images and backing files are ' 'present before live migration.', instance=instance) self._create_images_and_backing( context, instance, instance_dir, disk_info, fallback_from_host=instance.host) if (configdrive.required_by(instance) and CONF.config_drive_format == 'iso9660'): # live migration will fail on copying iso config drive to # destination and writing to read-only device. # Please see bug/1246201 for more details. src = "%s:%s/disk.config" % (instance.host, instance_dir) self._remotefs.copy_file(src, instance_dir) if not is_block_migration: # NOTE(angdraug): when block storage is shared between source # and destination and instance path isn't (e.g. volume backed self._ensure_console_log_for_instance(instance) self._fetch_instance_kernel_ramdisk(context, instance) block_device_mapping = driver.block_device_info_get_mapping( block_device_info) if len(block_device_mapping): LOG.debug('Connecting volumes before live migration.', instance=instance) for bdm in block_device_mapping: connection_info = bdm['connection_info'] disk_info = blockinfo.get_info_from_bdm( instance, CONF.libvirt.virt_type, instance.image_meta, bdm) self._connect_volume(connection_info, disk_info) LOG.debug('Plugging VIFs before live migration.', instance=instance) max_retry = CONF.live_migration_retry_count for cnt in range(max_retry): try: self.plug_vifs(instance, network_info) break except processutils.ProcessExecutionError: if cnt == max_retry - 1: raise else: LOG.warning(_LW('plug_vifs() failed %(cnt)d. Retry up to ' '%(max_retry)d.'), {'cnt': cnt, 'max_retry': max_retry}, instance=instance) greenthread.sleep(1) if not migrate_data: migrate_data = objects.LibvirtLiveMigrateData(bdms=[]) else: migrate_data.bdms = [] migrate_data.graphics_listen_addr_vnc = CONF.vnc.vncserver_listen migrate_data.graphics_listen_addr_spice = CONF.spice.server_listen migrate_data.serial_listen_addr = \ CONF.serial_console.proxyclient_address migrate_data.target_connect_addr = \ CONF.libvirt.live_migration_inbound_addr migrate_data.supported_perf_events = self._supported_perf_events for vol in block_device_mapping: connection_info = vol['connection_info'] if connection_info.get('serial'): disk_info = blockinfo.get_info_from_bdm( instance, CONF.libvirt.virt_type, instance.image_meta, vol) bdmi = objects.LibvirtLiveMigrateBDMInfo() bdmi.serial = connection_info['serial'] bdmi.connection_info = connection_info bdmi.bus = disk_info['bus'] bdmi.dev = disk_info['dev'] bdmi.type = disk_info['type'] bdmi.format = disk_info.get('format') bdmi.boot_index = disk_info.get('boot_index') migrate_data.bdms.append(bdmi) return migrate_data def _try_fetch_image_cache(self, image, fetch_func, context, filename, image_id, instance, size, fallback_from_host=None): try: image.cache(fetch_func=fetch_func, context=context, filename=filename, image_id=image_id, size=size) except exception.ImageNotFound: if not fallback_from_host: raise LOG.debug("Image %(image_id)s doesn't exist anymore " "on image service, attempting to copy " "image from %(host)s", {'image_id': image_id, 'host': fallback_from_host}, instance=instance) def copy_from_host(target): libvirt_utils.copy_image(src=target, dest=target, host=fallback_from_host, receive=True) image.cache(fetch_func=copy_from_host, filename=filename) def _create_images_and_backing(self, context, instance, instance_dir, disk_info, fallback_from_host=None): if not disk_info: disk_info = [] for info in disk_info: base = os.path.basename(info['path']) # Get image type and create empty disk image, and # create backing file in case of qcow2. instance_disk = os.path.join(instance_dir, base) if not info['backing_file'] and not os.path.exists(instance_disk): libvirt_utils.create_image(info['type'], instance_disk, info['virt_disk_size']) elif info['backing_file']: # Creating backing file follows same way as spawning instances. cache_name = os.path.basename(info['backing_file']) image = self.image_backend.image(instance, instance_disk, CONF.libvirt.images_type) if cache_name.startswith('ephemeral'): # The argument 'size' is used by image.cache to # validate disk size retrieved from cache against # the instance disk size (should always return OK) # and ephemeral_size is used by _create_ephemeral # to build the image if the disk is not already # cached. image.cache( fetch_func=self._create_ephemeral, fs_label=cache_name, os_type=instance.os_type, filename=cache_name, size=info['virt_disk_size'], ephemeral_size=info['virt_disk_size'] / units.Gi) elif cache_name.startswith('swap'): inst_type = instance.get_flavor() swap_mb = inst_type.swap image.cache(fetch_func=self._create_swap, filename="swap_%s" % swap_mb, size=swap_mb * units.Mi, swap_mb=swap_mb) else: self._try_fetch_image_cache(image, libvirt_utils.fetch_image, context, cache_name, instance.image_ref, instance, info['virt_disk_size'], fallback_from_host) # if image has kernel and ramdisk, just download # following normal way. self._fetch_instance_kernel_ramdisk( context, instance, fallback_from_host=fallback_from_host) def post_live_migration(self, context, instance, block_device_info, migrate_data=None): # Disconnect from volume server block_device_mapping = driver.block_device_info_get_mapping( block_device_info) connector = self.get_volume_connector(instance) volume_api = self._volume_api for vol in block_device_mapping: # Retrieve connection info from Cinder's initialize_connection API. volume_id = vol['connection_info']['serial'] connection_info = volume_api.initialize_connection(context, volume_id, connector) if 'multipath_id' in vol['connection_info']['data']: multipath_id = vol['connection_info']['data']['multipath_id'] connection_info['data']['multipath_id'] = multipath_id disk_dev = vol['mount_device'].rpartition("/")[2] self._disconnect_volume(connection_info, disk_dev) def post_live_migration_at_source(self, context, instance, network_info): self.unplug_vifs(instance, network_info) def post_live_migration_at_destination(self, context, instance, network_info, block_migration=False, block_device_info=None): disk_info = blockinfo.get_disk_info( CONF.libvirt.virt_type, instance, instance.image_meta, block_device_info) xml = self._get_guest_xml(context, instance, network_info, disk_info, instance.image_meta, block_device_info=block_device_info, write_to_disk=True) self._host.write_instance_config(xml) def _get_instance_disk_info(self, instance_name, xml, block_device_info=None): block_device_mapping = driver.block_device_info_get_mapping( block_device_info) volume_devices = set() for vol in block_device_mapping: disk_dev = vol['mount_device'].rpartition("/")[2] volume_devices.add(disk_dev) disk_info = [] doc = etree.fromstring(xml) def find_nodes(doc, device_type): return (doc.findall('.//devices/%s' % device_type), doc.findall('.//devices/%s/source' % device_type), doc.findall('.//devices/%s/driver' % device_type), doc.findall('.//devices/%s/target' % device_type)) if (CONF.libvirt.virt_type == 'parallels' and doc.find('os/type').text == vm_mode.EXE): node_type = 'filesystem' else: node_type = 'disk' (disk_nodes, path_nodes, driver_nodes, target_nodes) = find_nodes(doc, node_type) for cnt, path_node in enumerate(path_nodes): disk_type = disk_nodes[cnt].get('type') path = path_node.get('file') or path_node.get('dev') if (node_type == 'filesystem'): target = target_nodes[cnt].attrib['dir'] else: target = target_nodes[cnt].attrib['dev'] if not path: LOG.debug('skipping disk for %s as it does not have a path', instance_name) continue if disk_type not in ['file', 'block']: LOG.debug('skipping disk because it looks like a volume', path) continue if target in volume_devices: LOG.debug('skipping disk %(path)s (%(target)s) as it is a ' 'volume', {'path': path, 'target': target}) continue if disk_type == 'file': if driver_nodes[cnt].get('type') == 'ploop': dk_size = 0 for dirpath, dirnames, filenames in os.walk(path): for f in filenames: fp = os.path.join(dirpath, f) dk_size += os.path.getsize(fp) else: dk_size = int(os.path.getsize(path)) elif disk_type == 'block' and block_device_info: dk_size = lvm.get_volume_size(path) else: LOG.debug('skipping disk %(path)s (%(target)s) - unable to ' 'determine if volume', {'path': path, 'target': target}) continue disk_type = driver_nodes[cnt].get('type') if disk_type in ("qcow2", "ploop"): backing_file = libvirt_utils.get_disk_backing_file(path) virt_size = disk_api.get_disk_size(path) over_commit_size = int(virt_size) - dk_size else: backing_file = "" virt_size = dk_size over_commit_size = 0 disk_info.append({'type': disk_type, 'path': path, 'virt_disk_size': virt_size, 'backing_file': backing_file, 'disk_size': dk_size, 'over_committed_disk_size': over_commit_size}) return disk_info def get_instance_disk_info(self, instance, block_device_info=None): try: guest = self._host.get_guest(instance) xml = guest.get_xml_desc() except libvirt.libvirtError as ex: error_code = ex.get_error_code() LOG.warning(_LW('Error from libvirt while getting description of ' '%(instance_name)s: [Error Code %(error_code)s] ' '%(ex)s'), {'instance_name': instance.name, 'error_code': error_code, 'ex': ex}, instance=instance) raise exception.InstanceNotFound(instance_id=instance.uuid) return jsonutils.dumps( self._get_instance_disk_info(instance.name, xml, block_device_info)) def _get_disk_over_committed_size_total(self): disk_over_committed_size = 0 instance_domains = self._host.list_instance_domains() if not instance_domains: return disk_over_committed_size instance_uuids = [dom.UUIDString() for dom in instance_domains] ctx = nova_context.get_admin_context() filters = {'uuid': instance_uuids} local_instance_list = objects.InstanceList.get_by_filters( ctx, filters, use_slave=True) local_instances = {inst.uuid: inst for inst in local_instance_list} bdms = objects.BlockDeviceMappingList.bdms_by_instance_uuid( ctx, instance_uuids) for dom in instance_domains: try: guest = libvirt_guest.Guest(dom) xml = guest.get_xml_desc() block_device_info = None if guest.uuid in local_instances \ and (bdms and guest.uuid in bdms): block_device_info = driver.get_block_device_info( local_instances[guest.uuid], bdms[guest.uuid]) disk_infos = self._get_instance_disk_info(guest.name, xml, block_device_info=block_device_info) if not disk_infos: continue for info in disk_infos: disk_over_committed_size += int( info['over_committed_disk_size']) except libvirt.libvirtError as ex: error_code = ex.get_error_code() LOG.warning(_LW( 'Error from libvirt while getting description of ' '%(instance_name)s: [Error Code %(error_code)s] %(ex)s' ), {'instance_name': guest.name, 'error_code': error_code, 'ex': ex}) except OSError as e: if e.errno in (errno.ENOENT, errno.ESTALE): LOG.warning(_LW('Periodic task is updating the host stat, ' 'it is trying to get disk %(i_name)s, ' 'but disk file was removed by concurrent ' 'operations such as resize.'), {'i_name': guest.name}) elif e.errno == errno.EACCES: LOG.warning(_LW('Periodic task is updating the host stat, ' 'it is trying to get disk %(i_name)s, ' 'but access is denied. It is most likely ' 'due to a VM that exists on the compute ' 'node but is not managed by Nova.'), {'i_name': guest.name}) else: raise except exception.VolumeBDMPathNotFound as e: LOG.warning(_LW('Periodic task is updating the host stats, ' 'it is trying to get disk info for %(i_name)s, ' 'but the backing volume block device was removed ' 'by concurrent operations such as resize. ' 'Error: %(error)s'), {'i_name': guest.name, 'error': e}) greenthread.sleep(0) return disk_over_committed_size def unfilter_instance(self, instance, network_info): self.firewall_driver.unfilter_instance(instance, network_info=network_info) def get_available_nodes(self, refresh=False): return [self._host.get_hostname()] def get_host_cpu_stats(self): return self._host.get_cpu_stats() def get_host_uptime(self): out, err = utils.execute('env', 'LANG=C', 'uptime') return out def manage_image_cache(self, context, all_instances): self.image_cache_manager.update(context, all_instances) def _cleanup_remote_migration(self, dest, inst_base, inst_base_resize, shared_storage=False): try: if os.path.exists(inst_base_resize): utils.execute('rm', '-rf', inst_base) utils.execute('mv', inst_base_resize, inst_base) if not shared_storage: self._remotefs.remove_dir(dest, inst_base) except Exception: pass def _is_storage_shared_with(self, dest, inst_base): if CONF.libvirt.images_type == 'rbd': return True shared_storage = (dest == self.get_host_ip_addr()) if not shared_storage: tmp_file = uuid.uuid4().hex + '.tmp' tmp_path = os.path.join(inst_base, tmp_file) try: self._remotefs.create_file(dest, tmp_path) if os.path.exists(tmp_path): shared_storage = True os.unlink(tmp_path) else: self._remotefs.remove_file(dest, tmp_path) except Exception: pass return shared_storage def migrate_disk_and_power_off(self, context, instance, dest, flavor, network_info, block_device_info=None, timeout=0, retry_interval=0): LOG.debug("Starting migrate_disk_and_power_off", instance=instance) ephemerals = driver.block_device_info_get_ephemerals(block_device_info) # ephemeral devices. However, we still want to check if # the original instance's ephemeral_gb property was set and eph_size = (block_device.get_bdm_ephemeral_disk_size(ephemerals) or instance.flavor.ephemeral_gb) root_down = flavor.root_gb < instance.flavor.root_gb ephemeral_down = flavor.ephemeral_gb < eph_size disk_info_text = self.get_instance_disk_info( instance, block_device_info=block_device_info) booted_from_volume = self._is_booted_from_volume(instance, disk_info_text) if (root_down and not booted_from_volume) or ephemeral_down: reason = _("Unable to resize disk down.") raise exception.InstanceFaultRollback( exception.ResizeError(reason=reason)) disk_info = jsonutils.loads(disk_info_text) if CONF.libvirt.images_type == 'lvm' and not booted_from_volume: reason = _("Migration is not supported for LVM backed instances") raise exception.InstanceFaultRollback( exception.MigrationPreCheckError(reason=reason)) inst_base = libvirt_utils.get_instance_path(instance) inst_base_resize = inst_base + "_resize" shared_storage = self._is_storage_shared_with(dest, inst_base) if not shared_storage: try: self._remotefs.create_dir(dest, inst_base) except processutils.ProcessExecutionError as e: reason = _("not able to execute ssh command: %s") % e raise exception.InstanceFaultRollback( exception.ResizeError(reason=reason)) self.power_off(instance, timeout, retry_interval) block_device_mapping = driver.block_device_info_get_mapping( block_device_info) for vol in block_device_mapping: connection_info = vol['connection_info'] disk_dev = vol['mount_device'].rpartition("/")[2] self._disconnect_volume(connection_info, disk_dev) try: utils.execute('mv', inst_base, inst_base_resize) if shared_storage: dest = None utils.execute('mkdir', '-p', inst_base) on_execute = lambda process: \ self.job_tracker.add_job(instance, process.pid) on_completion = lambda process: \ self.job_tracker.remove_job(instance, process.pid) active_flavor = instance.get_flavor() for info in disk_info: img_path = info['path'] fname = os.path.basename(img_path) from_path = os.path.join(inst_base_resize, fname) # what is in it. # We will not copy over the swap disk here, and rely on # finish_migration/_create_image to re-create it for us. if not (fname == 'disk.swap' and active_flavor.get('swap', 0) != flavor.get('swap', 0)): compression = info['type'] not in NO_COMPRESSION_TYPES libvirt_utils.copy_image(from_path, img_path, host=dest, on_execute=on_execute, on_completion=on_completion, compression=compression) # Ensure disk.info is written to the new path to avoid disks being # reinspected and potentially changing format. src_disk_info_path = os.path.join(inst_base_resize, 'disk.info') if os.path.exists(src_disk_info_path): dst_disk_info_path = os.path.join(inst_base, 'disk.info') libvirt_utils.copy_image(src_disk_info_path, dst_disk_info_path, host=dest, on_execute=on_execute, on_completion=on_completion) except Exception: with excutils.save_and_reraise_exception(): self._cleanup_remote_migration(dest, inst_base, inst_base_resize, shared_storage) return disk_info_text def _wait_for_running(self, instance): state = self.get_info(instance).state if state == power_state.RUNNING: LOG.info(_LI("Instance running successfully."), instance=instance) raise loopingcall.LoopingCallDone() @staticmethod def _disk_size_from_instance(instance, disk_name): if disk_name == 'disk': size = instance.flavor.root_gb elif disk_name == 'disk.local': size = instance.flavor.ephemeral_gb # N.B. We don't handle ephemeral disks named disk.ephN here, # should return if an instance has multiple ephemeral disks. else: size = 0 return size * units.Gi @staticmethod def _disk_raw_to_qcow2(path): path_qcow = path + '_qcow' utils.execute('qemu-img', 'convert', '-f', 'raw', '-O', 'qcow2', path, path_qcow) utils.execute('mv', path_qcow, path) @staticmethod def _disk_qcow2_to_raw(path): path_raw = path + '_raw' utils.execute('qemu-img', 'convert', '-f', 'qcow2', '-O', 'raw', path, path_raw) utils.execute('mv', path_raw, path) def _disk_resize(self, image, size): if not isinstance(image, imgmodel.LocalFileImage): LOG.debug("Skipping resize of non-local image") return # If we have a non partitioned image that we can extend # then ensure we're in 'raw' format so we can extend file system. converted = False if (size and image.format == imgmodel.FORMAT_QCOW2 and disk_api.can_resize_image(image.path, size) and disk_api.is_image_extendable(image)): self._disk_qcow2_to_raw(image.path) converted = True image = imgmodel.LocalFileImage(image.path, imgmodel.FORMAT_RAW) if size: disk_api.extend(image, size) if converted: self._disk_raw_to_qcow2(image.path) def finish_migration(self, context, migration, instance, disk_info, network_info, image_meta, resize_instance, block_device_info=None, power_on=True): LOG.debug("Starting finish_migration", instance=instance) block_disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance, image_meta, block_device_info) self._create_image(context, instance, block_disk_info['mapping'], network_info=network_info, block_device_info=None, inject_files=False, fallback_from_host=migration.source_compute) self._ensure_console_log_for_instance(instance) gen_confdrive = functools.partial(self._create_configdrive, context, instance, network_info=network_info) disk_info = jsonutils.loads(disk_info) for info in disk_info: path = info['path'] disk_name = os.path.basename(path) size = self._disk_size_from_instance(instance, disk_name) if resize_instance: image = imgmodel.LocalFileImage(path, info['type']) self._disk_resize(image, size) # be incorrectly assumed to be qcow2, which is a severe security # flaw. The reverse is not true, because the atrociously-named-Raw # backend supports both qcow2 and raw disks, and will choose # appropriately between them as long as disk.info exists and is # correctly populated, which it is because Qcow2 writes to # disk.info. # # In general, we do not yet support format conversion during # migration. For example: # * Converting from use_cow_images=True to use_cow_images=False # isn't handled. This isn't a security bug, but is almost # certainly buggy in other cases, as the 'Raw' backend doesn't # need to be converted. if (disk_name != 'disk.config' and info['type'] == 'raw' and CONF.use_cow_images): self._disk_raw_to_qcow2(info['path']) xml = self._get_guest_xml(context, instance, network_info, block_disk_info, image_meta, block_device_info=block_device_info, write_to_disk=True) # NOTE(mriedem): vifs_already_plugged=True here, regardless of whether # or not we've migrated to another host, because we unplug VIFs locally self._create_domain_and_network(context, xml, instance, network_info, block_disk_info, block_device_info=block_device_info, power_on=power_on, vifs_already_plugged=True, post_xml_callback=gen_confdrive) if power_on: timer = loopingcall.FixedIntervalLoopingCall( self._wait_for_running, instance) timer.start(interval=0.5).wait() LOG.debug("finish_migration finished successfully.", instance=instance) def _cleanup_failed_migration(self, inst_base): try: shutil.rmtree(inst_base) except OSError as e: if e.errno != errno.ENOENT: raise def finish_revert_migration(self, context, instance, network_info, block_device_info=None, power_on=True): LOG.debug("Starting finish_revert_migration", instance=instance) inst_base = libvirt_utils.get_instance_path(instance) inst_base_resize = inst_base + "_resize" # make sure we don't have a left-over same-host base directory # failure happened early. if os.path.exists(inst_base_resize): self._cleanup_failed_migration(inst_base) utils.execute('mv', inst_base_resize, inst_base) root_disk = self.image_backend.image(instance, 'disk') # Once we rollback, the snapshot is no longer needed, so remove it # TODO(nic): Remove the try/except/finally in a future release # To avoid any upgrade issues surrounding instances being in pending # resize state when the software is updated, this portion of the # method logs exceptions rather than failing on them. Once it can be # reasonably assumed that no such instances exist in the wild # anymore, the try/except/finally should be removed, # and ignore_errors should be set back to False (the default) so # that problems throw errors, like they should. if root_disk.exists(): try: root_disk.rollback_to_snap(libvirt_utils.RESIZE_SNAPSHOT_NAME) except exception.SnapshotNotFound: LOG.warning(_LW("Failed to rollback snapshot (%s)"), libvirt_utils.RESIZE_SNAPSHOT_NAME) finally: root_disk.remove_snap(libvirt_utils.RESIZE_SNAPSHOT_NAME, ignore_errors=True) disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance, instance.image_meta, block_device_info) xml = self._get_guest_xml(context, instance, network_info, disk_info, instance.image_meta, block_device_info=block_device_info) self._create_domain_and_network(context, xml, instance, network_info, disk_info, block_device_info=block_device_info, power_on=power_on, vifs_already_plugged=True) if power_on: timer = loopingcall.FixedIntervalLoopingCall( self._wait_for_running, instance) timer.start(interval=0.5).wait() LOG.debug("finish_revert_migration finished successfully.", instance=instance) def confirm_migration(self, migration, instance, network_info): self._cleanup_resize(instance, network_info) @staticmethod def _get_io_devices(xml_doc): result = {"volumes": [], "ifaces": []} try: doc = etree.fromstring(xml_doc) except Exception: return result blocks = [('./devices/disk', 'volumes'), ('./devices/interface', 'ifaces')] for block, key in blocks: section = doc.findall(block) for node in section: for child in node.getchildren(): if child.tag == 'target' and child.get('dev'): result[key].append(child.get('dev')) return result def get_diagnostics(self, instance): guest = self._host.get_guest(instance) # TODO(sahid): We are converting all calls from a # virDomain object to use nova.virt.libvirt.Guest. # We should be able to remove domain at the end. domain = guest._domain output = {} # get cpu time, might launch an exception if the method # is not supported by the underlying hypervisor being # used by libvirt try: for vcpu in guest.get_vcpus_info(): output["cpu" + str(vcpu.id) + "_time"] = vcpu.time except libvirt.libvirtError: pass # get io status xml = guest.get_xml_desc() dom_io = LibvirtDriver._get_io_devices(xml) for guest_disk in dom_io["volumes"]: try: # blockStats might launch an exception if the method # is not supported by the underlying hypervisor being # used by libvirt stats = domain.blockStats(guest_disk) output[guest_disk + "_read_req"] = stats[0] output[guest_disk + "_read"] = stats[1] output[guest_disk + "_write_req"] = stats[2] output[guest_disk + "_write"] = stats[3] output[guest_disk + "_errors"] = stats[4] except libvirt.libvirtError: pass for interface in dom_io["ifaces"]: try: # interfaceStats might launch an exception if the method # is not supported by the underlying hypervisor being # used by libvirt stats = domain.interfaceStats(interface) output[interface + "_rx"] = stats[0] output[interface + "_rx_packets"] = stats[1] output[interface + "_rx_errors"] = stats[2] output[interface + "_rx_drop"] = stats[3] output[interface + "_tx"] = stats[4] output[interface + "_tx_packets"] = stats[5] output[interface + "_tx_errors"] = stats[6] output[interface + "_tx_drop"] = stats[7] except libvirt.libvirtError: pass output["memory"] = domain.maxMemory() # memoryStats might launch an exception if the method # is not supported by the underlying hypervisor being # used by libvirt try: mem = domain.memoryStats() for key in mem.keys(): output["memory-" + key] = mem[key] except (libvirt.libvirtError, AttributeError): pass return output def get_instance_diagnostics(self, instance): guest = self._host.get_guest(instance) # TODO(sahid): We are converting all calls from a # virDomain object to use nova.virt.libvirt.Guest. # We should be able to remove domain at the end. domain = guest._domain xml = guest.get_xml_desc() xml_doc = etree.fromstring(xml) # TODO(sahid): Needs to use get_info but more changes have to # be done since a mapping STATE_MAP LIBVIRT_POWER_STATE is # needed. (state, max_mem, mem, num_cpu, cpu_time) = \ guest._get_domain_info(self._host) config_drive = configdrive.required_by(instance) launched_at = timeutils.normalize_time(instance.launched_at) uptime = timeutils.delta_seconds(launched_at, timeutils.utcnow()) diags = diagnostics.Diagnostics(state=power_state.STATE_MAP[state], driver='libvirt', config_drive=config_drive, hypervisor_os='linux', uptime=uptime) diags.memory_details.maximum = max_mem / units.Mi diags.memory_details.used = mem / units.Mi # get cpu time, might launch an exception if the method # is not supported by the underlying hypervisor being # used by libvirt try: for vcpu in guest.get_vcpus_info(): diags.add_cpu(time=vcpu.time) except libvirt.libvirtError: pass # get io status dom_io = LibvirtDriver._get_io_devices(xml) for guest_disk in dom_io["volumes"]: try: # blockStats might launch an exception if the method # is not supported by the underlying hypervisor being # used by libvirt stats = domain.blockStats(guest_disk) diags.add_disk(read_bytes=stats[1], read_requests=stats[0], write_bytes=stats[3], write_requests=stats[2]) except libvirt.libvirtError: pass for interface in dom_io["ifaces"]: try: # interfaceStats might launch an exception if the method # is not supported by the underlying hypervisor being # used by libvirt stats = domain.interfaceStats(interface) diags.add_nic(rx_octets=stats[0], rx_errors=stats[2], rx_drop=stats[3], rx_packets=stats[1], tx_octets=stats[4], tx_errors=stats[6], tx_drop=stats[7], tx_packets=stats[5]) except libvirt.libvirtError: pass # Update mac addresses of interface if stats have been reported if diags.nic_details: nodes = xml_doc.findall('./devices/interface/mac') for index, node in enumerate(nodes): diags.nic_details[index].mac_address = node.get('address') return diags @staticmethod def _prepare_device_bus(dev): bus = None address = (dev.device_addr.format_address() if dev.device_addr else None) if isinstance(dev.device_addr, vconfig.LibvirtConfigGuestDeviceAddressPCI): bus = objects.PCIDeviceBus() elif isinstance(dev, vconfig.LibvirtConfigGuestDisk): if dev.target_bus == 'scsi': bus = objects.SCSIDeviceBus() elif dev.target_bus == 'ide': bus = objects.IDEDeviceBus() elif dev.target_bus == 'usb': bus = objects.USBDeviceBus() if address is not None and bus is not None: bus.address = address return bus def _build_device_metadata(self, context, instance): def _get_device_name(bdm): return block_device.strip_dev(bdm.device_name) vifs = objects.VirtualInterfaceList.get_by_instance_uuid(context, instance.uuid) tagged_vifs = {vif.address: vif for vif in vifs if vif.tag} # TODO(mriedem): We should be able to avoid the DB query here by using # block_device_info['block_device_mapping'] which is passed into most # methods that call this function. bdms = objects.BlockDeviceMappingList.get_by_instance_uuid( context, instance.uuid) tagged_bdms = {_get_device_name(bdm): bdm for bdm in bdms if bdm.tag} devices = [] guest = self._host.get_guest(instance) xml = guest.get_xml_desc() xml_dom = etree.fromstring(xml) guest_config = vconfig.LibvirtConfigGuest() guest_config.parse_dom(xml_dom) for dev in guest_config.devices: # Build network intefaces related metedata if isinstance(dev, vconfig.LibvirtConfigGuestInterface): vif = tagged_vifs.get(dev.mac_addr) if not vif: continue bus = self._prepare_device_bus(dev) device = objects.NetworkInterfaceMetadata( mac=vif.address, tags=[vif.tag] ) if bus: device.bus = bus devices.append(device) # Build disks related metedata if isinstance(dev, vconfig.LibvirtConfigGuestDisk): bdm = tagged_bdms.get(dev.target_dev) if not bdm: continue bus = self._prepare_device_bus(dev) device = objects.DiskMetadata(tags=[bdm.tag]) if bus: device.bus = bus devices.append(device) if devices: dev_meta = objects.InstanceDeviceMetadata(devices=devices) return dev_meta def instance_on_disk(self, instance): # ensure directories exist and are writable instance_path = libvirt_utils.get_instance_path(instance) LOG.debug('Checking instance files accessibility %s', instance_path, instance=instance) shared_instance_path = os.access(instance_path, os.W_OK) # NOTE(flwang): For shared block storage scenario, the file system is # not really shared by the two hosts, but the volume of evacuated # instance is reachable. shared_block_storage = (self.image_backend.backend(). is_shared_block_storage()) return shared_instance_path or shared_block_storage def inject_network_info(self, instance, nw_info): self.firewall_driver.setup_basic_filtering(instance, nw_info) def delete_instance_files(self, instance): target = libvirt_utils.get_instance_path(instance) # A resize may be in progress target_resize = target + '_resize' # Other threads may attempt to rename the path, so renaming the path # to target + '_del' (because it is atomic) and iterating through # twice in the unlikely event that a concurrent rename occurs between # the two rename attempts in this method. In general this method # should be fairly thread-safe without these additional checks, since # other operations involving renames are not permitted when the task # state is not None and the task state should be set to something # other than None by the time this method is invoked. target_del = target + '_del' for i in six.moves.range(2): try: utils.execute('mv', target, target_del) break except Exception: pass try: utils.execute('mv', target_resize, target_del) break except Exception: pass # Either the target or target_resize path may still exist if all # rename attempts failed. remaining_path = None for p in (target, target_resize): if os.path.exists(p): remaining_path = p break # A previous delete attempt may have been interrupted, so target_del # may exist even if all rename attempts during the present method # invocation failed due to the absence of both target and # target_resize. if not remaining_path and os.path.exists(target_del): self.job_tracker.terminate_jobs(instance) LOG.info(_LI('Deleting instance files %s'), target_del, instance=instance) remaining_path = target_del try: shutil.rmtree(target_del) except OSError as e: LOG.error(_LE('Failed to cleanup directory %(target)s: ' '%(e)s'), {'target': target_del, 'e': e}, instance=instance) # It is possible that the delete failed, if so don't mark the instance if remaining_path and os.path.exists(remaining_path): LOG.info(_LI('Deletion of %s failed'), remaining_path, instance=instance) return False LOG.info(_LI('Deletion of %s complete'), target_del, instance=instance) return True @property def need_legacy_block_device_info(self): return False def default_root_device_name(self, instance, image_meta, root_bdm): disk_bus = blockinfo.get_disk_bus_for_device_type( instance, CONF.libvirt.virt_type, image_meta, "disk") cdrom_bus = blockinfo.get_disk_bus_for_device_type( instance, CONF.libvirt.virt_type, image_meta, "cdrom") root_info = blockinfo.get_root_info( instance, CONF.libvirt.virt_type, image_meta, root_bdm, disk_bus, cdrom_bus) return block_device.prepend_dev(root_info['dev']) def default_device_names_for_instance(self, instance, root_device_name, *block_device_lists): block_device_mapping = list(itertools.chain(*block_device_lists)) for bdm in block_device_mapping: if bdm.device_name is not None: LOG.warning( _LW("Ignoring supplied device name: %(device_name)s. " "Libvirt can't honour user-supplied dev names"), {'device_name': bdm.device_name}, instance=instance) bdm.device_name = None block_device_info = driver.get_block_device_info(instance, block_device_mapping) blockinfo.default_device_names(CONF.libvirt.virt_type, nova_context.get_admin_context(), instance, block_device_info, instance.image_meta) def get_device_name_for_instance(self, instance, bdms, block_device_obj): block_device_info = driver.get_block_device_info(instance, bdms) instance_info = blockinfo.get_disk_info( CONF.libvirt.virt_type, instance, instance.image_meta, block_device_info=block_device_info) suggested_dev_name = block_device_obj.device_name if suggested_dev_name is not None: LOG.warning( _LW('Ignoring supplied device name: %(suggested_dev)s'), {'suggested_dev': suggested_dev_name}, instance=instance) # NOTE(ndipanov): get_info_from_bdm will generate the new device name # only when it's actually not set on the bd object block_device_obj.device_name = None disk_info = blockinfo.get_info_from_bdm( instance, CONF.libvirt.virt_type, instance.image_meta, block_device_obj, mapping=instance_info['mapping']) return block_device.prepend_dev(disk_info['dev']) def is_supported_fs_format(self, fs_type): return fs_type in [disk_api.FS_FORMAT_EXT2, disk_api.FS_FORMAT_EXT3, disk_api.FS_FORMAT_EXT4, disk_api.FS_FORMAT_XFS]
true
true
f72cd4093b6c2735e85a9e0cc06731f3fd380a07
12,960
py
Python
elastalert/alerts.py
talyian/elastalert
8ff39d485c0babd098ad659b53ce0f8ad456c6c3
[ "Apache-2.0" ]
null
null
null
elastalert/alerts.py
talyian/elastalert
8ff39d485c0babd098ad659b53ce0f8ad456c6c3
[ "Apache-2.0" ]
1
2021-06-02T04:32:03.000Z
2021-06-02T04:32:03.000Z
elastalert/alerts.py
talyian/elastalert
8ff39d485c0babd098ad659b53ce0f8ad456c6c3
[ "Apache-2.0" ]
null
null
null
# -*- coding: utf-8 -*- import datetime import json import logging import subprocess from email.mime.text import MIMEText from smtplib import SMTP from smtplib import SMTPException from socket import error from jira.client import JIRA from jira.exceptions import JIRAError from staticconf.loader import yaml_loader from util import EAException from util import pretty_ts def get_counts_string(match): """ Looks for keys matching top_events_X in matches, generated by get_top_counts, and returns a readable string about the various counts. """ message = '' for key, counts in match.items(): if key.startswith('top_events_'): message += '%s:\n' % (key[11:]) top_events = counts.items() top_events.sort(key=lambda x: x[1], reverse=True) for term, count in top_events: message += '%s: %s\n' % (term, count) message += '\n' return message def basic_match_string(rule, match): """ Returns a string for the given rule and match. """ text = rule['name'] + '\n\n' # Add custom alert text alert_text = rule.get('alert_text', '') if 'alert_text_args' in rule: alert_text_args = rule.get('alert_text_args') alert_text_values = [match.get(arg, '<MISSING VALUE>') for arg in alert_text_args] alert_text = alert_text.format(*alert_text_values) text += alert_text while text[-2:] != '\n\n': text += '\n' if rule.get('alert_text_type') != 'alert_text_only': # Add rule text text += rule['type'].get_match_str(match) while text[-2:] != '\n\n': text += '\n' # Add top_counts if rule.get('top_count_keys'): text += get_counts_string(match) if rule.get('alert_text_type') != 'exclude_fields': # Add match items match_items = match.items() match_items.sort(key=lambda x: x[0]) text += '\n'.join(['%s: %s' % (key, val) for key, val in match.items() if not key.startswith('top_events_')]) return text class Alerter(object): """ Base class for types of alerts. :param rule: The rule configuration. """ required_options = frozenset([]) def __init__(self, rule): self.rule = rule self.pipeline = None def alert(self, match): """ Send an alert. Match is a dictionary of information about the alert. :param match: A dictionary of relevant information to the alert. """ raise NotImplementedError() def get_info(self): """ Returns a dictionary of data related to this alert. At minimum, this should contain a field type corresponding to the type of Alerter. """ return {'type': 'Unknown'} def create_title(self, matches): """ Creates custom alert title to be used, e.g. as an e-mail subject or JIRA issue summary. :param matches: A list of dictionaries of relevant information to the alert. """ if 'alert_subject' in self.rule: return self.create_custom_title(matches) return self.create_default_title(matches) def create_custom_title(self, matches): alert_subject = self.rule['alert_subject'] if 'alert_subject_args' in self.rule: alert_subject_args = self.rule['alert_subject_args'] alert_subject_values = [matches[0].get(arg, '<MISSING VALUE>') for arg in alert_subject_args] return alert_subject.format(*alert_subject_values) return alert_subject def create_default_title(self, matches): return self.rule['name'] class DebugAlerter(Alerter): """ The debug alerter uses a Python logger (by default, alerting to terminal). """ def alert(self, matches): logging.info('%d match(es)' % (len(matches))) qk = self.rule.get('query_key', None) for match in matches: if qk in match: logging.info('%s matched %s at %s' % (match[qk], self.rule['name'], match[self.rule['timestamp_field']])) else: logging.info('%s at %s' % (self.rule['name'], match[self.rule['timestamp_field']])) logging.info(basic_match_string(self.rule, match)) def get_info(self): return {'type': 'debug'} class EmailAlerter(Alerter): """ Sends an email alert """ required_options = frozenset(['email']) def __init__(self, *args): super(EmailAlerter, self).__init__(*args) self.smtp_host = self.rule.get('smtp_host', 'localhost') self.from_addr = self.rule.get('from_addr', 'ElastAlert') # Convert email to a list if it isn't already if isinstance(self.rule['email'], str): self.rule['email'] = [self.rule['email']] def alert(self, matches): body = '' for match in matches: body += basic_match_string(self.rule, match) # Separate text of aggregated alerts with dashes if len(matches) > 1: body += '\n----------------------------------------\n' # Add JIRA ticket if it exists if self.pipeline is not None and 'jira_ticket' in self.pipeline: url = '%s/browse/%s' % (self.rule['jira_server'], self.pipeline['jira_ticket']) body += '\nJIRA ticket: %s' % (url) email_msg = MIMEText(body) email_msg['Subject'] = self.create_title(matches) email_msg['To'] = ', '.join(self.rule['email']) email_msg['From'] = self.from_addr email_msg['Reply-To'] = self.rule.get('email_reply_to', email_msg['To']) try: self.smtp = SMTP(self.smtp_host) except (SMTPException, error) as e: raise EAException("Error connecting to SMTP host: %s" % (e)) self.smtp.sendmail(self.from_addr, self.rule['email'], email_msg.as_string()) self.smtp.close() logging.info("Sent email to %s" % (self.rule['email'])) def create_default_title(self, matches): subject = 'ElastAlert: %s' % (self.rule['name']) # If the rule has a query_key, add that value plus timestamp to subject if 'query_key' in self.rule: qk = matches[0].get(self.rule['query_key']) if qk: subject += ' - %s' % (qk) return subject def get_info(self): return {'type': 'email', 'recipients': self.rule['email']} class JiraAlerter(Alerter): """ Creates a Jira ticket for each alert """ required_options = frozenset(['jira_server', 'jira_account_file', 'jira_project', 'jira_issuetype']) def __init__(self, rule): super(JiraAlerter, self).__init__(rule) self.server = self.rule['jira_server'] self.get_jira_account(self.rule['jira_account_file']) self.project = self.rule['jira_project'] self.issue_type = self.rule['jira_issuetype'] self.component = self.rule.get('jira_component') self.label = self.rule.get('jira_label') self.assignee = self.rule.get('jira_assignee') self.max_age = self.rule.get('jira_max_age', 30) self.bump_tickets = self.rule.get('jira_bump_tickets', False) self.jira_args = {'project': {'key': self.project}, 'issuetype': {'name': self.issue_type}} if self.component: self.jira_args['components'] = [{'name': self.component}] if self.label: self.jira_args['labels'] = [self.label] if self.assignee: self.jira_args['assignee'] = {'name': self.assignee} try: self.client = JIRA(self.server, basic_auth=(self.user, self.password)) except JIRAError as e: # JIRAError may contain HTML, pass along only first 1024 chars raise EAException("Error connecting to JIRA: %s" % (str(e)[:1024])) def set_assignee(self, assignee): self.assignee = assignee if assignee: self.jira_args['assignee'] = {'name': assignee} elif 'assignee' in self.jira_args: self.jira_args.pop('assignee') def get_jira_account(self, account_file): """ Gets the username and password from a jira account file. :param account_file: Name of the file which contains user and password information. """ account_conf = yaml_loader(account_file) if 'user' not in account_conf or 'password' not in account_conf: raise EAException('Jira account file must have user and password fields') self.user = account_conf['user'] self.password = account_conf['password'] def find_existing_ticket(self, matches): # Default title, get stripped search version if 'alert_subject' not in self.rule: title = self.create_default_title(matches, True) else: title = self.create_title(matches) # This is necessary for search for work. Other special characters and dashes # directly adjacent to words appear to be ok title = title.replace(' - ', ' ') date = (datetime.datetime.now() - datetime.timedelta(days=self.max_age)).strftime('%Y/%m/%d') jql = 'project=%s AND summary~"%s" and created >= "%s"' % (self.project, title, date) try: issues = self.client.search_issues(jql) except JIRAError as e: logging.exception("Error while searching for JIRA ticket using jql '%s': %s" % (jql, e)) return None if len(issues): return issues[0] def comment_on_ticket(self, ticket, match): text = basic_match_string(self.rule, match) timestamp = pretty_ts(match[self.rule['timestamp_field']]) comment = "This alert was triggered again at %s\n%s" % (timestamp, text) self.client.add_comment(ticket, comment) def alert(self, matches): title = self.create_title(matches) if self.bump_tickets: ticket = self.find_existing_ticket(matches) if ticket: logging.info('Commenting on existing ticket %s' % (ticket.key)) for match in matches: self.comment_on_ticket(ticket, match) return description = '' for match in matches: description += basic_match_string(self.rule, match) if len(matches) > 1: description += '\n----------------------------------------\n' self.jira_args['summary'] = title self.jira_args['description'] = description try: self.issue = self.client.create_issue(**self.jira_args) except JIRAError as e: raise EAException("Error creating JIRA ticket: %s" % (e)) logging.info("Opened Jira ticket: %s" % (self.issue)) if self.pipeline is not None: self.pipeline['jira_ticket'] = self.issue def create_default_title(self, matches, for_search=False): # If there is a query_key, use that in the title if 'query_key' in self.rule and self.rule['query_key'] in matches[0]: title = 'ElastAlert: %s matched %s' % (matches[0][self.rule['query_key']], self.rule['name']) else: title = 'ElastAlert: %s' % (self.rule['name']) if for_search: return title title += ' - %s' % (pretty_ts(matches[0][self.rule['timestamp_field']], self.rule.get('use_local_time'))) # Add count for spikes count = matches[0].get('spike_count') if count: title += ' - %s+ events' % (count) return title def get_info(self): return {'type': 'jira'} class CommandAlerter(Alerter): required_options = set(['command']) def __init__(self, *args): super(CommandAlerter, self).__init__(*args) if isinstance(self.rule['command'], basestring) and '%' in self.rule['command']: logging.warning('Warning! You could be vulnerable to shell injection!') self.rule['command'] = [self.rule['command']] def alert(self, matches): for match in matches: # Format the command and arguments try: command = [command_arg % match for command_arg in self.rule['command']] self.last_command = command except KeyError as e: raise EAException("Error formatting command: %s" % (e)) # Run command and pipe data try: subp = subprocess.Popen(command, stdin=subprocess.PIPE) if self.rule.get('pipe_match_json'): match_json = json.dumps(match) stdout, stderr = subp.communicate(input=match_json) except OSError as e: raise EAException("Error while running command %s: %s" % (' '.join(command), e)) def get_info(self): return {'type': 'command', 'command': ' '.join(self.last_command)}
37.028571
121
0.599691
import datetime import json import logging import subprocess from email.mime.text import MIMEText from smtplib import SMTP from smtplib import SMTPException from socket import error from jira.client import JIRA from jira.exceptions import JIRAError from staticconf.loader import yaml_loader from util import EAException from util import pretty_ts def get_counts_string(match): message = '' for key, counts in match.items(): if key.startswith('top_events_'): message += '%s:\n' % (key[11:]) top_events = counts.items() top_events.sort(key=lambda x: x[1], reverse=True) for term, count in top_events: message += '%s: %s\n' % (term, count) message += '\n' return message def basic_match_string(rule, match): text = rule['name'] + '\n\n' alert_text = rule.get('alert_text', '') if 'alert_text_args' in rule: alert_text_args = rule.get('alert_text_args') alert_text_values = [match.get(arg, '<MISSING VALUE>') for arg in alert_text_args] alert_text = alert_text.format(*alert_text_values) text += alert_text while text[-2:] != '\n\n': text += '\n' if rule.get('alert_text_type') != 'alert_text_only': text += rule['type'].get_match_str(match) while text[-2:] != '\n\n': text += '\n' if rule.get('top_count_keys'): text += get_counts_string(match) if rule.get('alert_text_type') != 'exclude_fields': match_items = match.items() match_items.sort(key=lambda x: x[0]) text += '\n'.join(['%s: %s' % (key, val) for key, val in match.items() if not key.startswith('top_events_')]) return text class Alerter(object): required_options = frozenset([]) def __init__(self, rule): self.rule = rule self.pipeline = None def alert(self, match): raise NotImplementedError() def get_info(self): return {'type': 'Unknown'} def create_title(self, matches): if 'alert_subject' in self.rule: return self.create_custom_title(matches) return self.create_default_title(matches) def create_custom_title(self, matches): alert_subject = self.rule['alert_subject'] if 'alert_subject_args' in self.rule: alert_subject_args = self.rule['alert_subject_args'] alert_subject_values = [matches[0].get(arg, '<MISSING VALUE>') for arg in alert_subject_args] return alert_subject.format(*alert_subject_values) return alert_subject def create_default_title(self, matches): return self.rule['name'] class DebugAlerter(Alerter): def alert(self, matches): logging.info('%d match(es)' % (len(matches))) qk = self.rule.get('query_key', None) for match in matches: if qk in match: logging.info('%s matched %s at %s' % (match[qk], self.rule['name'], match[self.rule['timestamp_field']])) else: logging.info('%s at %s' % (self.rule['name'], match[self.rule['timestamp_field']])) logging.info(basic_match_string(self.rule, match)) def get_info(self): return {'type': 'debug'} class EmailAlerter(Alerter): required_options = frozenset(['email']) def __init__(self, *args): super(EmailAlerter, self).__init__(*args) self.smtp_host = self.rule.get('smtp_host', 'localhost') self.from_addr = self.rule.get('from_addr', 'ElastAlert') if isinstance(self.rule['email'], str): self.rule['email'] = [self.rule['email']] def alert(self, matches): body = '' for match in matches: body += basic_match_string(self.rule, match) # Separate text of aggregated alerts with dashes if len(matches) > 1: body += '\n----------------------------------------\n' # Add JIRA ticket if it exists if self.pipeline is not None and 'jira_ticket' in self.pipeline: url = '%s/browse/%s' % (self.rule['jira_server'], self.pipeline['jira_ticket']) body += '\nJIRA ticket: %s' % (url) email_msg = MIMEText(body) email_msg['Subject'] = self.create_title(matches) email_msg['To'] = ', '.join(self.rule['email']) email_msg['From'] = self.from_addr email_msg['Reply-To'] = self.rule.get('email_reply_to', email_msg['To']) try: self.smtp = SMTP(self.smtp_host) except (SMTPException, error) as e: raise EAException("Error connecting to SMTP host: %s" % (e)) self.smtp.sendmail(self.from_addr, self.rule['email'], email_msg.as_string()) self.smtp.close() logging.info("Sent email to %s" % (self.rule['email'])) def create_default_title(self, matches): subject = 'ElastAlert: %s' % (self.rule['name']) # If the rule has a query_key, add that value plus timestamp to subject if 'query_key' in self.rule: qk = matches[0].get(self.rule['query_key']) if qk: subject += ' - %s' % (qk) return subject def get_info(self): return {'type': 'email', 'recipients': self.rule['email']} class JiraAlerter(Alerter): required_options = frozenset(['jira_server', 'jira_account_file', 'jira_project', 'jira_issuetype']) def __init__(self, rule): super(JiraAlerter, self).__init__(rule) self.server = self.rule['jira_server'] self.get_jira_account(self.rule['jira_account_file']) self.project = self.rule['jira_project'] self.issue_type = self.rule['jira_issuetype'] self.component = self.rule.get('jira_component') self.label = self.rule.get('jira_label') self.assignee = self.rule.get('jira_assignee') self.max_age = self.rule.get('jira_max_age', 30) self.bump_tickets = self.rule.get('jira_bump_tickets', False) self.jira_args = {'project': {'key': self.project}, 'issuetype': {'name': self.issue_type}} if self.component: self.jira_args['components'] = [{'name': self.component}] if self.label: self.jira_args['labels'] = [self.label] if self.assignee: self.jira_args['assignee'] = {'name': self.assignee} try: self.client = JIRA(self.server, basic_auth=(self.user, self.password)) except JIRAError as e: # JIRAError may contain HTML, pass along only first 1024 chars raise EAException("Error connecting to JIRA: %s" % (str(e)[:1024])) def set_assignee(self, assignee): self.assignee = assignee if assignee: self.jira_args['assignee'] = {'name': assignee} elif 'assignee' in self.jira_args: self.jira_args.pop('assignee') def get_jira_account(self, account_file): account_conf = yaml_loader(account_file) if 'user' not in account_conf or 'password' not in account_conf: raise EAException('Jira account file must have user and password fields') self.user = account_conf['user'] self.password = account_conf['password'] def find_existing_ticket(self, matches): # Default title, get stripped search version if 'alert_subject' not in self.rule: title = self.create_default_title(matches, True) else: title = self.create_title(matches) # This is necessary for search for work. Other special characters and dashes # directly adjacent to words appear to be ok title = title.replace(' - ', ' ') date = (datetime.datetime.now() - datetime.timedelta(days=self.max_age)).strftime('%Y/%m/%d') jql = 'project=%s AND summary~"%s" and created >= "%s"' % (self.project, title, date) try: issues = self.client.search_issues(jql) except JIRAError as e: logging.exception("Error while searching for JIRA ticket using jql '%s': %s" % (jql, e)) return None if len(issues): return issues[0] def comment_on_ticket(self, ticket, match): text = basic_match_string(self.rule, match) timestamp = pretty_ts(match[self.rule['timestamp_field']]) comment = "This alert was triggered again at %s\n%s" % (timestamp, text) self.client.add_comment(ticket, comment) def alert(self, matches): title = self.create_title(matches) if self.bump_tickets: ticket = self.find_existing_ticket(matches) if ticket: logging.info('Commenting on existing ticket %s' % (ticket.key)) for match in matches: self.comment_on_ticket(ticket, match) return description = '' for match in matches: description += basic_match_string(self.rule, match) if len(matches) > 1: description += '\n----------------------------------------\n' self.jira_args['summary'] = title self.jira_args['description'] = description try: self.issue = self.client.create_issue(**self.jira_args) except JIRAError as e: raise EAException("Error creating JIRA ticket: %s" % (e)) logging.info("Opened Jira ticket: %s" % (self.issue)) if self.pipeline is not None: self.pipeline['jira_ticket'] = self.issue def create_default_title(self, matches, for_search=False): # If there is a query_key, use that in the title if 'query_key' in self.rule and self.rule['query_key'] in matches[0]: title = 'ElastAlert: %s matched %s' % (matches[0][self.rule['query_key']], self.rule['name']) else: title = 'ElastAlert: %s' % (self.rule['name']) if for_search: return title title += ' - %s' % (pretty_ts(matches[0][self.rule['timestamp_field']], self.rule.get('use_local_time'))) # Add count for spikes count = matches[0].get('spike_count') if count: title += ' - %s+ events' % (count) return title def get_info(self): return {'type': 'jira'} class CommandAlerter(Alerter): required_options = set(['command']) def __init__(self, *args): super(CommandAlerter, self).__init__(*args) if isinstance(self.rule['command'], basestring) and '%' in self.rule['command']: logging.warning('Warning! You could be vulnerable to shell injection!') self.rule['command'] = [self.rule['command']] def alert(self, matches): for match in matches: # Format the command and arguments try: command = [command_arg % match for command_arg in self.rule['command']] self.last_command = command except KeyError as e: raise EAException("Error formatting command: %s" % (e)) # Run command and pipe data try: subp = subprocess.Popen(command, stdin=subprocess.PIPE) if self.rule.get('pipe_match_json'): match_json = json.dumps(match) stdout, stderr = subp.communicate(input=match_json) except OSError as e: raise EAException("Error while running command %s: %s" % (' '.join(command), e)) def get_info(self): return {'type': 'command', 'command': ' '.join(self.last_command)}
true
true
f72cd428667980c9fdb4e230f0d8a948590c845d
1,070
py
Python
kubernetes/test/test_v1beta1_rolling_update_daemon_set.py
TomasTomecek/kubernetes-python
c37c074303a13c72662b9201ccc023fb0ca45755
[ "Apache-2.0" ]
null
null
null
kubernetes/test/test_v1beta1_rolling_update_daemon_set.py
TomasTomecek/kubernetes-python
c37c074303a13c72662b9201ccc023fb0ca45755
[ "Apache-2.0" ]
null
null
null
kubernetes/test/test_v1beta1_rolling_update_daemon_set.py
TomasTomecek/kubernetes-python
c37c074303a13c72662b9201ccc023fb0ca45755
[ "Apache-2.0" ]
1
2020-05-09T07:16:55.000Z
2020-05-09T07:16:55.000Z
# coding: utf-8 """ Kubernetes No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) OpenAPI spec version: v1.12.4 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import os import sys import unittest import kubernetes.client from kubernetes.client.rest import ApiException from kubernetes.client.models.v1beta1_rolling_update_daemon_set import V1beta1RollingUpdateDaemonSet class TestV1beta1RollingUpdateDaemonSet(unittest.TestCase): """ V1beta1RollingUpdateDaemonSet unit test stubs """ def setUp(self): pass def tearDown(self): pass def testV1beta1RollingUpdateDaemonSet(self): """ Test V1beta1RollingUpdateDaemonSet """ # FIXME: construct object with mandatory attributes with example values #model = kubernetes.client.models.v1beta1_rolling_update_daemon_set.V1beta1RollingUpdateDaemonSet() pass if __name__ == '__main__': unittest.main()
23.777778
107
0.738318
from __future__ import absolute_import import os import sys import unittest import kubernetes.client from kubernetes.client.rest import ApiException from kubernetes.client.models.v1beta1_rolling_update_daemon_set import V1beta1RollingUpdateDaemonSet class TestV1beta1RollingUpdateDaemonSet(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def testV1beta1RollingUpdateDaemonSet(self): pass if __name__ == '__main__': unittest.main()
true
true
f72cd49b263b57b7fcb9084dfd4139d1f60dc573
22,741
py
Python
django/contrib/contenttypes/fields.py
tomviner/django
87fed9444033533ad7105c4b1e4ffc5d7854a2c6
[ "BSD-3-Clause" ]
null
null
null
django/contrib/contenttypes/fields.py
tomviner/django
87fed9444033533ad7105c4b1e4ffc5d7854a2c6
[ "BSD-3-Clause" ]
null
null
null
django/contrib/contenttypes/fields.py
tomviner/django
87fed9444033533ad7105c4b1e4ffc5d7854a2c6
[ "BSD-3-Clause" ]
1
2022-03-26T09:05:09.000Z
2022-03-26T09:05:09.000Z
from __future__ import unicode_literals from collections import defaultdict from django.contrib.contenttypes.models import ContentType from django.core import checks from django.core.exceptions import FieldDoesNotExist, ObjectDoesNotExist from django.db import DEFAULT_DB_ALIAS, connection, models, router, transaction from django.db.models import DO_NOTHING, signals from django.db.models.base import ModelBase from django.db.models.fields.related import ( ForeignObject, ForeignObjectRel, ForeignRelatedObjectsDescriptor, ) from django.db.models.query_utils import PathInfo from django.utils.encoding import python_2_unicode_compatible, smart_text from django.utils.functional import cached_property @python_2_unicode_compatible class GenericForeignKey(object): """ Provide a generic many-to-one relation through the ``content_type`` and ``object_id`` fields. This class also doubles as an accessor to the related object (similar to ReverseSingleRelatedObjectDescriptor) by adding itself as a model attribute. """ # Field flags auto_created = False concrete = False editable = False hidden = False is_relation = True many_to_many = False many_to_one = True one_to_many = False one_to_one = False related_model = None allow_unsaved_instance_assignment = False def __init__(self, ct_field='content_type', fk_field='object_id', for_concrete_model=True): self.ct_field = ct_field self.fk_field = fk_field self.for_concrete_model = for_concrete_model self.editable = False self.rel = None self.column = None def contribute_to_class(self, cls, name, **kwargs): self.name = name self.model = cls self.cache_attr = "_%s_cache" % name cls._meta.add_field(self, virtual=True) # Only run pre-initialization field assignment on non-abstract models if not cls._meta.abstract: signals.pre_init.connect(self.instance_pre_init, sender=cls) setattr(cls, name, self) def __str__(self): model = self.model app = model._meta.app_label return '%s.%s.%s' % (app, model._meta.object_name, self.name) def check(self, **kwargs): errors = [] errors.extend(self._check_field_name()) errors.extend(self._check_object_id_field()) errors.extend(self._check_content_type_field()) return errors def _check_field_name(self): if self.name.endswith("_"): return [ checks.Error( 'Field names must not end with an underscore.', hint=None, obj=self, id='fields.E001', ) ] else: return [] def _check_object_id_field(self): try: self.model._meta.get_field(self.fk_field) except FieldDoesNotExist: return [ checks.Error( "The GenericForeignKey object ID references the non-existent field '%s'." % self.fk_field, hint=None, obj=self, id='contenttypes.E001', ) ] else: return [] def _check_content_type_field(self): """ Check if field named `field_name` in model `model` exists and is a valid content_type field (is a ForeignKey to ContentType). """ try: field = self.model._meta.get_field(self.ct_field) except FieldDoesNotExist: return [ checks.Error( "The GenericForeignKey content type references the non-existent field '%s.%s'." % ( self.model._meta.object_name, self.ct_field ), hint=None, obj=self, id='contenttypes.E002', ) ] else: if not isinstance(field, models.ForeignKey): return [ checks.Error( "'%s.%s' is not a ForeignKey." % ( self.model._meta.object_name, self.ct_field ), hint=( "GenericForeignKeys must use a ForeignKey to " "'contenttypes.ContentType' as the 'content_type' field." ), obj=self, id='contenttypes.E003', ) ] elif field.rel.to != ContentType: return [ checks.Error( "'%s.%s' is not a ForeignKey to 'contenttypes.ContentType'." % ( self.model._meta.object_name, self.ct_field ), hint=( "GenericForeignKeys must use a ForeignKey to " "'contenttypes.ContentType' as the 'content_type' field." ), obj=self, id='contenttypes.E004', ) ] else: return [] def instance_pre_init(self, signal, sender, args, kwargs, **_kwargs): """ Handle initializing an object with the generic FK instead of content_type and object_id fields. """ if self.name in kwargs: value = kwargs.pop(self.name) if value is not None: kwargs[self.ct_field] = self.get_content_type(obj=value) kwargs[self.fk_field] = value._get_pk_val() else: kwargs[self.ct_field] = None kwargs[self.fk_field] = None def get_content_type(self, obj=None, id=None, using=None): if obj is not None: return ContentType.objects.db_manager(obj._state.db).get_for_model( obj, for_concrete_model=self.for_concrete_model) elif id is not None: return ContentType.objects.db_manager(using).get_for_id(id) else: # This should never happen. I love comments like this, don't you? raise Exception("Impossible arguments to GFK.get_content_type!") def get_prefetch_queryset(self, instances, queryset=None): if queryset is not None: raise ValueError("Custom queryset can't be used for this lookup.") # For efficiency, group the instances by content type and then do one # query per model fk_dict = defaultdict(set) # We need one instance for each group in order to get the right db: instance_dict = {} ct_attname = self.model._meta.get_field(self.ct_field).get_attname() for instance in instances: # We avoid looking for values if either ct_id or fkey value is None ct_id = getattr(instance, ct_attname) if ct_id is not None: fk_val = getattr(instance, self.fk_field) if fk_val is not None: fk_dict[ct_id].add(fk_val) instance_dict[ct_id] = instance ret_val = [] for ct_id, fkeys in fk_dict.items(): instance = instance_dict[ct_id] ct = self.get_content_type(id=ct_id, using=instance._state.db) ret_val.extend(ct.get_all_objects_for_this_type(pk__in=fkeys)) # For doing the join in Python, we have to match both the FK val and the # content type, so we use a callable that returns a (fk, class) pair. def gfk_key(obj): ct_id = getattr(obj, ct_attname) if ct_id is None: return None else: model = self.get_content_type(id=ct_id, using=obj._state.db).model_class() return (model._meta.pk.get_prep_value(getattr(obj, self.fk_field)), model) return (ret_val, lambda obj: (obj._get_pk_val(), obj.__class__), gfk_key, True, self.cache_attr) def is_cached(self, instance): return hasattr(instance, self.cache_attr) def __get__(self, instance, instance_type=None): if instance is None: return self try: return getattr(instance, self.cache_attr) except AttributeError: rel_obj = None # Make sure to use ContentType.objects.get_for_id() to ensure that # lookups are cached (see ticket #5570). This takes more code than # the naive ``getattr(instance, self.ct_field)``, but has better # performance when dealing with GFKs in loops and such. f = self.model._meta.get_field(self.ct_field) ct_id = getattr(instance, f.get_attname(), None) if ct_id is not None: ct = self.get_content_type(id=ct_id, using=instance._state.db) try: rel_obj = ct.get_object_for_this_type(pk=getattr(instance, self.fk_field)) except ObjectDoesNotExist: pass setattr(instance, self.cache_attr, rel_obj) return rel_obj def __set__(self, instance, value): ct = None fk = None if value is not None: ct = self.get_content_type(obj=value) fk = value._get_pk_val() if not self.allow_unsaved_instance_assignment and fk is None: raise ValueError( 'Cannot assign "%r": "%s" instance isn\'t saved in the database.' % (value, value._meta.object_name) ) setattr(instance, self.ct_field, ct) setattr(instance, self.fk_field, fk) setattr(instance, self.cache_attr, value) class GenericRel(ForeignObjectRel): """ Used by GenericRelation to store information about the relation. """ def __init__(self, field, to, related_name=None, related_query_name=None, limit_choices_to=None): super(GenericRel, self).__init__( field, to, related_name=related_query_name or '+', related_query_name=related_query_name, limit_choices_to=limit_choices_to, on_delete=DO_NOTHING, ) class GenericRelation(ForeignObject): """ Provide a reverse to a relation created by a GenericForeignKey. """ # Field flags auto_created = False many_to_many = False many_to_one = False one_to_many = True one_to_one = False rel_class = GenericRel def __init__(self, to, object_id_field='object_id', content_type_field='content_type', for_concrete_model=True, related_query_name=None, limit_choices_to=None, **kwargs): kwargs['rel'] = self.rel_class( self, to, related_query_name=related_query_name, limit_choices_to=limit_choices_to, ) kwargs['blank'] = True kwargs['editable'] = False kwargs['serialize'] = False # This construct is somewhat of an abuse of ForeignObject. This field # represents a relation from pk to object_id field. But, this relation # isn't direct, the join is generated reverse along foreign key. So, # the from_field is object_id field, to_field is pk because of the # reverse join. super(GenericRelation, self).__init__( to, from_fields=[object_id_field], to_fields=[], **kwargs) self.object_id_field_name = object_id_field self.content_type_field_name = content_type_field self.for_concrete_model = for_concrete_model def check(self, **kwargs): errors = super(GenericRelation, self).check(**kwargs) errors.extend(self._check_generic_foreign_key_existence()) return errors def _check_generic_foreign_key_existence(self): target = self.rel.to if isinstance(target, ModelBase): fields = target._meta.virtual_fields if any(isinstance(field, GenericForeignKey) and field.ct_field == self.content_type_field_name and field.fk_field == self.object_id_field_name for field in fields): return [] else: return [ checks.Error( ("The GenericRelation defines a relation with the model " "'%s.%s', but that model does not have a GenericForeignKey.") % ( target._meta.app_label, target._meta.object_name ), hint=None, obj=self, id='contenttypes.E004', ) ] else: return [] def resolve_related_fields(self): self.to_fields = [self.model._meta.pk.name] return [(self.rel.to._meta.get_field(self.object_id_field_name), self.model._meta.pk)] def get_path_info(self): opts = self.rel.to._meta target = opts.pk return [PathInfo(self.model._meta, opts, (target,), self.rel, True, False)] def get_reverse_path_info(self): opts = self.model._meta from_opts = self.rel.to._meta return [PathInfo(from_opts, opts, (opts.pk,), self, not self.unique, False)] def get_choices_default(self): return super(GenericRelation, self).get_choices(include_blank=False) def value_to_string(self, obj): qs = getattr(obj, self.name).all() return smart_text([instance._get_pk_val() for instance in qs]) def contribute_to_class(self, cls, name, **kwargs): kwargs['virtual_only'] = True super(GenericRelation, self).contribute_to_class(cls, name, **kwargs) self.model = cls setattr(cls, self.name, ReverseGenericRelatedObjectsDescriptor(self.rel)) def set_attributes_from_rel(self): pass def get_internal_type(self): return "ManyToManyField" def get_content_type(self): """ Return the content type associated with this field's model. """ return ContentType.objects.get_for_model(self.model, for_concrete_model=self.for_concrete_model) def get_extra_restriction(self, where_class, alias, remote_alias): field = self.rel.to._meta.get_field(self.content_type_field_name) contenttype_pk = self.get_content_type().pk cond = where_class() lookup = field.get_lookup('exact')(field.get_col(remote_alias), contenttype_pk) cond.add(lookup, 'AND') return cond def bulk_related_objects(self, objs, using=DEFAULT_DB_ALIAS): """ Return all objects related to ``objs`` via this ``GenericRelation``. """ return self.rel.to._base_manager.db_manager(using).filter(**{ "%s__pk" % self.content_type_field_name: ContentType.objects.db_manager(using).get_for_model( self.model, for_concrete_model=self.for_concrete_model).pk, "%s__in" % self.object_id_field_name: [obj.pk for obj in objs] }) class ReverseGenericRelatedObjectsDescriptor(ForeignRelatedObjectsDescriptor): """ Accessor to the related objects manager on the one-to-many relation created by GenericRelation. In the example:: class Post(Model): comments = GenericRelation(Comment) ``post.comments`` is a ReverseGenericRelatedObjectsDescriptor instance. """ @cached_property def related_manager_cls(self): return create_generic_related_manager( self.rel.to._default_manager.__class__, self.rel, ) def create_generic_related_manager(superclass, rel): """ Factory function to create a manager that subclasses another manager (generally the default manager of a given model) and adds behaviors specific to generic relations. """ class GenericRelatedObjectManager(superclass): def __init__(self, instance=None): super(GenericRelatedObjectManager, self).__init__() self.instance = instance self.model = rel.to content_type = ContentType.objects.db_manager(instance._state.db).get_for_model( instance, for_concrete_model=rel.field.for_concrete_model) self.content_type = content_type qn = connection.ops.quote_name join_cols = rel.field.get_joining_columns(reverse_join=True)[0] self.source_col_name = qn(join_cols[0]) self.target_col_name = qn(join_cols[1]) self.content_type_field_name = rel.field.content_type_field_name self.object_id_field_name = rel.field.object_id_field_name self.prefetch_cache_name = rel.field.attname self.pk_val = instance._get_pk_val() self.core_filters = { '%s__pk' % self.content_type_field_name: content_type.id, self.object_id_field_name: self.pk_val, } def __call__(self, **kwargs): # We use **kwargs rather than a kwarg argument to enforce the # `manager='manager_name'` syntax. manager = getattr(self.model, kwargs.pop('manager')) manager_class = create_generic_related_manager(manager.__class__, rel) return manager_class(instance=self.instance) do_not_call_in_templates = True def __str__(self): return repr(self) def get_queryset(self): try: return self.instance._prefetched_objects_cache[self.prefetch_cache_name] except (AttributeError, KeyError): db = self._db or router.db_for_read(self.model, instance=self.instance) return super(GenericRelatedObjectManager, self).get_queryset().using(db).filter(**self.core_filters) def get_prefetch_queryset(self, instances, queryset=None): if queryset is None: queryset = super(GenericRelatedObjectManager, self).get_queryset() queryset._add_hints(instance=instances[0]) queryset = queryset.using(queryset._db or self._db) query = { '%s__pk' % self.content_type_field_name: self.content_type.id, '%s__in' % self.object_id_field_name: set(obj._get_pk_val() for obj in instances) } # We (possibly) need to convert object IDs to the type of the # instances' PK in order to match up instances: object_id_converter = instances[0]._meta.pk.to_python return (queryset.filter(**query), lambda relobj: object_id_converter(getattr(relobj, self.object_id_field_name)), lambda obj: obj._get_pk_val(), False, self.prefetch_cache_name) def add(self, *objs): db = router.db_for_write(self.model, instance=self.instance) with transaction.atomic(using=db, savepoint=False): for obj in objs: if not isinstance(obj, self.model): raise TypeError("'%s' instance expected" % self.model._meta.object_name) setattr(obj, self.content_type_field_name, self.content_type) setattr(obj, self.object_id_field_name, self.pk_val) obj.save() add.alters_data = True def remove(self, *objs, **kwargs): if not objs: return bulk = kwargs.pop('bulk', True) self._clear(self.filter(pk__in=[o.pk for o in objs]), bulk) remove.alters_data = True def clear(self, **kwargs): bulk = kwargs.pop('bulk', True) self._clear(self, bulk) clear.alters_data = True def _clear(self, queryset, bulk): db = router.db_for_write(self.model, instance=self.instance) queryset = queryset.using(db) if bulk: # `QuerySet.delete()` creates its own atomic block which # contains the `pre_delete` and `post_delete` signal handlers. queryset.delete() else: with transaction.atomic(using=db, savepoint=False): for obj in queryset: obj.delete() _clear.alters_data = True def set(self, objs, **kwargs): # Force evaluation of `objs` in case it's a queryset whose value # could be affected by `manager.clear()`. Refs #19816. objs = tuple(objs) clear = kwargs.pop('clear', False) db = router.db_for_write(self.model, instance=self.instance) with transaction.atomic(using=db, savepoint=False): if clear: self.clear() self.add(*objs) else: old_objs = set(self.using(db).all()) new_objs = [] for obj in objs: if obj in old_objs: old_objs.remove(obj) else: new_objs.append(obj) self.remove(*old_objs) self.add(*new_objs) set.alters_data = True def create(self, **kwargs): kwargs[self.content_type_field_name] = self.content_type kwargs[self.object_id_field_name] = self.pk_val db = router.db_for_write(self.model, instance=self.instance) return super(GenericRelatedObjectManager, self).using(db).create(**kwargs) create.alters_data = True def get_or_create(self, **kwargs): kwargs[self.content_type_field_name] = self.content_type kwargs[self.object_id_field_name] = self.pk_val db = router.db_for_write(self.model, instance=self.instance) return super(GenericRelatedObjectManager, self).using(db).get_or_create(**kwargs) get_or_create.alters_data = True def update_or_create(self, **kwargs): kwargs[self.content_type_field_name] = self.content_type kwargs[self.object_id_field_name] = self.pk_val db = router.db_for_write(self.model, instance=self.instance) return super(GenericRelatedObjectManager, self).using(db).update_or_create(**kwargs) update_or_create.alters_data = True return GenericRelatedObjectManager
38.873504
116
0.592146
from __future__ import unicode_literals from collections import defaultdict from django.contrib.contenttypes.models import ContentType from django.core import checks from django.core.exceptions import FieldDoesNotExist, ObjectDoesNotExist from django.db import DEFAULT_DB_ALIAS, connection, models, router, transaction from django.db.models import DO_NOTHING, signals from django.db.models.base import ModelBase from django.db.models.fields.related import ( ForeignObject, ForeignObjectRel, ForeignRelatedObjectsDescriptor, ) from django.db.models.query_utils import PathInfo from django.utils.encoding import python_2_unicode_compatible, smart_text from django.utils.functional import cached_property @python_2_unicode_compatible class GenericForeignKey(object): auto_created = False concrete = False editable = False hidden = False is_relation = True many_to_many = False many_to_one = True one_to_many = False one_to_one = False related_model = None allow_unsaved_instance_assignment = False def __init__(self, ct_field='content_type', fk_field='object_id', for_concrete_model=True): self.ct_field = ct_field self.fk_field = fk_field self.for_concrete_model = for_concrete_model self.editable = False self.rel = None self.column = None def contribute_to_class(self, cls, name, **kwargs): self.name = name self.model = cls self.cache_attr = "_%s_cache" % name cls._meta.add_field(self, virtual=True) if not cls._meta.abstract: signals.pre_init.connect(self.instance_pre_init, sender=cls) setattr(cls, name, self) def __str__(self): model = self.model app = model._meta.app_label return '%s.%s.%s' % (app, model._meta.object_name, self.name) def check(self, **kwargs): errors = [] errors.extend(self._check_field_name()) errors.extend(self._check_object_id_field()) errors.extend(self._check_content_type_field()) return errors def _check_field_name(self): if self.name.endswith("_"): return [ checks.Error( 'Field names must not end with an underscore.', hint=None, obj=self, id='fields.E001', ) ] else: return [] def _check_object_id_field(self): try: self.model._meta.get_field(self.fk_field) except FieldDoesNotExist: return [ checks.Error( "The GenericForeignKey object ID references the non-existent field '%s'." % self.fk_field, hint=None, obj=self, id='contenttypes.E001', ) ] else: return [] def _check_content_type_field(self): try: field = self.model._meta.get_field(self.ct_field) except FieldDoesNotExist: return [ checks.Error( "The GenericForeignKey content type references the non-existent field '%s.%s'." % ( self.model._meta.object_name, self.ct_field ), hint=None, obj=self, id='contenttypes.E002', ) ] else: if not isinstance(field, models.ForeignKey): return [ checks.Error( "'%s.%s' is not a ForeignKey." % ( self.model._meta.object_name, self.ct_field ), hint=( "GenericForeignKeys must use a ForeignKey to " "'contenttypes.ContentType' as the 'content_type' field." ), obj=self, id='contenttypes.E003', ) ] elif field.rel.to != ContentType: return [ checks.Error( "'%s.%s' is not a ForeignKey to 'contenttypes.ContentType'." % ( self.model._meta.object_name, self.ct_field ), hint=( "GenericForeignKeys must use a ForeignKey to " "'contenttypes.ContentType' as the 'content_type' field." ), obj=self, id='contenttypes.E004', ) ] else: return [] def instance_pre_init(self, signal, sender, args, kwargs, **_kwargs): if self.name in kwargs: value = kwargs.pop(self.name) if value is not None: kwargs[self.ct_field] = self.get_content_type(obj=value) kwargs[self.fk_field] = value._get_pk_val() else: kwargs[self.ct_field] = None kwargs[self.fk_field] = None def get_content_type(self, obj=None, id=None, using=None): if obj is not None: return ContentType.objects.db_manager(obj._state.db).get_for_model( obj, for_concrete_model=self.for_concrete_model) elif id is not None: return ContentType.objects.db_manager(using).get_for_id(id) else: raise Exception("Impossible arguments to GFK.get_content_type!") def get_prefetch_queryset(self, instances, queryset=None): if queryset is not None: raise ValueError("Custom queryset can't be used for this lookup.") fk_dict = defaultdict(set) instance_dict = {} ct_attname = self.model._meta.get_field(self.ct_field).get_attname() for instance in instances: ct_id = getattr(instance, ct_attname) if ct_id is not None: fk_val = getattr(instance, self.fk_field) if fk_val is not None: fk_dict[ct_id].add(fk_val) instance_dict[ct_id] = instance ret_val = [] for ct_id, fkeys in fk_dict.items(): instance = instance_dict[ct_id] ct = self.get_content_type(id=ct_id, using=instance._state.db) ret_val.extend(ct.get_all_objects_for_this_type(pk__in=fkeys)) def gfk_key(obj): ct_id = getattr(obj, ct_attname) if ct_id is None: return None else: model = self.get_content_type(id=ct_id, using=obj._state.db).model_class() return (model._meta.pk.get_prep_value(getattr(obj, self.fk_field)), model) return (ret_val, lambda obj: (obj._get_pk_val(), obj.__class__), gfk_key, True, self.cache_attr) def is_cached(self, instance): return hasattr(instance, self.cache_attr) def __get__(self, instance, instance_type=None): if instance is None: return self try: return getattr(instance, self.cache_attr) except AttributeError: rel_obj = None f = self.model._meta.get_field(self.ct_field) ct_id = getattr(instance, f.get_attname(), None) if ct_id is not None: ct = self.get_content_type(id=ct_id, using=instance._state.db) try: rel_obj = ct.get_object_for_this_type(pk=getattr(instance, self.fk_field)) except ObjectDoesNotExist: pass setattr(instance, self.cache_attr, rel_obj) return rel_obj def __set__(self, instance, value): ct = None fk = None if value is not None: ct = self.get_content_type(obj=value) fk = value._get_pk_val() if not self.allow_unsaved_instance_assignment and fk is None: raise ValueError( 'Cannot assign "%r": "%s" instance isn\'t saved in the database.' % (value, value._meta.object_name) ) setattr(instance, self.ct_field, ct) setattr(instance, self.fk_field, fk) setattr(instance, self.cache_attr, value) class GenericRel(ForeignObjectRel): def __init__(self, field, to, related_name=None, related_query_name=None, limit_choices_to=None): super(GenericRel, self).__init__( field, to, related_name=related_query_name or '+', related_query_name=related_query_name, limit_choices_to=limit_choices_to, on_delete=DO_NOTHING, ) class GenericRelation(ForeignObject): # Field flags auto_created = False many_to_many = False many_to_one = False one_to_many = True one_to_one = False rel_class = GenericRel def __init__(self, to, object_id_field='object_id', content_type_field='content_type', for_concrete_model=True, related_query_name=None, limit_choices_to=None, **kwargs): kwargs['rel'] = self.rel_class( self, to, related_query_name=related_query_name, limit_choices_to=limit_choices_to, ) kwargs['blank'] = True kwargs['editable'] = False kwargs['serialize'] = False # This construct is somewhat of an abuse of ForeignObject. This field # represents a relation from pk to object_id field. But, this relation # isn't direct, the join is generated reverse along foreign key. So, super(GenericRelation, self).__init__( to, from_fields=[object_id_field], to_fields=[], **kwargs) self.object_id_field_name = object_id_field self.content_type_field_name = content_type_field self.for_concrete_model = for_concrete_model def check(self, **kwargs): errors = super(GenericRelation, self).check(**kwargs) errors.extend(self._check_generic_foreign_key_existence()) return errors def _check_generic_foreign_key_existence(self): target = self.rel.to if isinstance(target, ModelBase): fields = target._meta.virtual_fields if any(isinstance(field, GenericForeignKey) and field.ct_field == self.content_type_field_name and field.fk_field == self.object_id_field_name for field in fields): return [] else: return [ checks.Error( ("The GenericRelation defines a relation with the model " "'%s.%s', but that model does not have a GenericForeignKey.") % ( target._meta.app_label, target._meta.object_name ), hint=None, obj=self, id='contenttypes.E004', ) ] else: return [] def resolve_related_fields(self): self.to_fields = [self.model._meta.pk.name] return [(self.rel.to._meta.get_field(self.object_id_field_name), self.model._meta.pk)] def get_path_info(self): opts = self.rel.to._meta target = opts.pk return [PathInfo(self.model._meta, opts, (target,), self.rel, True, False)] def get_reverse_path_info(self): opts = self.model._meta from_opts = self.rel.to._meta return [PathInfo(from_opts, opts, (opts.pk,), self, not self.unique, False)] def get_choices_default(self): return super(GenericRelation, self).get_choices(include_blank=False) def value_to_string(self, obj): qs = getattr(obj, self.name).all() return smart_text([instance._get_pk_val() for instance in qs]) def contribute_to_class(self, cls, name, **kwargs): kwargs['virtual_only'] = True super(GenericRelation, self).contribute_to_class(cls, name, **kwargs) self.model = cls setattr(cls, self.name, ReverseGenericRelatedObjectsDescriptor(self.rel)) def set_attributes_from_rel(self): pass def get_internal_type(self): return "ManyToManyField" def get_content_type(self): return ContentType.objects.get_for_model(self.model, for_concrete_model=self.for_concrete_model) def get_extra_restriction(self, where_class, alias, remote_alias): field = self.rel.to._meta.get_field(self.content_type_field_name) contenttype_pk = self.get_content_type().pk cond = where_class() lookup = field.get_lookup('exact')(field.get_col(remote_alias), contenttype_pk) cond.add(lookup, 'AND') return cond def bulk_related_objects(self, objs, using=DEFAULT_DB_ALIAS): return self.rel.to._base_manager.db_manager(using).filter(**{ "%s__pk" % self.content_type_field_name: ContentType.objects.db_manager(using).get_for_model( self.model, for_concrete_model=self.for_concrete_model).pk, "%s__in" % self.object_id_field_name: [obj.pk for obj in objs] }) class ReverseGenericRelatedObjectsDescriptor(ForeignRelatedObjectsDescriptor): @cached_property def related_manager_cls(self): return create_generic_related_manager( self.rel.to._default_manager.__class__, self.rel, ) def create_generic_related_manager(superclass, rel): class GenericRelatedObjectManager(superclass): def __init__(self, instance=None): super(GenericRelatedObjectManager, self).__init__() self.instance = instance self.model = rel.to content_type = ContentType.objects.db_manager(instance._state.db).get_for_model( instance, for_concrete_model=rel.field.for_concrete_model) self.content_type = content_type qn = connection.ops.quote_name join_cols = rel.field.get_joining_columns(reverse_join=True)[0] self.source_col_name = qn(join_cols[0]) self.target_col_name = qn(join_cols[1]) self.content_type_field_name = rel.field.content_type_field_name self.object_id_field_name = rel.field.object_id_field_name self.prefetch_cache_name = rel.field.attname self.pk_val = instance._get_pk_val() self.core_filters = { '%s__pk' % self.content_type_field_name: content_type.id, self.object_id_field_name: self.pk_val, } def __call__(self, **kwargs): manager = getattr(self.model, kwargs.pop('manager')) manager_class = create_generic_related_manager(manager.__class__, rel) return manager_class(instance=self.instance) do_not_call_in_templates = True def __str__(self): return repr(self) def get_queryset(self): try: return self.instance._prefetched_objects_cache[self.prefetch_cache_name] except (AttributeError, KeyError): db = self._db or router.db_for_read(self.model, instance=self.instance) return super(GenericRelatedObjectManager, self).get_queryset().using(db).filter(**self.core_filters) def get_prefetch_queryset(self, instances, queryset=None): if queryset is None: queryset = super(GenericRelatedObjectManager, self).get_queryset() queryset._add_hints(instance=instances[0]) queryset = queryset.using(queryset._db or self._db) query = { '%s__pk' % self.content_type_field_name: self.content_type.id, '%s__in' % self.object_id_field_name: set(obj._get_pk_val() for obj in instances) } object_id_converter = instances[0]._meta.pk.to_python return (queryset.filter(**query), lambda relobj: object_id_converter(getattr(relobj, self.object_id_field_name)), lambda obj: obj._get_pk_val(), False, self.prefetch_cache_name) def add(self, *objs): db = router.db_for_write(self.model, instance=self.instance) with transaction.atomic(using=db, savepoint=False): for obj in objs: if not isinstance(obj, self.model): raise TypeError("'%s' instance expected" % self.model._meta.object_name) setattr(obj, self.content_type_field_name, self.content_type) setattr(obj, self.object_id_field_name, self.pk_val) obj.save() add.alters_data = True def remove(self, *objs, **kwargs): if not objs: return bulk = kwargs.pop('bulk', True) self._clear(self.filter(pk__in=[o.pk for o in objs]), bulk) remove.alters_data = True def clear(self, **kwargs): bulk = kwargs.pop('bulk', True) self._clear(self, bulk) clear.alters_data = True def _clear(self, queryset, bulk): db = router.db_for_write(self.model, instance=self.instance) queryset = queryset.using(db) if bulk: # `QuerySet.delete()` creates its own atomic block which # contains the `pre_delete` and `post_delete` signal handlers. queryset.delete() else: with transaction.atomic(using=db, savepoint=False): for obj in queryset: obj.delete() _clear.alters_data = True def set(self, objs, **kwargs): # Force evaluation of `objs` in case it's a queryset whose value objs = tuple(objs) clear = kwargs.pop('clear', False) db = router.db_for_write(self.model, instance=self.instance) with transaction.atomic(using=db, savepoint=False): if clear: self.clear() self.add(*objs) else: old_objs = set(self.using(db).all()) new_objs = [] for obj in objs: if obj in old_objs: old_objs.remove(obj) else: new_objs.append(obj) self.remove(*old_objs) self.add(*new_objs) set.alters_data = True def create(self, **kwargs): kwargs[self.content_type_field_name] = self.content_type kwargs[self.object_id_field_name] = self.pk_val db = router.db_for_write(self.model, instance=self.instance) return super(GenericRelatedObjectManager, self).using(db).create(**kwargs) create.alters_data = True def get_or_create(self, **kwargs): kwargs[self.content_type_field_name] = self.content_type kwargs[self.object_id_field_name] = self.pk_val db = router.db_for_write(self.model, instance=self.instance) return super(GenericRelatedObjectManager, self).using(db).get_or_create(**kwargs) get_or_create.alters_data = True def update_or_create(self, **kwargs): kwargs[self.content_type_field_name] = self.content_type kwargs[self.object_id_field_name] = self.pk_val db = router.db_for_write(self.model, instance=self.instance) return super(GenericRelatedObjectManager, self).using(db).update_or_create(**kwargs) update_or_create.alters_data = True return GenericRelatedObjectManager
true
true
f72cd646013ea6a170a5f979dcbd68b1bc930df2
8,783
py
Python
nintendo/nnas.py
elsorino/DiscordAndU
70e57bbd55daa2b0e24cff0831867daff05822f8
[ "MIT" ]
1
2021-04-26T19:23:56.000Z
2021-04-26T19:23:56.000Z
nintendo/nnas.py
elsorino/DiscordAndU
70e57bbd55daa2b0e24cff0831867daff05822f8
[ "MIT" ]
null
null
null
nintendo/nnas.py
elsorino/DiscordAndU
70e57bbd55daa2b0e24cff0831867daff05822f8
[ "MIT" ]
null
null
null
from nintendo.common.http import HTTPClient, HTTPRequest from nintendo.common import xml, ssl, util import pkg_resources import collections import hashlib import struct import base64 import urllib.parse import logging logger = logging.getLogger(__name__) CERT = pkg_resources.resource_filename("nintendo", "files/cert/wiiu_common.crt") KEY = pkg_resources.resource_filename("nintendo", "files/cert/wiiu_common.key") def calc_password_hash(pid, password): data = struct.pack("<I", pid) + b"\x02\x65\x43\x46" + password.encode("ascii") return hashlib.sha256(data).hexdigest() # Types NexToken = collections.namedtuple("NexToken", "host port username password token") Email = collections.namedtuple("Email", "address id parent primary reachable type validated validation_date") Mii = collections.namedtuple("Mii", "data id images name pid primary nnid") ProfileMii = collections.namedtuple("Mii", "data id hash images name primary") Account = collections.namedtuple("Account", "attributes domain type username") Profile = collections.namedtuple( "Profile", "accounts active birthday country creation_date device_attributes gender language " "updated marketing off_device pid email mii region timezone nnid utc_offset" ) # Parsers NexToken.parse = lambda obj: NexToken( obj["host"].value, int(obj["port"].value), obj["pid"].value, obj["nex_password"].value, obj["token"].value ) Email.parse = lambda obj: Email( obj["address"].value, int(obj["id"].value), obj["parent"].value == "Y", obj["primary"].value == "Y", obj["reachable"].value == "Y", obj["type"].value, obj["validated"].value == "Y", obj["validated_date"].value ) Mii.parse = lambda obj: Mii( base64.b64decode(obj["data"].value), int(obj["id"].value), {image["type"].value: image["url"].value for image in obj["images"]}, obj["name"].value, int(obj["pid"].value), obj["primary"].value == "Y", obj["user_id"].value ) ProfileMii.parse = lambda obj: ProfileMii( base64.b64decode(obj["data"].value), int(obj["id"].value), obj["mii_hash"].value, {image["type"].value: image["url"].value for image in obj["mii_images"]}, obj["name"].value, obj["primary"].value == "Y", ) Account.parse = lambda obj: Account( obj["attributes"].value, obj["domain"].value, obj["type"].value, obj["username"].value ) Profile.parse = lambda obj: Profile( [Account.parse(account) for account in obj["accounts"]], obj["active_flag"].value == "Y", obj["birth_date"].value, obj["country"].value, obj["create_date"].value, {attrib["name"].value: attrib["value"].value for attrib in obj["device_attributes"]}, obj["gender"].value, obj["language"].value, obj["updated"].value, obj["marketing_flag"].value == "Y", obj["off_device_flag"].value == "Y", int(obj["pid"].value), Email.parse(obj["email"]), ProfileMii.parse(obj["mii"]), int(obj["region"].value), obj["tz_name"].value, obj["user_id"].value, int(obj["utc_offset"].value) ) class NNASError(Exception): def __init__(self, *, status_code, text): self.status_code = status_code self.text = text def __str__(self): return "Account request failed with status %i" %self.status_code class NNASClient: def __init__(self): self.client = HTTPClient() cert = ssl.SSLCertificate.load(CERT, ssl.TYPE_PEM) key = ssl.SSLPrivateKey.load(KEY, ssl.TYPE_PEM) self.cert = cert, key self.url = "account.nintendo.net" self.client_id = "a2efa818a34fa16b8afbc8a74eba3eda" self.client_secret = "c91cdb5658bd4954ade78533a339cf9a" self.platform_id = 1 self.device_type = 2 self.device_id = None self.serial_number = None self.system_version = 0x250 self.device_cert = None self.region = 4 self.country = "NL" self.language = "en" self.fpd_version = 0 self.environment = "L1" self.title_id = None self.title_version = None self.auth_token = None def set_certificate(self, cert, key): self.cert = cert, key def set_url(self, url): self.url = url def set_client_id(self, client_id): self.client_id = client_id def set_client_secret(self, client_secret): self.client_secret = client_secret def set_platform_id(self, platform_id): self.platform_id = platform_id def set_device_type(self, device_type): self.device_type = device_type def set_device(self, device_id, serial_number, system_version, cert=None): self.device_id = device_id self.serial_number = serial_number self.system_version = system_version self.device_cert = cert def set_locale(self, region, country, language): self.region = region self.country = country self.language = language def set_fpd_version(self, version): self.fpd_version = version def set_environment(self, environment): self.environment = environment def set_title(self, title_id, title_version): self.title_id = title_id self.title_version = title_version def prepare(self, req, auth=None, cert=None): req.certificate = self.cert req.headers["Host"] = self.url req.headers["X-Nintendo-Platform-ID"] = self.platform_id req.headers["X-Nintendo-Device-Type"] = self.device_type if self.device_id is not None: req.headers["X-Nintendo-Device-ID"] = self.device_id if self.serial_number is not None: req.headers["X-Nintendo-Serial-Number"] = self.serial_number req.headers["X-Nintendo-System-Version"] = "%04X" %self.system_version req.headers["X-Nintendo-Region"] = self.region req.headers["X-Nintendo-Country"] = self.country req.headers["Accept-Language"] = self.language if auth is None: req.headers["X-Nintendo-Client-ID"] = self.client_id req.headers["X-Nintendo-Client-Secret"] = self.client_secret req.headers["Accept"] = "*/*" req.headers["X-Nintendo-FPD-Version"] = "%04X" %self.fpd_version req.headers["X-Nintendo-Environment"] = self.environment if self.title_id is not None: req.headers["X-Nintendo-Title-ID"] = "%016X" %self.title_id req.headers["X-Nintendo-Unique-ID"] = "%05X" %((self.title_id >> 8) & 0xFFFFF) if self.title_version is not None: req.headers["X-Nintendo-Application-Version"] = "%04X" %self.title_version if cert is not None: req.headers["X-Nintendo-Device-Cert"] = cert if auth is not None: req.headers["Authorization"] = auth def request(self, req): response = self.client.request(req, True) if response.error(): logger.error("Account request returned status code %i\n%s", response.status, response.text) raise NNASError(status_code=response.status, text=response.text) return response.xml def login(self, username, password, password_type=None): req = HTTPRequest.post("/v1/api/oauth20/access_token/generate") self.prepare(req, cert=self.device_cert) req.form["grant_type"] = "password" req.form["user_id"] = urllib.parse.quote(username) req.form["password"] = urllib.parse.quote(password) if password_type is not None: req.form["password_type"] = password_type response = self.request(req) self.auth_token = "Bearer " + response["access_token"]["token"].value def get_emails(self): req = HTTPRequest.get("/v1/api/people/@me/emails") self.prepare(req, self.auth_token) return [Email.parse(email) for email in self.request(req)] def get_profile(self): req = HTTPRequest.get("/v1/api/people/@me/profile") self.prepare(req, self.auth_token) return Profile.parse(self.request(req)) def get_nex_token(self, game_server_id): req = HTTPRequest.get("/v1/api/provider/nex_token/@me") req.params["game_server_id"] = "%08X" %game_server_id self.prepare(req, self.auth_token) return NexToken.parse(self.request(req)) #The following functions can be used without logging in def get_miis(self, pids): req = HTTPRequest.get("/v1/api/miis") req.params["pids"] = urllib.parse.quote(",".join([str(pid) for pid in pids])) self.prepare(req) response = self.request(req) return [Mii.parse(mii) for mii in response] def get_pids(self, nnids): req = HTTPRequest.get("/v1/api/admin/mapped_ids") req.params["input_type"] = "user_id" req.params["output_type"] = "pid" req.params["input"] = urllib.parse.quote(",".join(nnids)) self.prepare(req) response = self.request(req) return {id["in_id"].value: int(id["out_id"].value) for id in response} def get_nnids(self, pids): req = HTTPRequest.get("/v1/api/admin/mapped_ids") req.params["input_type"] = "pid" req.params["output_type"] = "user_id" req.params["input"] = urllib.parse.quote(",".join([str(pid) for pid in pids])) self.prepare(req) response = self.request(req) return {int(id["in_id"].value): id["out_id"].value for id in response} def get_mii(self, pid): return self.get_miis([pid])[0] def get_pid(self, nnid): return self.get_pids([nnid])[nnid] def get_nnid(self, pid): return self.get_nnids([pid])[pid]
31.822464
109
0.710919
from nintendo.common.http import HTTPClient, HTTPRequest from nintendo.common import xml, ssl, util import pkg_resources import collections import hashlib import struct import base64 import urllib.parse import logging logger = logging.getLogger(__name__) CERT = pkg_resources.resource_filename("nintendo", "files/cert/wiiu_common.crt") KEY = pkg_resources.resource_filename("nintendo", "files/cert/wiiu_common.key") def calc_password_hash(pid, password): data = struct.pack("<I", pid) + b"\x02\x65\x43\x46" + password.encode("ascii") return hashlib.sha256(data).hexdigest() NexToken = collections.namedtuple("NexToken", "host port username password token") Email = collections.namedtuple("Email", "address id parent primary reachable type validated validation_date") Mii = collections.namedtuple("Mii", "data id images name pid primary nnid") ProfileMii = collections.namedtuple("Mii", "data id hash images name primary") Account = collections.namedtuple("Account", "attributes domain type username") Profile = collections.namedtuple( "Profile", "accounts active birthday country creation_date device_attributes gender language " "updated marketing off_device pid email mii region timezone nnid utc_offset" ) NexToken.parse = lambda obj: NexToken( obj["host"].value, int(obj["port"].value), obj["pid"].value, obj["nex_password"].value, obj["token"].value ) Email.parse = lambda obj: Email( obj["address"].value, int(obj["id"].value), obj["parent"].value == "Y", obj["primary"].value == "Y", obj["reachable"].value == "Y", obj["type"].value, obj["validated"].value == "Y", obj["validated_date"].value ) Mii.parse = lambda obj: Mii( base64.b64decode(obj["data"].value), int(obj["id"].value), {image["type"].value: image["url"].value for image in obj["images"]}, obj["name"].value, int(obj["pid"].value), obj["primary"].value == "Y", obj["user_id"].value ) ProfileMii.parse = lambda obj: ProfileMii( base64.b64decode(obj["data"].value), int(obj["id"].value), obj["mii_hash"].value, {image["type"].value: image["url"].value for image in obj["mii_images"]}, obj["name"].value, obj["primary"].value == "Y", ) Account.parse = lambda obj: Account( obj["attributes"].value, obj["domain"].value, obj["type"].value, obj["username"].value ) Profile.parse = lambda obj: Profile( [Account.parse(account) for account in obj["accounts"]], obj["active_flag"].value == "Y", obj["birth_date"].value, obj["country"].value, obj["create_date"].value, {attrib["name"].value: attrib["value"].value for attrib in obj["device_attributes"]}, obj["gender"].value, obj["language"].value, obj["updated"].value, obj["marketing_flag"].value == "Y", obj["off_device_flag"].value == "Y", int(obj["pid"].value), Email.parse(obj["email"]), ProfileMii.parse(obj["mii"]), int(obj["region"].value), obj["tz_name"].value, obj["user_id"].value, int(obj["utc_offset"].value) ) class NNASError(Exception): def __init__(self, *, status_code, text): self.status_code = status_code self.text = text def __str__(self): return "Account request failed with status %i" %self.status_code class NNASClient: def __init__(self): self.client = HTTPClient() cert = ssl.SSLCertificate.load(CERT, ssl.TYPE_PEM) key = ssl.SSLPrivateKey.load(KEY, ssl.TYPE_PEM) self.cert = cert, key self.url = "account.nintendo.net" self.client_id = "a2efa818a34fa16b8afbc8a74eba3eda" self.client_secret = "c91cdb5658bd4954ade78533a339cf9a" self.platform_id = 1 self.device_type = 2 self.device_id = None self.serial_number = None self.system_version = 0x250 self.device_cert = None self.region = 4 self.country = "NL" self.language = "en" self.fpd_version = 0 self.environment = "L1" self.title_id = None self.title_version = None self.auth_token = None def set_certificate(self, cert, key): self.cert = cert, key def set_url(self, url): self.url = url def set_client_id(self, client_id): self.client_id = client_id def set_client_secret(self, client_secret): self.client_secret = client_secret def set_platform_id(self, platform_id): self.platform_id = platform_id def set_device_type(self, device_type): self.device_type = device_type def set_device(self, device_id, serial_number, system_version, cert=None): self.device_id = device_id self.serial_number = serial_number self.system_version = system_version self.device_cert = cert def set_locale(self, region, country, language): self.region = region self.country = country self.language = language def set_fpd_version(self, version): self.fpd_version = version def set_environment(self, environment): self.environment = environment def set_title(self, title_id, title_version): self.title_id = title_id self.title_version = title_version def prepare(self, req, auth=None, cert=None): req.certificate = self.cert req.headers["Host"] = self.url req.headers["X-Nintendo-Platform-ID"] = self.platform_id req.headers["X-Nintendo-Device-Type"] = self.device_type if self.device_id is not None: req.headers["X-Nintendo-Device-ID"] = self.device_id if self.serial_number is not None: req.headers["X-Nintendo-Serial-Number"] = self.serial_number req.headers["X-Nintendo-System-Version"] = "%04X" %self.system_version req.headers["X-Nintendo-Region"] = self.region req.headers["X-Nintendo-Country"] = self.country req.headers["Accept-Language"] = self.language if auth is None: req.headers["X-Nintendo-Client-ID"] = self.client_id req.headers["X-Nintendo-Client-Secret"] = self.client_secret req.headers["Accept"] = "*/*" req.headers["X-Nintendo-FPD-Version"] = "%04X" %self.fpd_version req.headers["X-Nintendo-Environment"] = self.environment if self.title_id is not None: req.headers["X-Nintendo-Title-ID"] = "%016X" %self.title_id req.headers["X-Nintendo-Unique-ID"] = "%05X" %((self.title_id >> 8) & 0xFFFFF) if self.title_version is not None: req.headers["X-Nintendo-Application-Version"] = "%04X" %self.title_version if cert is not None: req.headers["X-Nintendo-Device-Cert"] = cert if auth is not None: req.headers["Authorization"] = auth def request(self, req): response = self.client.request(req, True) if response.error(): logger.error("Account request returned status code %i\n%s", response.status, response.text) raise NNASError(status_code=response.status, text=response.text) return response.xml def login(self, username, password, password_type=None): req = HTTPRequest.post("/v1/api/oauth20/access_token/generate") self.prepare(req, cert=self.device_cert) req.form["grant_type"] = "password" req.form["user_id"] = urllib.parse.quote(username) req.form["password"] = urllib.parse.quote(password) if password_type is not None: req.form["password_type"] = password_type response = self.request(req) self.auth_token = "Bearer " + response["access_token"]["token"].value def get_emails(self): req = HTTPRequest.get("/v1/api/people/@me/emails") self.prepare(req, self.auth_token) return [Email.parse(email) for email in self.request(req)] def get_profile(self): req = HTTPRequest.get("/v1/api/people/@me/profile") self.prepare(req, self.auth_token) return Profile.parse(self.request(req)) def get_nex_token(self, game_server_id): req = HTTPRequest.get("/v1/api/provider/nex_token/@me") req.params["game_server_id"] = "%08X" %game_server_id self.prepare(req, self.auth_token) return NexToken.parse(self.request(req)) def get_miis(self, pids): req = HTTPRequest.get("/v1/api/miis") req.params["pids"] = urllib.parse.quote(",".join([str(pid) for pid in pids])) self.prepare(req) response = self.request(req) return [Mii.parse(mii) for mii in response] def get_pids(self, nnids): req = HTTPRequest.get("/v1/api/admin/mapped_ids") req.params["input_type"] = "user_id" req.params["output_type"] = "pid" req.params["input"] = urllib.parse.quote(",".join(nnids)) self.prepare(req) response = self.request(req) return {id["in_id"].value: int(id["out_id"].value) for id in response} def get_nnids(self, pids): req = HTTPRequest.get("/v1/api/admin/mapped_ids") req.params["input_type"] = "pid" req.params["output_type"] = "user_id" req.params["input"] = urllib.parse.quote(",".join([str(pid) for pid in pids])) self.prepare(req) response = self.request(req) return {int(id["in_id"].value): id["out_id"].value for id in response} def get_mii(self, pid): return self.get_miis([pid])[0] def get_pid(self, nnid): return self.get_pids([nnid])[nnid] def get_nnid(self, pid): return self.get_nnids([pid])[pid]
true
true
f72cd64df372a6dea962a0662deef14976f5aa45
507
py
Python
accounts/urls.py
JhoLee/django-lecture_manager
d74ab1d48c954583ffd509346d7cb30b9214f1dc
[ "MIT" ]
null
null
null
accounts/urls.py
JhoLee/django-lecture_manager
d74ab1d48c954583ffd509346d7cb30b9214f1dc
[ "MIT" ]
7
2020-06-05T20:02:50.000Z
2021-09-22T18:05:02.000Z
accounts/urls.py
JhoLee/django-lecture_manager
d74ab1d48c954583ffd509346d7cb30b9214f1dc
[ "MIT" ]
null
null
null
from django.contrib.auth import views as auth_views from django.urls import path from . import views app_name = 'accounts' urlpatterns = [ path('signup/', views.signup, name='signup'), path('login/', views.signin, name='login'), path('logout/', views.signout, name='logout'), path('profile/', views.view_profile, name='view_profile'), path('profile/update/', views.update_profile, name='update_profile'), path('change-password/', views.change_password, name='password_change'), ]
31.6875
76
0.704142
from django.contrib.auth import views as auth_views from django.urls import path from . import views app_name = 'accounts' urlpatterns = [ path('signup/', views.signup, name='signup'), path('login/', views.signin, name='login'), path('logout/', views.signout, name='logout'), path('profile/', views.view_profile, name='view_profile'), path('profile/update/', views.update_profile, name='update_profile'), path('change-password/', views.change_password, name='password_change'), ]
true
true
f72cd66faafd23457f38cf7a6f13260a3caed7b6
2,894
py
Python
deps/turtlebot/follow_line_tc_pkg/scripts/follow_line_step_basicimage.py
CARMinesDouai/2021-robot_guide
226e3279a710c34d6f7b31e4cba4f047ae8aabee
[ "MIT" ]
null
null
null
deps/turtlebot/follow_line_tc_pkg/scripts/follow_line_step_basicimage.py
CARMinesDouai/2021-robot_guide
226e3279a710c34d6f7b31e4cba4f047ae8aabee
[ "MIT" ]
null
null
null
deps/turtlebot/follow_line_tc_pkg/scripts/follow_line_step_basicimage.py
CARMinesDouai/2021-robot_guide
226e3279a710c34d6f7b31e4cba4f047ae8aabee
[ "MIT" ]
1
2020-12-15T10:17:24.000Z
2020-12-15T10:17:24.000Z
#!/usr/bin/env python import rospy import cv2 from cv_bridge import CvBridge, CvBridgeError from geometry_msgs.msg import Twist from sensor_msgs.msg import Image class LineFollower(object): def __init__(self): self.bridge_object = CvBridge() self.cmd_vel_pub = rospy.Publisher('/cmd_vel', Twist, queue_size=10) self.cmd_vel_subs = rospy.Subscriber('/cmd_vel', Twist, self.cmdvel_callback) self.last_cmdvel_command = Twist() self._cmdvel_pub_rate = rospy.Rate(10) self.image_sub = rospy.Subscriber("/camera/rgb/image_raw",Image,self.camera_callback) def cmdvel_callback(self,msg): self.last_cmdvel_command = msg def compare_twist_commands(self,twist1,twist2): LX = twist1.linear.x == twist2.linear.x LY = twist1.linear.y == twist2.linear.y LZ = twist1.linear.z == twist2.linear.z AX = twist1.angular.x == twist2.angular.x AY = twist1.angular.y == twist2.angular.y AZ = twist1.angular.z == twist2.angular.z equal = LX and LY and LZ and AX and AY and AZ if not equal: rospy.logwarn("The Current Twist is not the same as the one sent, Resending") return equal def camera_callback(self,data): try: # We select bgr8 because its the OpneCV encoding by default cv_image = self.bridge_object.imgmsg_to_cv2(data, desired_encoding="bgr8") except CvBridgeError as e: print(e) cv2.imshow("Image window", cv_image) cv2.waitKey(1) def move_robot(self, twist_object): # We make this to avoid Topic loss, specially at the start current_equal_to_new = False while (not (current_equal_to_new) ): self.cmd_vel_pub.publish(twist_object) self._cmdvel_pub_rate.sleep() current_equal_to_new = self.compare_twist_commands(twist1=self.last_cmdvel_command, twist2=twist_object) def clean_class(self): # Stop Robot twist_object = Twist() twist_object.angular.z = 0.0 self.move_robot(twist_object) def main(): rospy.init_node('line_following_node', anonymous=True) line_follower_object = LineFollower() twist_object = Twist() # Make it start turning twist_object.angular.z = 0.5 rate = rospy.Rate(5) ctrl_c = False def shutdownhook(): # works better than the rospy.is_shut_down() line_follower_object.clean_class() cv2.destroyAllWindows() rospy.loginfo("shutdown time!") ctrl_c = True rospy.on_shutdown(shutdownhook) while not ctrl_c: line_follower_object.move_robot(twist_object) rate.sleep() if __name__ == '__main__': main()
31.456522
95
0.62716
import rospy import cv2 from cv_bridge import CvBridge, CvBridgeError from geometry_msgs.msg import Twist from sensor_msgs.msg import Image class LineFollower(object): def __init__(self): self.bridge_object = CvBridge() self.cmd_vel_pub = rospy.Publisher('/cmd_vel', Twist, queue_size=10) self.cmd_vel_subs = rospy.Subscriber('/cmd_vel', Twist, self.cmdvel_callback) self.last_cmdvel_command = Twist() self._cmdvel_pub_rate = rospy.Rate(10) self.image_sub = rospy.Subscriber("/camera/rgb/image_raw",Image,self.camera_callback) def cmdvel_callback(self,msg): self.last_cmdvel_command = msg def compare_twist_commands(self,twist1,twist2): LX = twist1.linear.x == twist2.linear.x LY = twist1.linear.y == twist2.linear.y LZ = twist1.linear.z == twist2.linear.z AX = twist1.angular.x == twist2.angular.x AY = twist1.angular.y == twist2.angular.y AZ = twist1.angular.z == twist2.angular.z equal = LX and LY and LZ and AX and AY and AZ if not equal: rospy.logwarn("The Current Twist is not the same as the one sent, Resending") return equal def camera_callback(self,data): try: cv_image = self.bridge_object.imgmsg_to_cv2(data, desired_encoding="bgr8") except CvBridgeError as e: print(e) cv2.imshow("Image window", cv_image) cv2.waitKey(1) def move_robot(self, twist_object): current_equal_to_new = False while (not (current_equal_to_new) ): self.cmd_vel_pub.publish(twist_object) self._cmdvel_pub_rate.sleep() current_equal_to_new = self.compare_twist_commands(twist1=self.last_cmdvel_command, twist2=twist_object) def clean_class(self): twist_object = Twist() twist_object.angular.z = 0.0 self.move_robot(twist_object) def main(): rospy.init_node('line_following_node', anonymous=True) line_follower_object = LineFollower() twist_object = Twist() twist_object.angular.z = 0.5 rate = rospy.Rate(5) ctrl_c = False def shutdownhook(): line_follower_object.clean_class() cv2.destroyAllWindows() rospy.loginfo("shutdown time!") ctrl_c = True rospy.on_shutdown(shutdownhook) while not ctrl_c: line_follower_object.move_robot(twist_object) rate.sleep() if __name__ == '__main__': main()
true
true
f72cd747e6808eabbbc492f7c29daeb23eb42ad6
1,816
py
Python
core/urls.py
saksham1991999/upscbasicfunda
b17e288081cb4ca9dd79d198cd0b22136c0794bb
[ "MIT" ]
null
null
null
core/urls.py
saksham1991999/upscbasicfunda
b17e288081cb4ca9dd79d198cd0b22136c0794bb
[ "MIT" ]
7
2021-04-08T21:17:18.000Z
2022-01-13T03:39:23.000Z
core/urls.py
saksham1991999/upscbasicfunda
b17e288081cb4ca9dd79d198cd0b22136c0794bb
[ "MIT" ]
null
null
null
from rest_framework.routers import DefaultRouter from . import views from django.urls import path, re_path app_name = 'core' urlpatterns = [ path("search/", views.SearchSubscriptionsView.as_view()), path("general-notification/",views.Notification.as_view()), path("personal-notification/",views.PersonalNotification.as_view()), path("promo-code/",views.PromocodeAPI.as_view()), path("promo-code-view/",views.PromoCodeViewAPI.as_view()), path("testing-mail/",views.DemoAPI.as_view()), ] router = DefaultRouter() router.register('users', views.UserViewSet, basename='users') router.register('team-members', views.TeamMemberViewSet, basename='team-members') router.register('team-form', views.TeamFormViewSet, basename='team-form') router.register('contact-us', views.ContactUsViewSet, basename='contactus') router.register('feedbacks', views.FeedbackViewSet, basename='feedback') router.register('faqs', views.FAQViewSet, basename='faqs') router.register('articles', views.ArticleViewSet, basename='articles') router.register('news', views.NewsViewSet, basename='news') router.register('newsletter', views.NewsletterViewSet, basename='newsletter') #router.register('General Notifications', views.Notification, basename='general-notification') router.register('categories', views.CategoryViewSet, basename='category') router.register('sub-categories', views.SubCategoryViewSet, basename='sub-category') router.register('pdfs', views.PDFSerializer, basename='pdf') router.register('mcqs', views.MCQSerializer, basename='mcq') router.register('summaries', views.SummarySerializer, basename='summary') router.register('sessions', views.SessionSerializer, basename='session') router.register('user-subscriptions', views.UserSubscriptionsSerializer, basename='user-subscription') urlpatterns += router.urls
42.232558
102
0.786344
from rest_framework.routers import DefaultRouter from . import views from django.urls import path, re_path app_name = 'core' urlpatterns = [ path("search/", views.SearchSubscriptionsView.as_view()), path("general-notification/",views.Notification.as_view()), path("personal-notification/",views.PersonalNotification.as_view()), path("promo-code/",views.PromocodeAPI.as_view()), path("promo-code-view/",views.PromoCodeViewAPI.as_view()), path("testing-mail/",views.DemoAPI.as_view()), ] router = DefaultRouter() router.register('users', views.UserViewSet, basename='users') router.register('team-members', views.TeamMemberViewSet, basename='team-members') router.register('team-form', views.TeamFormViewSet, basename='team-form') router.register('contact-us', views.ContactUsViewSet, basename='contactus') router.register('feedbacks', views.FeedbackViewSet, basename='feedback') router.register('faqs', views.FAQViewSet, basename='faqs') router.register('articles', views.ArticleViewSet, basename='articles') router.register('news', views.NewsViewSet, basename='news') router.register('newsletter', views.NewsletterViewSet, basename='newsletter') router.register('categories', views.CategoryViewSet, basename='category') router.register('sub-categories', views.SubCategoryViewSet, basename='sub-category') router.register('pdfs', views.PDFSerializer, basename='pdf') router.register('mcqs', views.MCQSerializer, basename='mcq') router.register('summaries', views.SummarySerializer, basename='summary') router.register('sessions', views.SessionSerializer, basename='session') router.register('user-subscriptions', views.UserSubscriptionsSerializer, basename='user-subscription') urlpatterns += router.urls
true
true
f72cd77e800a0e0719a55ec6af8ef51dcd7cbf46
3,591
py
Python
src/classes/item.py
kevin3/cwl-ica
cf706ea42993d563f364c0847ee4b882f8fe067c
[ "MIT" ]
8
2021-12-08T05:33:58.000Z
2022-03-07T00:40:48.000Z
src/classes/item.py
kevin3/cwl-ica
cf706ea42993d563f364c0847ee4b882f8fe067c
[ "MIT" ]
34
2021-08-11T03:59:33.000Z
2022-03-10T05:39:26.000Z
src/classes/item.py
kevin3/cwl-ica
cf706ea42993d563f364c0847ee4b882f8fe067c
[ "MIT" ]
1
2022-01-08T07:34:55.000Z
2022-01-08T07:34:55.000Z
#!/usr/bin/env python3 """ Item is a terrible name. I whole-heartedly acknowledge this and apologise for any future maintainer. In this context item represents an element under 'workflow' in workflow.yaml, 'tool' in tool.yaml and so on. An item itself does not contain much information. Just a name, a path (this will just be the name relative to the tool root anyway) and the categories associated with any of the subsequent versions of this tool / workflow. Categories are only relevant for tools and workflows. """ from utils.logging import get_logger from ruamel.yaml.comments import CommentedMap as OrderedDict from pathlib import Path from classes.item_version import ItemVersion from utils.errors import ItemCreationError, ItemDirectoryNotFoundError logger = get_logger() class Item: """ Only subclasses are actually used. These comprise ItemTool, ItemWorkflow, ItemExpression... Item represents an element under workflow.yaml or tool.yaml etc. """ def __init__(self, name, path, root_dir=None, versions=None, categories=None): # Initialise name self.name = name self.path = path self.root_dir = root_dir # Get versions (these will be of a type that is a subclass of ItemVersion) if versions is None: self.versions = [] # Confirm if versions is a list elif len(versions) == 0: self.versions = [] elif isinstance(versions[0], ItemVersion): self.versions = versions elif isinstance(versions[0], dict): self.versions = self.get_versions(versions) else: # Set default self.versions = [] # Get categories self.categories = categories if categories is not None else [] def check_dir(self): """ Check that the directory exists for this 'item' class :param root_dir: :return: """ if not self.root_dir / Path(self.name) is not None: logger.error(f"Could not get directory \"{self.root_dir}/{self.name}\"") raise ItemDirectoryNotFoundError def to_dict(self): """ Write an item to a dictionary - redefined in expression and schema class where categories are not defined :return: """ return OrderedDict({ "name": self.name, "path": str(self.path), "versions": [ version.to_dict() if isinstance(version, ItemVersion) else version # Still just a dict for version in self.versions ], "categories": self.categories }) def get_versions(self, versions): """ Implemented in subclass :return: """ raise NotImplementedError @classmethod def from_dict(cls, item_dict): """ Returns an item object from a dictionary :param item_dict: :return: """ # Check the item_dict has the appropriate keys if item_dict.get("name", None) is None: logger.error("\"name\" attribute not found, cannot create item") raise ItemCreationError if item_dict.get("path", None) is None: logger.error("\"path\" attribute not found, cannot create item") raise ItemCreationError # Return the class object return cls(name=item_dict.get("name"), path=item_dict.get("path"), versions=item_dict.get("versions", None), categories=item_dict.get("categories", None))
32.645455
113
0.624617
from utils.logging import get_logger from ruamel.yaml.comments import CommentedMap as OrderedDict from pathlib import Path from classes.item_version import ItemVersion from utils.errors import ItemCreationError, ItemDirectoryNotFoundError logger = get_logger() class Item: def __init__(self, name, path, root_dir=None, versions=None, categories=None): self.name = name self.path = path self.root_dir = root_dir if versions is None: self.versions = [] elif len(versions) == 0: self.versions = [] elif isinstance(versions[0], ItemVersion): self.versions = versions elif isinstance(versions[0], dict): self.versions = self.get_versions(versions) else: self.versions = [] self.categories = categories if categories is not None else [] def check_dir(self): if not self.root_dir / Path(self.name) is not None: logger.error(f"Could not get directory \"{self.root_dir}/{self.name}\"") raise ItemDirectoryNotFoundError def to_dict(self): return OrderedDict({ "name": self.name, "path": str(self.path), "versions": [ version.to_dict() if isinstance(version, ItemVersion) else version for version in self.versions ], "categories": self.categories }) def get_versions(self, versions): raise NotImplementedError @classmethod def from_dict(cls, item_dict): if item_dict.get("name", None) is None: logger.error("\"name\" attribute not found, cannot create item") raise ItemCreationError if item_dict.get("path", None) is None: logger.error("\"path\" attribute not found, cannot create item") raise ItemCreationError return cls(name=item_dict.get("name"), path=item_dict.get("path"), versions=item_dict.get("versions", None), categories=item_dict.get("categories", None))
true
true
f72cd844ec376f6444b3a3f87163523a385a0c9f
23,894
py
Python
lib/FamaProfiling/FamaProfilingServer.py
aekazakov/FamaProfiling
d9db15ea217e3be2aab65c356564a6d345b4f410
[ "MIT" ]
null
null
null
lib/FamaProfiling/FamaProfilingServer.py
aekazakov/FamaProfiling
d9db15ea217e3be2aab65c356564a6d345b4f410
[ "MIT" ]
null
null
null
lib/FamaProfiling/FamaProfilingServer.py
aekazakov/FamaProfiling
d9db15ea217e3be2aab65c356564a6d345b4f410
[ "MIT" ]
null
null
null
#!/usr/bin/env python # -*- coding: utf-8 -*- import datetime import json import os import random as _random import sys import traceback from getopt import getopt, GetoptError from multiprocessing import Process from os import environ from wsgiref.simple_server import make_server import requests as _requests from jsonrpcbase import JSONRPCService, InvalidParamsError, KeywordError, \ JSONRPCError, InvalidRequestError from jsonrpcbase import ServerError as JSONServerError from biokbase import log from authclient import KBaseAuth as _KBaseAuth try: from ConfigParser import ConfigParser except ImportError: from configparser import ConfigParser DEPLOY = 'KB_DEPLOYMENT_CONFIG' SERVICE = 'KB_SERVICE_NAME' AUTH = 'auth-service-url' # Note that the error fields do not match the 2.0 JSONRPC spec def get_config_file(): return environ.get(DEPLOY, None) def get_service_name(): return environ.get(SERVICE, None) def get_config(): if not get_config_file(): return None retconfig = {} config = ConfigParser() config.read(get_config_file()) for nameval in config.items(get_service_name() or 'FamaProfiling'): retconfig[nameval[0]] = nameval[1] return retconfig config = get_config() from FamaProfilingImpl import FamaProfiling # noqa @IgnorePep8 impl_FamaProfiling = FamaProfiling(config) class JSONObjectEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, set): return list(obj) if isinstance(obj, frozenset): return list(obj) if hasattr(obj, 'toJSONable'): return obj.toJSONable() return json.JSONEncoder.default(self, obj) class JSONRPCServiceCustom(JSONRPCService): def call(self, ctx, jsondata): """ Calls jsonrpc service's method and returns its return value in a JSON string or None if there is none. Arguments: jsondata -- remote method call in jsonrpc format """ result = self.call_py(ctx, jsondata) if result is not None: return json.dumps(result, cls=JSONObjectEncoder) return None def _call_method(self, ctx, request): """Calls given method with given params and returns it value.""" method = self.method_data[request['method']]['method'] params = request['params'] result = None try: if isinstance(params, list): # Does it have enough arguments? if len(params) < self._man_args(method) - 1: raise InvalidParamsError('not enough arguments') # Does it have too many arguments? if(not self._vargs(method) and len(params) > self._max_args(method) - 1): raise InvalidParamsError('too many arguments') result = method(ctx, *params) elif isinstance(params, dict): # Do not accept keyword arguments if the jsonrpc version is # not >=1.1. if request['jsonrpc'] < 11: raise KeywordError result = method(ctx, **params) else: # No params result = method(ctx) except JSONRPCError: raise except Exception as e: # log.exception('method %s threw an exception' % request['method']) # Exception was raised inside the method. newerr = JSONServerError() newerr.trace = traceback.format_exc() if len(e.args) == 1: newerr.data = repr(e.args[0]) else: newerr.data = repr(e.args) raise newerr return result def call_py(self, ctx, jsondata): """ Calls jsonrpc service's method and returns its return value in python object format or None if there is none. This method is same as call() except the return value is a python object instead of JSON string. This method is mainly only useful for debugging purposes. """ rdata = jsondata # we already deserialize the json string earlier in the server code, no # need to do it again # try: # rdata = json.loads(jsondata) # except ValueError: # raise ParseError # set some default values for error handling request = self._get_default_vals() if isinstance(rdata, dict) and rdata: # It's a single request. self._fill_request(request, rdata) respond = self._handle_request(ctx, request) # Don't respond to notifications if respond is None: return None return respond elif isinstance(rdata, list) and rdata: # It's a batch. requests = [] responds = [] for rdata_ in rdata: # set some default values for error handling request_ = self._get_default_vals() self._fill_request(request_, rdata_) requests.append(request_) for request_ in requests: respond = self._handle_request(ctx, request_) # Don't respond to notifications if respond is not None: responds.append(respond) if responds: return responds # Nothing to respond. return None else: # empty dict, list or wrong type raise InvalidRequestError def _handle_request(self, ctx, request): """Handles given request and returns its response.""" if 'types' in self.method_data[request['method']]: self._validate_params_types(request['method'], request['params']) result = self._call_method(ctx, request) # Do not respond to notifications. if request['id'] is None: return None respond = {} self._fill_ver(request['jsonrpc'], respond) respond['result'] = result respond['id'] = request['id'] return respond class MethodContext(dict): def __init__(self, logger): self['client_ip'] = None self['user_id'] = None self['authenticated'] = None self['token'] = None self['module'] = None self['method'] = None self['call_id'] = None self['rpc_context'] = None self['provenance'] = None self._debug_levels = set([7, 8, 9, 'DEBUG', 'DEBUG2', 'DEBUG3']) self._logger = logger def log_err(self, message): self._log(log.ERR, message) def log_info(self, message): self._log(log.INFO, message) def log_debug(self, message, level=1): if level in self._debug_levels: pass else: level = int(level) if level < 1 or level > 3: raise ValueError("Illegal log level: " + str(level)) level = level + 6 self._log(level, message) def set_log_level(self, level): self._logger.set_log_level(level) def get_log_level(self): return self._logger.get_log_level() def clear_log_level(self): self._logger.clear_user_log_level() def _log(self, level, message): self._logger.log_message(level, message, self['client_ip'], self['user_id'], self['module'], self['method'], self['call_id']) def provenance(self): callbackURL = os.environ.get('SDK_CALLBACK_URL') if callbackURL: # OK, there's a callback server from which we can get provenance arg_hash = {'method': 'CallbackServer.get_provenance', 'params': [], 'version': '1.1', 'id': str(_random.random())[2:] } body = json.dumps(arg_hash) response = _requests.post(callbackURL, data=body, timeout=60) response.encoding = 'utf-8' if response.status_code == 500: if ('content-type' in response.headers and response.headers['content-type'] == 'application/json'): err = response.json() if 'error' in err: raise ServerError(**err['error']) else: raise ServerError('Unknown', 0, response.text) else: raise ServerError('Unknown', 0, response.text) if not response.ok: response.raise_for_status() resp = response.json() if 'result' not in resp: raise ServerError('Unknown', 0, 'An unknown server error occurred') return resp['result'][0] else: return self.get('provenance') class ServerError(Exception): ''' The call returned an error. Fields: name - the name of the error. code - the error code. message - a human readable error message. data - the server side stacktrace. ''' def __init__(self, name, code, message, data=None, error=None): super(Exception, self).__init__(message) self.name = name self.code = code self.message = message if message else '' self.data = data or error or '' # data = JSON RPC 2.0, error = 1.1 def __str__(self): return self.name + ': ' + str(self.code) + '. ' + self.message + \ '\n' + self.data def getIPAddress(environ): xFF = environ.get('HTTP_X_FORWARDED_FOR') realIP = environ.get('HTTP_X_REAL_IP') trustXHeaders = config is None or \ config.get('dont_trust_x_ip_headers') != 'true' if (trustXHeaders): if (xFF): return xFF.split(',')[0].strip() if (realIP): return realIP.strip() return environ.get('REMOTE_ADDR') class Application(object): # Wrap the wsgi handler in a class definition so that we can # do some initialization and avoid regenerating stuff over # and over def logcallback(self): self.serverlog.set_log_file(self.userlog.get_log_file()) def log(self, level, context, message): self.serverlog.log_message(level, message, context['client_ip'], context['user_id'], context['module'], context['method'], context['call_id']) def __init__(self): submod = get_service_name() or 'FamaProfiling' self.userlog = log.log( submod, ip_address=True, authuser=True, module=True, method=True, call_id=True, changecallback=self.logcallback, config=get_config_file()) self.serverlog = log.log( submod, ip_address=True, authuser=True, module=True, method=True, call_id=True, logfile=self.userlog.get_log_file()) self.serverlog.set_log_level(6) self.rpc_service = JSONRPCServiceCustom() self.method_authentication = dict() self.rpc_service.add(impl_FamaProfiling.run_FamaReadProfiling, name='FamaProfiling.run_FamaReadProfiling', types=[dict]) self.method_authentication['FamaProfiling.run_FamaReadProfiling'] = 'required' # noqa self.rpc_service.add(impl_FamaProfiling.run_FamaGenomeProfiling, name='FamaProfiling.run_FamaGenomeProfiling', types=[dict]) self.method_authentication['FamaProfiling.run_FamaGenomeProfiling'] = 'required' # noqa self.rpc_service.add(impl_FamaProfiling.view_FamaFunctionalProfile, name='FamaProfiling.view_FamaFunctionalProfile', types=[dict]) self.method_authentication['FamaProfiling.view_FamaFunctionalProfile'] = 'required' # noqa self.rpc_service.add(impl_FamaProfiling.status, name='FamaProfiling.status', types=[dict]) authurl = config.get(AUTH) if config else None self.auth_client = _KBaseAuth(authurl) def __call__(self, environ, start_response): # Context object, equivalent to the perl impl CallContext ctx = MethodContext(self.userlog) ctx['client_ip'] = getIPAddress(environ) status = '500 Internal Server Error' try: body_size = int(environ.get('CONTENT_LENGTH', 0)) except (ValueError): body_size = 0 if environ['REQUEST_METHOD'] == 'OPTIONS': # we basically do nothing and just return headers status = '200 OK' rpc_result = "" else: request_body = environ['wsgi.input'].read(body_size) try: req = json.loads(request_body) except ValueError as ve: err = {'error': {'code': -32700, 'name': "Parse error", 'message': str(ve), } } rpc_result = self.process_error(err, ctx, {'version': '1.1'}) else: ctx['module'], ctx['method'] = req['method'].split('.') ctx['call_id'] = req['id'] ctx['rpc_context'] = { 'call_stack': [{'time': self.now_in_utc(), 'method': req['method']} ] } prov_action = {'service': ctx['module'], 'method': ctx['method'], 'method_params': req['params'] } ctx['provenance'] = [prov_action] try: token = environ.get('HTTP_AUTHORIZATION') # parse out the method being requested and check if it # has an authentication requirement method_name = req['method'] auth_req = self.method_authentication.get( method_name, 'none') if auth_req != 'none': if token is None and auth_req == 'required': err = JSONServerError() err.data = ( 'Authentication required for ' + 'FamaProfiling ' + 'but no authentication header was passed') raise err elif token is None and auth_req == 'optional': pass else: try: user = self.auth_client.get_user(token) ctx['user_id'] = user ctx['authenticated'] = 1 ctx['token'] = token except Exception as e: if auth_req == 'required': err = JSONServerError() err.data = \ "Token validation failed: %s" % e raise err if (environ.get('HTTP_X_FORWARDED_FOR')): self.log(log.INFO, ctx, 'X-Forwarded-For: ' + environ.get('HTTP_X_FORWARDED_FOR')) self.log(log.INFO, ctx, 'start method') rpc_result = self.rpc_service.call(ctx, req) self.log(log.INFO, ctx, 'end method') status = '200 OK' except JSONRPCError as jre: err = {'error': {'code': jre.code, 'name': jre.message, 'message': jre.data } } trace = jre.trace if hasattr(jre, 'trace') else None rpc_result = self.process_error(err, ctx, req, trace) except Exception: err = {'error': {'code': 0, 'name': 'Unexpected Server Error', 'message': 'An unexpected server error ' + 'occurred', } } rpc_result = self.process_error(err, ctx, req, traceback.format_exc()) # print('Request method was %s\n' % environ['REQUEST_METHOD']) # print('Environment dictionary is:\n%s\n' % pprint.pformat(environ)) # print('Request body was: %s' % request_body) # print('Result from the method call is:\n%s\n' % \ # pprint.pformat(rpc_result)) if rpc_result: response_body = rpc_result else: response_body = '' response_headers = [ ('Access-Control-Allow-Origin', '*'), ('Access-Control-Allow-Headers', environ.get( 'HTTP_ACCESS_CONTROL_REQUEST_HEADERS', 'authorization')), ('content-type', 'application/json'), ('content-length', str(len(response_body)))] start_response(status, response_headers) return [response_body.encode('utf8')] def process_error(self, error, context, request, trace=None): if trace: self.log(log.ERR, context, trace.split('\n')[0:-1]) if 'id' in request: error['id'] = request['id'] if 'version' in request: error['version'] = request['version'] e = error['error'].get('error') if not e: error['error']['error'] = trace elif 'jsonrpc' in request: error['jsonrpc'] = request['jsonrpc'] error['error']['data'] = trace else: error['version'] = '1.0' error['error']['error'] = trace return json.dumps(error) def now_in_utc(self): # noqa Taken from http://stackoverflow.com/questions/3401428/how-to-get-an-isoformat-datetime-string-including-the-default-timezone @IgnorePep8 dtnow = datetime.datetime.now() dtutcnow = datetime.datetime.utcnow() delta = dtnow - dtutcnow hh, mm = divmod((delta.days * 24 * 60 * 60 + delta.seconds + 30) // 60, 60) return "%s%+02d:%02d" % (dtnow.isoformat(), hh, mm) application = Application() # This is the uwsgi application dictionary. On startup uwsgi will look # for this dict and pull its configuration from here. # This simply lists where to "mount" the application in the URL path # # This uwsgi module "magically" appears when running the app within # uwsgi and is not available otherwise, so wrap an exception handler # around it # # To run this server in uwsgi with 4 workers listening on port 9999 use: # uwsgi -M -p 4 --http :9999 --wsgi-file _this_file_ # To run a using the single threaded python BaseHTTP service # listening on port 9999 by default execute this file # try: import uwsgi # Before we do anything with the application, see if the # configs specify patching all std routines to be asynch # *ONLY* use this if you are going to wrap the service in # a wsgi container that has enabled gevent, such as # uwsgi with the --gevent option if config is not None and config.get('gevent_monkeypatch_all', False): print("Monkeypatching std libraries for async") from gevent import monkey monkey.patch_all() uwsgi.applications = {'': application} except ImportError: # Not available outside of wsgi, ignore pass _proc = None def start_server(host='localhost', port=0, newprocess=False): ''' By default, will start the server on localhost on a system assigned port in the main thread. Excecution of the main thread will stay in the server main loop until interrupted. To run the server in a separate process, and thus allow the stop_server method to be called, set newprocess = True. This will also allow returning of the port number.''' global _proc if _proc: raise RuntimeError('server is already running') httpd = make_server(host, port, application) port = httpd.server_address[1] print("Listening on port %s" % port) if newprocess: _proc = Process(target=httpd.serve_forever) _proc.daemon = True _proc.start() else: httpd.serve_forever() return port def stop_server(): global _proc _proc.terminate() _proc = None def process_async_cli(input_file_path, output_file_path, token): exit_code = 0 with open(input_file_path) as data_file: req = json.load(data_file) if 'version' not in req: req['version'] = '1.1' if 'id' not in req: req['id'] = str(_random.random())[2:] ctx = MethodContext(application.userlog) if token: user = application.auth_client.get_user(token) ctx['user_id'] = user ctx['authenticated'] = 1 ctx['token'] = token if 'context' in req: ctx['rpc_context'] = req['context'] ctx['CLI'] = 1 ctx['module'], ctx['method'] = req['method'].split('.') prov_action = {'service': ctx['module'], 'method': ctx['method'], 'method_params': req['params']} ctx['provenance'] = [prov_action] resp = None try: resp = application.rpc_service.call_py(ctx, req) except JSONRPCError as jre: trace = jre.trace if hasattr(jre, 'trace') else None resp = {'id': req['id'], 'version': req['version'], 'error': {'code': jre.code, 'name': jre.message, 'message': jre.data, 'error': trace} } except Exception: trace = traceback.format_exc() resp = {'id': req['id'], 'version': req['version'], 'error': {'code': 0, 'name': 'Unexpected Server Error', 'message': 'An unexpected server error occurred', 'error': trace} } if 'error' in resp: exit_code = 500 with open(output_file_path, "w") as f: f.write(json.dumps(resp, cls=JSONObjectEncoder)) return exit_code if __name__ == "__main__": if (len(sys.argv) >= 3 and len(sys.argv) <= 4 and os.path.isfile(sys.argv[1])): token = None if len(sys.argv) == 4: if os.path.isfile(sys.argv[3]): with open(sys.argv[3]) as token_file: token = token_file.read() else: token = sys.argv[3] sys.exit(process_async_cli(sys.argv[1], sys.argv[2], token)) try: opts, args = getopt(sys.argv[1:], "", ["port=", "host="]) except GetoptError as err: # print help information and exit: print(str(err)) # will print something like "option -a not recognized" sys.exit(2) port = 9999 host = 'localhost' for o, a in opts: if o == '--port': port = int(a) elif o == '--host': host = a print("Host set to %s" % host) else: assert False, "unhandled option" start_server(host=host, port=port) # print("Listening on port %s" % port) # httpd = make_server( host, port, application) # # httpd.serve_forever()
37.044961
151
0.545451
import datetime import json import os import random as _random import sys import traceback from getopt import getopt, GetoptError from multiprocessing import Process from os import environ from wsgiref.simple_server import make_server import requests as _requests from jsonrpcbase import JSONRPCService, InvalidParamsError, KeywordError, \ JSONRPCError, InvalidRequestError from jsonrpcbase import ServerError as JSONServerError from biokbase import log from authclient import KBaseAuth as _KBaseAuth try: from ConfigParser import ConfigParser except ImportError: from configparser import ConfigParser DEPLOY = 'KB_DEPLOYMENT_CONFIG' SERVICE = 'KB_SERVICE_NAME' AUTH = 'auth-service-url' def get_config_file(): return environ.get(DEPLOY, None) def get_service_name(): return environ.get(SERVICE, None) def get_config(): if not get_config_file(): return None retconfig = {} config = ConfigParser() config.read(get_config_file()) for nameval in config.items(get_service_name() or 'FamaProfiling'): retconfig[nameval[0]] = nameval[1] return retconfig config = get_config() from FamaProfilingImpl import FamaProfiling impl_FamaProfiling = FamaProfiling(config) class JSONObjectEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, set): return list(obj) if isinstance(obj, frozenset): return list(obj) if hasattr(obj, 'toJSONable'): return obj.toJSONable() return json.JSONEncoder.default(self, obj) class JSONRPCServiceCustom(JSONRPCService): def call(self, ctx, jsondata): result = self.call_py(ctx, jsondata) if result is not None: return json.dumps(result, cls=JSONObjectEncoder) return None def _call_method(self, ctx, request): method = self.method_data[request['method']]['method'] params = request['params'] result = None try: if isinstance(params, list): if len(params) < self._man_args(method) - 1: raise InvalidParamsError('not enough arguments') if(not self._vargs(method) and len(params) > self._max_args(method) - 1): raise InvalidParamsError('too many arguments') result = method(ctx, *params) elif isinstance(params, dict): if request['jsonrpc'] < 11: raise KeywordError result = method(ctx, **params) else: result = method(ctx) except JSONRPCError: raise except Exception as e: newerr = JSONServerError() newerr.trace = traceback.format_exc() if len(e.args) == 1: newerr.data = repr(e.args[0]) else: newerr.data = repr(e.args) raise newerr return result def call_py(self, ctx, jsondata): rdata = jsondata request = self._get_default_vals() if isinstance(rdata, dict) and rdata: self._fill_request(request, rdata) respond = self._handle_request(ctx, request) # Don't respond to notifications if respond is None: return None return respond elif isinstance(rdata, list) and rdata: requests = [] responds = [] for rdata_ in rdata: # set some default values for error handling request_ = self._get_default_vals() self._fill_request(request_, rdata_) requests.append(request_) for request_ in requests: respond = self._handle_request(ctx, request_) # Don't respond to notifications if respond is not None: responds.append(respond) if responds: return responds return None else: raise InvalidRequestError def _handle_request(self, ctx, request): if 'types' in self.method_data[request['method']]: self._validate_params_types(request['method'], request['params']) result = self._call_method(ctx, request) if request['id'] is None: return None respond = {} self._fill_ver(request['jsonrpc'], respond) respond['result'] = result respond['id'] = request['id'] return respond class MethodContext(dict): def __init__(self, logger): self['client_ip'] = None self['user_id'] = None self['authenticated'] = None self['token'] = None self['module'] = None self['method'] = None self['call_id'] = None self['rpc_context'] = None self['provenance'] = None self._debug_levels = set([7, 8, 9, 'DEBUG', 'DEBUG2', 'DEBUG3']) self._logger = logger def log_err(self, message): self._log(log.ERR, message) def log_info(self, message): self._log(log.INFO, message) def log_debug(self, message, level=1): if level in self._debug_levels: pass else: level = int(level) if level < 1 or level > 3: raise ValueError("Illegal log level: " + str(level)) level = level + 6 self._log(level, message) def set_log_level(self, level): self._logger.set_log_level(level) def get_log_level(self): return self._logger.get_log_level() def clear_log_level(self): self._logger.clear_user_log_level() def _log(self, level, message): self._logger.log_message(level, message, self['client_ip'], self['user_id'], self['module'], self['method'], self['call_id']) def provenance(self): callbackURL = os.environ.get('SDK_CALLBACK_URL') if callbackURL: arg_hash = {'method': 'CallbackServer.get_provenance', 'params': [], 'version': '1.1', 'id': str(_random.random())[2:] } body = json.dumps(arg_hash) response = _requests.post(callbackURL, data=body, timeout=60) response.encoding = 'utf-8' if response.status_code == 500: if ('content-type' in response.headers and response.headers['content-type'] == 'application/json'): err = response.json() if 'error' in err: raise ServerError(**err['error']) else: raise ServerError('Unknown', 0, response.text) else: raise ServerError('Unknown', 0, response.text) if not response.ok: response.raise_for_status() resp = response.json() if 'result' not in resp: raise ServerError('Unknown', 0, 'An unknown server error occurred') return resp['result'][0] else: return self.get('provenance') class ServerError(Exception): def __init__(self, name, code, message, data=None, error=None): super(Exception, self).__init__(message) self.name = name self.code = code self.message = message if message else '' self.data = data or error or '' # data = JSON RPC 2.0, error = 1.1 def __str__(self): return self.name + ': ' + str(self.code) + '. ' + self.message + \ '\n' + self.data def getIPAddress(environ): xFF = environ.get('HTTP_X_FORWARDED_FOR') realIP = environ.get('HTTP_X_REAL_IP') trustXHeaders = config is None or \ config.get('dont_trust_x_ip_headers') != 'true' if (trustXHeaders): if (xFF): return xFF.split(',')[0].strip() if (realIP): return realIP.strip() return environ.get('REMOTE_ADDR') class Application(object): # Wrap the wsgi handler in a class definition so that we can # do some initialization and avoid regenerating stuff over # and over def logcallback(self): self.serverlog.set_log_file(self.userlog.get_log_file()) def log(self, level, context, message): self.serverlog.log_message(level, message, context['client_ip'], context['user_id'], context['module'], context['method'], context['call_id']) def __init__(self): submod = get_service_name() or 'FamaProfiling' self.userlog = log.log( submod, ip_address=True, authuser=True, module=True, method=True, call_id=True, changecallback=self.logcallback, config=get_config_file()) self.serverlog = log.log( submod, ip_address=True, authuser=True, module=True, method=True, call_id=True, logfile=self.userlog.get_log_file()) self.serverlog.set_log_level(6) self.rpc_service = JSONRPCServiceCustom() self.method_authentication = dict() self.rpc_service.add(impl_FamaProfiling.run_FamaReadProfiling, name='FamaProfiling.run_FamaReadProfiling', types=[dict]) self.method_authentication['FamaProfiling.run_FamaReadProfiling'] = 'required' # noqa self.rpc_service.add(impl_FamaProfiling.run_FamaGenomeProfiling, name='FamaProfiling.run_FamaGenomeProfiling', types=[dict]) self.method_authentication['FamaProfiling.run_FamaGenomeProfiling'] = 'required' # noqa self.rpc_service.add(impl_FamaProfiling.view_FamaFunctionalProfile, name='FamaProfiling.view_FamaFunctionalProfile', types=[dict]) self.method_authentication['FamaProfiling.view_FamaFunctionalProfile'] = 'required' # noqa self.rpc_service.add(impl_FamaProfiling.status, name='FamaProfiling.status', types=[dict]) authurl = config.get(AUTH) if config else None self.auth_client = _KBaseAuth(authurl) def __call__(self, environ, start_response): # Context object, equivalent to the perl impl CallContext ctx = MethodContext(self.userlog) ctx['client_ip'] = getIPAddress(environ) status = '500 Internal Server Error' try: body_size = int(environ.get('CONTENT_LENGTH', 0)) except (ValueError): body_size = 0 if environ['REQUEST_METHOD'] == 'OPTIONS': # we basically do nothing and just return headers status = '200 OK' rpc_result = "" else: request_body = environ['wsgi.input'].read(body_size) try: req = json.loads(request_body) except ValueError as ve: err = {'error': {'code': -32700, 'name': "Parse error", 'message': str(ve), } } rpc_result = self.process_error(err, ctx, {'version': '1.1'}) else: ctx['module'], ctx['method'] = req['method'].split('.') ctx['call_id'] = req['id'] ctx['rpc_context'] = { 'call_stack': [{'time': self.now_in_utc(), 'method': req['method']} ] } prov_action = {'service': ctx['module'], 'method': ctx['method'], 'method_params': req['params'] } ctx['provenance'] = [prov_action] try: token = environ.get('HTTP_AUTHORIZATION') # parse out the method being requested and check if it # has an authentication requirement method_name = req['method'] auth_req = self.method_authentication.get( method_name, 'none') if auth_req != 'none': if token is None and auth_req == 'required': err = JSONServerError() err.data = ( 'Authentication required for ' + 'FamaProfiling ' + 'but no authentication header was passed') raise err elif token is None and auth_req == 'optional': pass else: try: user = self.auth_client.get_user(token) ctx['user_id'] = user ctx['authenticated'] = 1 ctx['token'] = token except Exception as e: if auth_req == 'required': err = JSONServerError() err.data = \ "Token validation failed: %s" % e raise err if (environ.get('HTTP_X_FORWARDED_FOR')): self.log(log.INFO, ctx, 'X-Forwarded-For: ' + environ.get('HTTP_X_FORWARDED_FOR')) self.log(log.INFO, ctx, 'start method') rpc_result = self.rpc_service.call(ctx, req) self.log(log.INFO, ctx, 'end method') status = '200 OK' except JSONRPCError as jre: err = {'error': {'code': jre.code, 'name': jre.message, 'message': jre.data } } trace = jre.trace if hasattr(jre, 'trace') else None rpc_result = self.process_error(err, ctx, req, trace) except Exception: err = {'error': {'code': 0, 'name': 'Unexpected Server Error', 'message': 'An unexpected server error ' + 'occurred', } } rpc_result = self.process_error(err, ctx, req, traceback.format_exc()) # print('Request method was %s\n' % environ['REQUEST_METHOD']) # print('Environment dictionary is:\n%s\n' % pprint.pformat(environ)) # print('Request body was: %s' % request_body) # print('Result from the method call is:\n%s\n' % \ # pprint.pformat(rpc_result)) if rpc_result: response_body = rpc_result else: response_body = '' response_headers = [ ('Access-Control-Allow-Origin', '*'), ('Access-Control-Allow-Headers', environ.get( 'HTTP_ACCESS_CONTROL_REQUEST_HEADERS', 'authorization')), ('content-type', 'application/json'), ('content-length', str(len(response_body)))] start_response(status, response_headers) return [response_body.encode('utf8')] def process_error(self, error, context, request, trace=None): if trace: self.log(log.ERR, context, trace.split('\n')[0:-1]) if 'id' in request: error['id'] = request['id'] if 'version' in request: error['version'] = request['version'] e = error['error'].get('error') if not e: error['error']['error'] = trace elif 'jsonrpc' in request: error['jsonrpc'] = request['jsonrpc'] error['error']['data'] = trace else: error['version'] = '1.0' error['error']['error'] = trace return json.dumps(error) def now_in_utc(self): # noqa Taken from http://stackoverflow.com/questions/3401428/how-to-get-an-isoformat-datetime-string-including-the-default-timezone @IgnorePep8 dtnow = datetime.datetime.now() dtutcnow = datetime.datetime.utcnow() delta = dtnow - dtutcnow hh, mm = divmod((delta.days * 24 * 60 * 60 + delta.seconds + 30) // 60, 60) return "%s%+02d:%02d" % (dtnow.isoformat(), hh, mm) application = Application() # This is the uwsgi application dictionary. On startup uwsgi will look # for this dict and pull its configuration from here. # This simply lists where to "mount" the application in the URL path # # This uwsgi module "magically" appears when running the app within # uwsgi and is not available otherwise, so wrap an exception handler # around it # # To run this server in uwsgi with 4 workers listening on port 9999 use: # uwsgi -M -p 4 --http :9999 --wsgi-file _this_file_ # To run a using the single threaded python BaseHTTP service # listening on port 9999 by default execute this file # try: import uwsgi # Before we do anything with the application, see if the # configs specify patching all std routines to be asynch # *ONLY* use this if you are going to wrap the service in # a wsgi container that has enabled gevent, such as # uwsgi with the --gevent option if config is not None and config.get('gevent_monkeypatch_all', False): print("Monkeypatching std libraries for async") from gevent import monkey monkey.patch_all() uwsgi.applications = {'': application} except ImportError: # Not available outside of wsgi, ignore pass _proc = None def start_server(host='localhost', port=0, newprocess=False): global _proc if _proc: raise RuntimeError('server is already running') httpd = make_server(host, port, application) port = httpd.server_address[1] print("Listening on port %s" % port) if newprocess: _proc = Process(target=httpd.serve_forever) _proc.daemon = True _proc.start() else: httpd.serve_forever() return port def stop_server(): global _proc _proc.terminate() _proc = None def process_async_cli(input_file_path, output_file_path, token): exit_code = 0 with open(input_file_path) as data_file: req = json.load(data_file) if 'version' not in req: req['version'] = '1.1' if 'id' not in req: req['id'] = str(_random.random())[2:] ctx = MethodContext(application.userlog) if token: user = application.auth_client.get_user(token) ctx['user_id'] = user ctx['authenticated'] = 1 ctx['token'] = token if 'context' in req: ctx['rpc_context'] = req['context'] ctx['CLI'] = 1 ctx['module'], ctx['method'] = req['method'].split('.') prov_action = {'service': ctx['module'], 'method': ctx['method'], 'method_params': req['params']} ctx['provenance'] = [prov_action] resp = None try: resp = application.rpc_service.call_py(ctx, req) except JSONRPCError as jre: trace = jre.trace if hasattr(jre, 'trace') else None resp = {'id': req['id'], 'version': req['version'], 'error': {'code': jre.code, 'name': jre.message, 'message': jre.data, 'error': trace} } except Exception: trace = traceback.format_exc() resp = {'id': req['id'], 'version': req['version'], 'error': {'code': 0, 'name': 'Unexpected Server Error', 'message': 'An unexpected server error occurred', 'error': trace} } if 'error' in resp: exit_code = 500 with open(output_file_path, "w") as f: f.write(json.dumps(resp, cls=JSONObjectEncoder)) return exit_code if __name__ == "__main__": if (len(sys.argv) >= 3 and len(sys.argv) <= 4 and os.path.isfile(sys.argv[1])): token = None if len(sys.argv) == 4: if os.path.isfile(sys.argv[3]): with open(sys.argv[3]) as token_file: token = token_file.read() else: token = sys.argv[3] sys.exit(process_async_cli(sys.argv[1], sys.argv[2], token)) try: opts, args = getopt(sys.argv[1:], "", ["port=", "host="]) except GetoptError as err: # print help information and exit: print(str(err)) # will print something like "option -a not recognized" sys.exit(2) port = 9999 host = 'localhost' for o, a in opts: if o == '--port': port = int(a) elif o == '--host': host = a print("Host set to %s" % host) else: assert False, "unhandled option" start_server(host=host, port=port) # print("Listening on port %s" % port) # httpd = make_server( host, port, application) # # httpd.serve_forever()
true
true