file_name
stringlengths 3
137
| prefix
stringlengths 0
918k
| suffix
stringlengths 0
962k
| middle
stringlengths 0
812k
|
---|---|---|---|
logger.ts
|
import { NextFunction, Request, Response } from "../utils/server";
export function
|
(req: Request, res: Response, next: NextFunction) {
console.info("template logging");
next();
}
|
logger
|
get_metadata.rs
|
// Copyright 2020 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/// This module tests calls to the get_metadata API.
use {
super::*,
fidl::endpoints::create_proxy,
fidl_fuchsia_io::FileEvent::OnOpen_,
fidl_fuchsia_pkg::{GetMetadataError, RepositoryUrl},
fuchsia_zircon::Status,
futures::channel::oneshot,
matches::assert_matches,
vfs::file::pcb::read_only_static,
};
async fn verify_get_metadata_with_read_success(env: &TestEnv, path: &str, file_contents: &str) {
let (file_proxy, server_end) = create_proxy().unwrap();
let res = env
.local_mirror_proxy()
.get_metadata(&mut RepositoryUrl { url: repo_url().to_string() }, path, server_end)
.await;
assert_eq!(res.unwrap(), Ok(()));
assert_matches!(
file_proxy.take_event_stream().next().await,
Some(Ok(OnOpen_{s, info: Some(_)})) if Status::ok(s) == Ok(())
);
assert_eq!(io_util::read_file(&file_proxy).await.unwrap(), file_contents.to_owned());
}
#[fuchsia::test]
async fn success() {
let env = TestEnv::builder()
.usb_dir(pseudo_directory! {
"0" => pseudo_directory! {
"fuchsia_pkg" => pseudo_directory! {
"blobs" => pseudo_directory! {},
"repository_metadata" => pseudo_directory! {
repo_url().host() => pseudo_directory! {
"1.root.json" => read_only_static("beep"),
"2.root.json" => read_only_static("boop"),
},
},
},
},
})
.build()
.await;
verify_get_metadata_with_read_success(&env, "1.root.json", "beep").await;
verify_get_metadata_with_read_success(&env, "2.root.json", "boop").await;
}
#[fuchsia::test]
async fn success_multiple_path_segments() {
let env = TestEnv::builder()
.usb_dir(pseudo_directory! {
"0" => pseudo_directory! {
"fuchsia_pkg" => pseudo_directory! {
"blobs" => pseudo_directory! {},
"repository_metadata" => pseudo_directory! {
repo_url().host() => pseudo_directory! {
"foo" => pseudo_directory! {
"bar" => pseudo_directory! {
"1.root.json" => read_only_static("beep"),
},
},
"baz" => pseudo_directory! {
"2.root.json" => read_only_static("boop"),
}
},
},
},
},
})
.build()
.await;
verify_get_metadata_with_read_success(&env, "foo/bar/1.root.json", "beep").await;
verify_get_metadata_with_read_success(&env, "baz/2.root.json", "boop").await;
}
async fn verify_get_metadata_with_on_open_failure_status(
env: &TestEnv,
path: &str,
status: Status,
) {
let (file_proxy, server_end) = create_proxy().unwrap();
let res = env
.local_mirror_proxy()
.get_metadata(&mut RepositoryUrl { url: repo_url().to_string() }, path, server_end)
.await;
assert_eq!(res.unwrap(), Ok(()));
assert_matches!(
file_proxy.take_event_stream().next().await,
Some(Ok(OnOpen_{s, info: None})) if Status::from_raw(s) == status
);
assert_matches!(io_util::read_file(&file_proxy).await, Err(_));
}
#[fuchsia::test]
async fn missing_repo_url_directory() {
let env = TestEnv::builder().build().await;
verify_get_metadata_with_on_open_failure_status(&env, "1.root.json", Status::NOT_FOUND).await;
}
#[fuchsia::test]
async fn missing_metadata_file() {
let env = TestEnv::builder()
.usb_dir(pseudo_directory! {
"0" => pseudo_directory! {
"fuchsia_pkg" => pseudo_directory! {
"blobs" => pseudo_directory! {},
"repository_metadata" => pseudo_directory! {
repo_url().host() => pseudo_directory! {
"2.root.json" => read_only_static("boop"),
},
},
},
},
})
.build()
.await;
verify_get_metadata_with_on_open_failure_status(&env, "1.root.json", Status::NOT_FOUND).await;
}
#[fuchsia::test]
async fn error_opening_metadata()
|
{
let (metadata_closed_sender, metadata_closed_recv) = oneshot::channel();
let env = TestEnv::builder()
.usb_dir(pseudo_directory! {
"0" => pseudo_directory! {
"fuchsia_pkg" => pseudo_directory! {
"blobs" => pseudo_directory! {},
"repository_metadata" => DropAndSignal::new(metadata_closed_sender),
}
}
})
.build()
.await;
// Wait for the channel connecting the pkg-local-mirror to the metadata dir to close.
// This ensures that GetMetadata calls will fail with the expected fidl error.
let () = metadata_closed_recv.await.unwrap();
let (file_proxy, server_end) = create_proxy().unwrap();
let res = env
.local_mirror_proxy()
.get_metadata(&mut RepositoryUrl { url: repo_url().to_string() }, "1.root.json", server_end)
.await;
assert_eq!(res.unwrap(), Err(GetMetadataError::ErrorOpeningMetadata));
assert_matches!(file_proxy.take_event_stream().next().await, None);
assert_matches!(io_util::read_file(&file_proxy).await, Err(_));
}
|
|
global_memory_status.rs
|
#![cfg(target_os = "windows")]
use windows::Win32::System::SystemInformation::{GlobalMemoryStatusEx, MEMORYSTATUSEX};
use crate::{
data_source::DataSource,
system::{Data, DataFormat},
};
pub struct GlobalMemoryStatusDataSource;
impl DataSource for GlobalMemoryStatusDataSource {
fn name(&self) -> &'static str {
"windows/global-memory-status"
}
fn update(&self) -> eyre::Result<()> {
Ok(())
}
fn query(&mut self, query: &str, _preferred_format: &DataFormat) -> eyre::Result<Data> {
let mut mem = MEMORYSTATUSEX::default();
mem.dwLength = std::mem::size_of::<MEMORYSTATUSEX>() as u32;
let result = unsafe { GlobalMemoryStatusEx(&mut mem) };
if result.0 == 0 {
Err(::windows::core::Error::from_win32())?;
}
|
"dwMemoryLoad" => Data::I64(mem.dwMemoryLoad as i64),
"ullTotalPhys" => Data::I64(mem.ullTotalPhys as i64),
"ullAvailPhys" => Data::I64(mem.ullAvailPhys as i64),
"ullUsedPhys" => Data::I64((mem.ullTotalPhys - mem.ullAvailPhys) as i64),
"ullTotalPageFile" => Data::I64(mem.ullTotalPageFile as i64),
"ullAvailPageFile" => Data::I64(mem.ullAvailPageFile as i64),
"ullTotalVirtual" => Data::I64(mem.ullTotalVirtual as i64),
"ullAvailVirtual" => Data::I64(mem.ullAvailVirtual as i64),
"ullAvailExtendedVirtual" => Data::I64(mem.ullAvailExtendedVirtual as i64),
"dMemoryLoad" => Data::F64(
(mem.ullTotalPhys - mem.ullAvailPhys) as f64 / mem.ullTotalPhys as f64 * 100.0,
),
_ => eyre::bail!("Unknown query: {}", query),
};
Ok(data)
}
}
|
let data = match query {
|
mod.rs
|
//! ECMAScript lexer.
pub use self::{
input::Input,
state::{TokenContext, TokenContexts},
};
use self::{state::State, util::*};
use crate::{
error::{Error, SyntaxError},
token::*,
Context, JscTarget, Syntax,
};
use either::Either::{Left, Right};
use smallvec::{smallvec, SmallVec};
use std::{cell::RefCell, char, iter::FusedIterator, rc::Rc};
use swc_atoms::{js_word, JsWord};
use swc_common::{
comments::{Comment, Comments},
BytePos, Span,
};
use swc_ecma_ast::op;
pub mod input;
mod jsx;
mod number;
mod state;
#[cfg(test)]
mod tests;
pub mod util;
pub(crate) type LexResult<T> = Result<T, Error>;
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub(crate) struct
|
(u32);
impl From<char> for Char {
fn from(c: char) -> Self {
Char(c as u32)
}
}
impl From<u32> for Char {
fn from(c: u32) -> Self {
Char(c)
}
}
pub(crate) struct CharIter(SmallVec<[char; 7]>);
impl IntoIterator for Char {
type Item = char;
type IntoIter = CharIter;
#[allow(unsafe_code)]
fn into_iter(self) -> Self::IntoIter {
// // TODO: Check if this is correct
// fn to_char(v: u8) -> char {
// char::from_digit(v as _, 16).unwrap_or('0')
// }
CharIter(match char::from_u32(self.0) {
Some(c) => smallvec![c],
None => {
let c = unsafe { char::from_u32_unchecked(self.0) };
let escaped = c.escape_unicode().to_string();
debug_assert!(escaped.starts_with("\\"));
let mut buf = smallvec![];
buf.push('\\');
buf.push('\0');
buf.push('u');
if escaped.len() == 8 {
buf.extend(escaped[3..=6].chars());
} else {
buf.extend(escaped[2..].chars());
}
buf
}
})
}
}
impl Iterator for CharIter {
type Item = char;
fn next(&mut self) -> Option<Self::Item> {
if self.0.is_empty() {
None
} else {
Some(self.0.remove(0))
}
}
}
impl FusedIterator for CharIter {}
#[derive(Clone)]
pub struct Lexer<'a, I: Input> {
comments: Option<&'a dyn Comments>,
/// [Some] if comment comment parsing is enabled. Otherwise [None]
leading_comments_buffer: Option<Rc<RefCell<Vec<Comment>>>>,
pub(crate) ctx: Context,
input: I,
/// Stores last position of the last comment.
///
/// [Rc] and [RefCell] is used because this value should always increment,
/// even if backtracking fails.
last_comment_pos: Rc<RefCell<BytePos>>,
state: State,
pub(crate) syntax: Syntax,
pub(crate) target: JscTarget,
errors: Rc<RefCell<Vec<Error>>>,
module_errors: Rc<RefCell<Vec<Error>>>,
buf: Rc<RefCell<String>>,
}
impl<I: Input> FusedIterator for Lexer<'_, I> {}
impl<'a, I: Input> Lexer<'a, I> {
pub fn new(
syntax: Syntax,
target: JscTarget,
input: I,
comments: Option<&'a dyn Comments>,
) -> Self {
Lexer {
comments,
leading_comments_buffer: if comments.is_some() {
Some(Default::default())
} else {
None
},
ctx: Default::default(),
input,
last_comment_pos: Rc::new(RefCell::new(BytePos(0))),
state: State::new(syntax),
syntax,
target,
errors: Default::default(),
module_errors: Default::default(),
buf: Rc::new(RefCell::new(String::with_capacity(256))),
}
}
/// Utility method to reuse buffer.
fn with_buf<F, Ret>(&mut self, op: F) -> LexResult<Ret>
where
F: for<'any> FnOnce(&mut Lexer<'any, I>, &mut String) -> LexResult<Ret>,
{
let b = self.buf.clone();
let mut buf = b.borrow_mut();
buf.clear();
let res = op(self, &mut buf);
res
}
/// babel: `getTokenFromCode`
fn read_token(&mut self) -> LexResult<Option<Token>> {
let c = match self.input.cur() {
Some(c) => c,
None => {
return Ok(None);
}
};
let start = self.cur_pos();
let token = match c {
'#' => return self.read_token_number_sign(),
// Identifier or keyword. '\uXXXX' sequences are allowed in
// identifiers, so '\' also dispatches to that.
c if c == '\\' || c.is_ident_start() => return self.read_ident_or_keyword().map(Some),
//
'.' => {
// Check for eof
let next = match self.input.peek() {
Some(next) => next,
None => {
self.input.bump();
return Ok(Some(tok!('.')));
}
};
if '0' <= next && next <= '9' {
return self
.read_number(true)
.map(|v| match v {
Left(v) => Num(v),
Right(v) => BigInt(v),
})
.map(Some);
}
self.input.bump(); // 1st `.`
if next == '.' && self.input.peek() == Some('.') {
self.input.bump(); // 2nd `.`
self.input.bump(); // 3rd `.`
return Ok(Some(tok!("...")));
}
return Ok(Some(tok!('.')));
}
'(' | ')' | ';' | ',' | '[' | ']' | '{' | '}' | '@' => {
// These tokens are emitted directly.
self.input.bump();
return Ok(Some(match c {
'(' => LParen,
')' => RParen,
';' => Semi,
',' => Comma,
'[' => LBracket,
']' => RBracket,
'{' => LBrace,
'}' => RBrace,
'@' => At,
_ => unreachable!(),
}));
}
'?' => match self.input.peek() {
Some('?') => {
self.input.bump();
self.input.bump();
if self.input.cur() == Some('=') {
self.input.bump();
return Ok(Some(tok!("??=")));
}
return Ok(Some(tok!("??")));
}
_ => {
self.input.bump();
return Ok(Some(tok!('?')));
}
},
'`' => {
self.bump();
return Ok(Some(tok!('`')));
}
':' => {
self.input.bump();
if self.syntax.fn_bind() && self.input.cur() == Some(':') {
self.input.bump();
return Ok(Some(tok!("::")));
}
return Ok(Some(tok!(':')));
}
'0' => {
let next = self.input.peek();
let radix = match next {
Some('x') | Some('X') => 16,
Some('o') | Some('O') => 8,
Some('b') | Some('B') => 2,
_ => {
return self
.read_number(false)
.map(|v| match v {
Left(v) => Num(v),
Right(v) => BigInt(v),
})
.map(Some)
}
};
return self
.read_radix_number(radix)
.map(|v| match v {
Left(v) => Num(v),
Right(v) => BigInt(v),
})
.map(Some);
}
'1'..='9' => {
return self
.read_number(false)
.map(|v| match v {
Left(v) => Num(v),
Right(v) => BigInt(v),
})
.map(Some)
}
'"' | '\'' => return self.read_str_lit().map(Some),
'/' => return self.read_slash(),
c @ '%' | c @ '*' => {
let is_mul = c == '*';
self.input.bump();
let mut token = if is_mul { BinOp(Mul) } else { BinOp(Mod) };
// check for **
if is_mul && self.input.cur() == Some('*') {
self.input.bump();
token = BinOp(Exp)
}
if self.input.cur() == Some('=') {
self.input.bump();
token = match token {
BinOp(Mul) => AssignOp(MulAssign),
BinOp(Mod) => AssignOp(ModAssign),
BinOp(Exp) => AssignOp(ExpAssign),
_ => unreachable!(),
}
}
token
}
// Logical operators
c @ '|' | c @ '&' => {
self.input.bump();
let token = if c == '&' { BitAnd } else { BitOr };
// '|=', '&='
if self.input.cur() == Some('=') {
self.input.bump();
return Ok(Some(AssignOp(match token {
BitAnd => BitAndAssign,
BitOr => BitOrAssign,
_ => unreachable!(),
})));
}
// '||', '&&'
if self.input.cur() == Some(c) {
self.input.bump();
if self.input.cur() == Some('=') {
self.input.bump();
return Ok(Some(AssignOp(match token {
BitAnd => op!("&&="),
BitOr => op!("||="),
_ => unreachable!(),
})));
}
return Ok(Some(BinOp(match token {
BitAnd => LogicalAnd,
BitOr => LogicalOr,
_ => unreachable!(),
})));
}
BinOp(token)
}
'^' => {
// Bitwise xor
self.input.bump();
if self.input.cur() == Some('=') {
self.input.bump();
AssignOp(BitXorAssign)
} else {
BinOp(BitXor)
}
}
'+' | '-' => {
self.input.bump();
// '++', '--'
if self.input.cur() == Some(c) {
self.input.bump();
// Handle -->
if self.state.had_line_break && c == '-' && self.eat(b'>') {
self.emit_module_mode_error(start, SyntaxError::LegacyCommentInModule);
self.skip_line_comment(0);
self.skip_space()?;
return self.read_token();
}
if c == '+' {
PlusPlus
} else {
MinusMinus
}
} else if self.input.cur() == Some('=') {
self.input.bump();
AssignOp(if c == '+' { AddAssign } else { SubAssign })
} else {
BinOp(if c == '+' { Add } else { Sub })
}
}
'<' | '>' => return self.read_token_lt_gt(),
'!' | '=' => {
self.input.bump();
if self.input.cur() == Some('=') {
// "=="
self.input.bump();
if self.input.cur() == Some('=') {
self.input.bump();
if c == '!' {
BinOp(NotEqEq)
} else {
BinOp(EqEqEq)
}
} else if c == '!' {
BinOp(NotEq)
} else {
BinOp(EqEq)
}
} else if c == '=' && self.input.cur() == Some('>') {
// "=>"
self.input.bump();
Arrow
} else if c == '!' {
Bang
} else {
AssignOp(Assign)
}
}
'~' => {
self.input.bump();
tok!('~')
}
// unexpected character
c => {
self.input.bump();
self.error_span(pos_span(start), SyntaxError::UnexpectedChar { c })?
}
};
Ok(Some(token))
}
/// `#`
fn read_token_number_sign(&mut self) -> LexResult<Option<Token>> {
debug_assert!(self.cur().is_some());
let start = self.input.cur_pos();
if self.input.is_at_start() && self.read_token_interpreter()? {
return Ok(None);
}
if self.syntax.class_private_props() || self.syntax.class_private_methods() {
self.input.bump(); // '#'
return Ok(Some(Token::Hash));
}
self.error(start, SyntaxError::Hash)?
}
fn read_token_interpreter(&mut self) -> LexResult<bool> {
if !self.input.is_at_start() {
return Ok(false);
}
let start = self.input.cur_pos();
self.input.bump();
let c = self.input.cur();
if c == Some('!') {
loop {
while let Some(c) = self.input.cur() {
if c != '\n' && c != '\r' && c != '\u{8232}' && c != '\u{8233}' {
self.input.bump();
continue;
}
}
}
} else {
self.input.reset_to(start);
Ok(false)
}
}
/// Read an escaped character for string literal.
///
/// In template literal, we should preserve raw string.
fn read_escaped_char(&mut self, raw: &mut Raw) -> LexResult<Option<Char>> {
debug_assert_eq!(self.cur(), Some('\\'));
let start = self.cur_pos();
self.bump(); // '\'
let in_template = raw.0.is_some();
let c = match self.cur() {
Some(c) => c,
None => self.error_span(pos_span(start), SyntaxError::InvalidStrEscape)?,
};
macro_rules! push_c_and_ret {
($c:expr) => {{
raw.push(c);
$c
}};
}
let c = match c {
'\\' => push_c_and_ret!('\\'),
'n' => push_c_and_ret!('\n'),
'r' => push_c_and_ret!('\r'),
't' => push_c_and_ret!('\t'),
'b' => push_c_and_ret!('\u{0008}'),
'v' => push_c_and_ret!('\u{000b}'),
'f' => push_c_and_ret!('\u{000c}'),
'\r' => {
raw.push_str("\r");
self.bump(); // remove '\r'
if self.eat(b'\n') {
raw.push_str("\n");
}
return Ok(None);
}
'\n' | '\u{2028}' | '\u{2029}' => {
match c {
'\n' => raw.push_str("\n"),
'\u{2028}' => raw.push_str("\u{2028}"),
'\u{2029}' => raw.push_str("\u{2029}"),
_ => unreachable!(),
}
self.bump();
return Ok(None);
}
// read hexadecimal escape sequences
'x' => {
raw.push_str("0x");
self.bump(); // 'x'
return self.read_hex_char(start, 2, raw).map(Some);
}
// read unicode escape sequences
'u' => {
return self.read_unicode_escape(start, raw).map(Some);
}
// octal escape sequences
'0'..='7' => {
raw.push(c);
self.bump();
let first_c = if c == '0' {
match self.cur() {
Some(next) if next.is_digit(8) => c,
// \0 is not an octal literal nor decimal literal.
_ => return Ok(Some('\u{0000}'.into())),
}
} else {
c
};
// TODO: Show template instead of strict mode
if in_template {
self.error(start, SyntaxError::LegacyOctal)?
}
self.emit_strict_mode_error(start, SyntaxError::LegacyOctal);
let mut value: u8 = first_c.to_digit(8).unwrap() as u8;
macro_rules! one {
($check:expr) => {{
match self.cur().and_then(|c| c.to_digit(8)) {
Some(v) => {
value = if $check {
let new_val = value
.checked_mul(8)
.and_then(|value| value.checked_add(v as u8));
match new_val {
Some(val) => val,
None => return Ok(Some(value as char).map(From::from)),
}
} else {
value * 8 + v as u8
};
self.bump();
}
_ => return Ok(Some(value as u32).map(From::from)),
}
}};
}
one!(false);
one!(true);
return Ok(Some(value as char).map(From::from));
}
_ => {
raw.push(c);
c
}
};
self.input.bump();
Ok(Some(c.into()))
}
}
impl<'a, I: Input> Lexer<'a, I> {
fn read_slash(&mut self) -> LexResult<Option<Token>> {
debug_assert_eq!(self.cur(), Some('/'));
// let start = self.cur_pos();
// Regex
if self.state.is_expr_allowed {
return self.read_regexp().map(Some);
}
// Divide operator
self.bump();
Ok(Some(if self.eat(b'=') {
tok!("/=")
} else {
tok!('/')
}))
}
fn read_token_lt_gt(&mut self) -> LexResult<Option<Token>> {
debug_assert!(self.cur() == Some('<') || self.cur() == Some('>'));
let start = self.cur_pos();
let c = self.cur().unwrap();
self.bump();
// XML style comment. `<!--`
if !self.ctx.dont_store_comments
&& c == '<'
&& self.is(b'!')
&& self.peek() == Some('-')
&& self.peek_ahead() == Some('-')
{
self.skip_line_comment(3);
self.skip_space()?;
self.emit_module_mode_error(start, SyntaxError::LegacyCommentInModule);
return self.read_token();
}
let mut op = if c == '<' { Lt } else { Gt };
// '<<', '>>'
if self.cur() == Some(c) {
self.bump();
op = if c == '<' { LShift } else { RShift };
//'>>>'
if c == '>' && self.cur() == Some(c) {
self.bump();
op = ZeroFillRShift;
}
}
let token = if self.eat(b'=') {
match op {
Lt => BinOp(LtEq),
Gt => BinOp(GtEq),
LShift => AssignOp(LShiftAssign),
RShift => AssignOp(RShiftAssign),
ZeroFillRShift => AssignOp(ZeroFillRShiftAssign),
_ => unreachable!(),
}
} else {
BinOp(op)
};
Ok(Some(token))
}
/// See https://tc39.github.io/ecma262/#sec-names-and-keywords
fn read_ident_or_keyword(&mut self) -> LexResult<Token> {
debug_assert!(self.cur().is_some());
let start = self.cur_pos();
let (word, has_escape) = self.read_word_as_str_with(|s| match s {
"null" => Word::Null,
"true" => Word::True,
"false" => Word::False,
"await" => Await.into(),
"break" => Break.into(),
"case" => Case.into(),
"catch" => Catch.into(),
"continue" => Continue.into(),
"debugger" => Debugger.into(),
"default" => Default_.into(),
"do" => Do.into(),
"export" => Export.into(),
"else" => Else.into(),
"finally" => Finally.into(),
"for" => For.into(),
"function" => Function.into(),
"if" => If.into(),
"return" => Return.into(),
"switch" => Switch.into(),
"throw" => Throw.into(),
"try" => Try.into(),
"var" => Var.into(),
"let" => Let.into(),
"const" => Const.into(),
"while" => While.into(),
"with" => With.into(),
"new" => New.into(),
"this" => This.into(),
"super" => Super.into(),
"class" => Class.into(),
"extends" => Extends.into(),
"import" => Import.into(),
"yield" => Yield.into(),
"in" => In.into(),
"instanceof" => InstanceOf.into(),
"typeof" => TypeOf.into(),
"void" => Void.into(),
"delete" => Delete.into(),
_ => Word::Ident(s.into()),
})?;
// Note: ctx is store in lexer because of this error.
// 'await' and 'yield' may have semantic of reserved word, which means lexer
// should know context or parser should handle this error. Our approach to this
// problem is former one.
if has_escape && self.ctx.is_reserved(&word) {
self.error(
start,
SyntaxError::EscapeInReservedWord { word: word.into() },
)?
} else {
Ok(Word(word))
}
}
fn may_read_word_as_str(&mut self) -> LexResult<Option<(JsWord, bool)>> {
match self.cur() {
Some(c) if c.is_ident_start() => self.read_word_as_str().map(Some),
_ => Ok(None),
}
}
fn read_word_as_str(&mut self) -> LexResult<(JsWord, bool)> {
self.read_word_as_str_with(|s| JsWord::from(s))
}
/// returns (word, has_escape)
///
/// This method is optimized for texts without escape sequences.
fn read_word_as_str_with<F, Ret>(&mut self, convert: F) -> LexResult<(Ret, bool)>
where
F: FnOnce(&str) -> Ret,
{
debug_assert!(self.cur().is_some());
let mut first = true;
self.with_buf(|l, buf| {
let mut has_escape = false;
while let Some(c) = {
// Optimization
{
let s = l.input.uncons_while(|c| c.is_ident_part());
if !s.is_empty() {
first = false;
}
buf.push_str(s)
}
l.cur()
} {
let start = l.cur_pos();
match c {
c if c.is_ident_part() => {
l.bump();
buf.push(c);
}
// unicode escape
'\\' => {
l.bump();
if !l.is(b'u') {
l.error_span(pos_span(start), SyntaxError::ExpectedUnicodeEscape)?
}
has_escape = true;
let c = l.read_unicode_escape(start, &mut Raw(None))?;
let valid = if first {
c.is_ident_start()
} else {
c.is_ident_part()
};
if !valid {
l.emit_error(start, SyntaxError::InvalidIdentChar);
}
buf.extend(c);
}
_ => {
break;
}
}
first = false;
}
let value = convert(&buf);
Ok((value, has_escape))
})
}
fn read_unicode_escape(&mut self, start: BytePos, raw: &mut Raw) -> LexResult<Char> {
debug_assert_eq!(self.cur(), Some('u'));
self.bump();
raw.push_str("u");
if self.eat(b'{') {
raw.push('{');
// let cp_start = self.cur_pos();
let c = self.read_code_point(raw)?;
if !self.eat(b'}') {
self.error(start, SyntaxError::InvalidUnicodeEscape)?
}
raw.push('}');
Ok(c)
} else {
self.read_hex_char(start, 4, raw)
}
}
///
///
/// This method returns [Char] as non-utf8 character is valid in JavaScript.
/// See https://github.com/swc-project/swc/issues/261
fn read_hex_char(&mut self, start: BytePos, count: u8, raw: &mut Raw) -> LexResult<Char> {
debug_assert!(count == 2 || count == 4);
// let pos = self.cur_pos();
match self.read_int_u32(16, count, raw)? {
Some(val) => Ok(val.into()),
None => self.error(start, SyntaxError::ExpectedHexChars { count })?,
}
}
/// Read `CodePoint`.
fn read_code_point(&mut self, raw: &mut Raw) -> LexResult<Char> {
let start = self.cur_pos();
let val = self.read_int_u32(16, 0, raw)?;
match val {
Some(val) if 0x0010_FFFF >= val => match char::from_u32(val) {
Some(c) => Ok(c.into()),
None => self.error(start, SyntaxError::InvalidCodePoint)?,
},
_ => self.error(start, SyntaxError::InvalidCodePoint)?,
}
}
/// See https://tc39.github.io/ecma262/#sec-literals-string-literals
fn read_str_lit(&mut self) -> LexResult<Token> {
debug_assert!(self.cur() == Some('\'') || self.cur() == Some('"'));
let start = self.cur_pos();
let quote = self.cur().unwrap();
self.bump(); // '"'
self.with_buf(|l, out| {
let mut has_escape = false;
while let Some(c) = {
// Optimization
{
let s = l
.input
.uncons_while(|c| c != quote && c != '\\' && !c.is_line_break());
out.push_str(s);
}
l.cur()
} {
match c {
c if c == quote => {
l.bump();
return Ok(Token::Str {
value: (&**out).into(),
has_escape,
});
}
'\\' => {
if let Some(s) = l.read_escaped_char(&mut Raw(None))? {
out.extend(s);
}
has_escape = true
}
c if c.is_line_break() => l.error(start, SyntaxError::UnterminatedStrLit)?,
_ => {
out.push(c);
l.bump();
}
}
}
l.error(start, SyntaxError::UnterminatedStrLit)?
})
}
/// Expects current char to be '/'
fn read_regexp(&mut self) -> LexResult<Token> {
debug_assert_eq!(self.cur(), Some('/'));
let start = self.cur_pos();
self.bump();
let (mut escaped, mut in_class) = (false, false);
// let content_start = self.cur_pos();
let content = self.with_buf(|l, buf| {
while let Some(c) = l.cur() {
// This is ported from babel.
// Seems like regexp literal cannot contain linebreak.
if c.is_line_terminator() {
l.error(start, SyntaxError::UnterminatedRegxp)?;
}
if escaped {
escaped = false;
} else {
match c {
'[' => in_class = true,
']' if in_class => in_class = false,
// Terminates content part of regex literal
'/' if !in_class => break,
_ => {}
}
escaped = c == '\\';
}
l.bump();
buf.push(c);
}
Ok((&**buf).into())
})?;
// let content_span = Span::new(content_start, self.cur_pos(),
// Default::default());
// input is terminated without following `/`
if !self.is(b'/') {
self.error(start, SyntaxError::UnterminatedRegxp)?;
}
self.bump(); // '/'
// Spec says "It is a Syntax Error if IdentifierPart contains a Unicode escape
// sequence." TODO: check for escape
// Need to use `read_word` because '\uXXXX' sequences are allowed
// here (don't ask).
// let flags_start = self.cur_pos();
let flags = self
.may_read_word_as_str()?
.map(|(value, _)| value)
.unwrap_or(js_word!(""));
Ok(Regex(content, flags))
}
fn read_shebang(&mut self) -> LexResult<Option<JsWord>> {
if self.input.cur() != Some('#') || self.input.peek() != Some('!') {
return Ok(None);
}
self.input.bump();
self.input.bump();
let s = self.input.uncons_while(|c| !c.is_line_terminator());
Ok(Some(s.into()))
}
fn read_tmpl_token(&mut self, start_of_tpl: BytePos) -> LexResult<Token> {
let start = self.cur_pos();
// TODO: Optimize
let mut has_escape = false;
let mut cooked = Some(String::new());
let mut raw = String::new();
while let Some(c) = self.cur() {
if c == '`' || (c == '$' && self.peek() == Some('{')) {
if start == self.cur_pos() && self.state.last_was_tpl_element() {
if c == '$' {
self.bump();
self.bump();
return Ok(tok!("${"));
} else {
self.bump();
return Ok(tok!('`'));
}
}
// TODO: Handle error
return Ok(Template {
cooked: cooked.map(|cooked| cooked.into()),
raw: raw.into(),
has_escape,
});
}
if c == '\\' {
has_escape = true;
raw.push('\\');
let mut wrapped = Raw(Some(raw));
match self.read_escaped_char(&mut wrapped) {
Ok(Some(s)) => {
if let Some(ref mut cooked) = cooked {
cooked.extend(s);
}
}
Ok(None) => {}
Err(error) => {
if self.target < JscTarget::Es2018 {
return Err(error);
} else {
cooked = None;
}
}
}
raw = wrapped.0.unwrap();
} else if c.is_line_terminator() {
self.state.had_line_break = true;
let c = if c == '\r' && self.peek() == Some('\n') {
raw.push('\r');
self.bump(); // '\r'
'\n'
} else {
match c {
'\n' => '\n',
'\r' => '\n',
'\u{2028}' => '\u{2028}',
'\u{2029}' => '\u{2029}',
_ => unreachable!(),
}
};
self.bump();
if let Some(ref mut cooked) = cooked {
cooked.push(c);
}
raw.push(c);
} else {
self.bump();
if let Some(ref mut cooked) = cooked {
cooked.push(c);
}
raw.push(c);
}
}
self.error(start_of_tpl, SyntaxError::UnterminatedTpl)?
}
pub fn had_line_break_before_last(&self) -> bool {
self.state.had_line_break
}
pub fn set_expr_allowed(&mut self, allow: bool) {
self.state.is_expr_allowed = allow;
}
}
fn pos_span(p: BytePos) -> Span {
Span::new(p, p, Default::default())
}
|
Char
|
suite_test.go
|
// Copyright 2012 tsuru authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package permission
import (
"testing"
"github.com/tsuru/config"
"github.com/tsuru/tsuru/db"
"github.com/tsuru/tsuru/db/dbtest"
check "gopkg.in/check.v1"
)
func
|
(t *testing.T) { check.TestingT(t) }
type S struct{}
var _ = check.Suite(&S{})
func (s *S) SetUpTest(c *check.C) {
config.Set("database:url", "127.0.0.1:27017?maxPoolSize=100")
config.Set("database:name", "tsuru_permission_test")
conn, err := db.Conn()
c.Assert(err, check.IsNil)
defer conn.Close()
dbtest.ClearAllCollections(conn.Apps().Database)
}
func (s *S) TearDownSuite(c *check.C) {
conn, err := db.Conn()
c.Assert(err, check.IsNil)
defer conn.Close()
conn.Apps().Database.DropDatabase()
}
|
Test
|
product.js
|
import { stringify } from 'qs';
import request from '@/utils/request';
import { getAuthority } from '@/utils/authority';
export async function getProducts(params) {
return request(`/api/product/list?${stringify(params)}`);
}
export async function saveProduct(params) {
return request(`/api/product/save?ref=${new Date().getTime()}`,{
method : "POST",
body: params,
headers:{'X-Access-Token':getAuthority()[0].token}
});
}
export async function updateProduct(params) {
return request(`/api/product/update?ref=${new Date().getTime()}`,{
method : "PUT",
body: params,
headers:{'X-Access-Token':getAuthority()[0].token}
});
}
export async function getProductDetail(params) {
return request(`/api/product/DT?productid=${params.productid}&ref=${new Date().getTime()}`,{
method : "GET",
headers:{'X-Access-Token':getAuthority()[0].token}
});
}
export async function searchProduct(params) {
return request(`/api/product/search`,{
method : "POST",
body: params,
headers:{'X-Access-Token':getAuthority()[0].token}
});
}
export async function saveProductVariants(params) {
return request(`/api/product/saveProductVariants`,{
method : "PUT",
body: params,
headers:{'X-Access-Token':getAuthority()[0].token}
});
}
export async function getProductsByCategory() {
return request(`/api/product/PL?ref=${new Date().getTime()}`,{
method : "GET",
headers:{'X-Access-Token':getAuthority()[0].token}
});
}
export async function getProductsByCategoryDetail() {
return request(`/api/product/POD?ref=${new Date().getTime()}`,{
method : "GET",
headers:{'X-Access-Token':getAuthority()[0].token}
});
}
export async function saveProducts(params) {
return request(`/api/product/saveProducts?ref=${new Date().getTime()}`,{
method : "PUT",
body: params,
headers:{'X-Access-Token':getAuthority()[0].token}
});
}
export async function addProduct(params) {
return request(`/api/product/add?ref=${new Date().getTime()}`,{
method : "POST",
body: params,
headers:{'X-Access-Token':getAuthority()[0].token}
});
}
export async function getProduct(params) {
return request(`/api/product/v2/${params}`);
}
export async function getVariantsBy(params) {
return request(`/api/product/v2/variants/${params}`);
}
export async function getOptionsBy(params) {
return request(`/api/product/v2/options/${params}`);
}
export async function deleteOption(params) {
return request(`/api/product/v2/options/delete/${params.key}/${params.productid}`,{
method : "DELETE",
headers:{'X-Access-Token':getAuthority()[0].token}
|
method : "POST",
body: params,
headers:{'X-Access-Token':getAuthority()[0].token}
});
}
export async function updateOption(params) {
return request(`/api/product/v2/options/update`,{
method : "PUT",
body: params,
headers:{'X-Access-Token':getAuthority()[0].token}
});
}
|
});
}
export async function addOption(params) {
return request(`/api/product/v2/options/add`,{
|
tag_keys_client_example_test.go
|
// Copyright 2021 Google LLC
//
// 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
//
// https://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.
// Code generated by protoc-gen-go_gapic. DO NOT EDIT.
package resourcemanager_test
import (
"context"
resourcemanager "cloud.google.com/go/resourcemanager/apiv3"
"google.golang.org/api/iterator"
resourcemanagerpb "google.golang.org/genproto/googleapis/cloud/resourcemanager/v3"
iampb "google.golang.org/genproto/googleapis/iam/v1"
)
func ExampleNewTagKeysClient() {
ctx := context.Background()
c, err := resourcemanager.NewTagKeysClient(ctx)
if err != nil {
// TODO: Handle error.
}
defer c.Close()
// TODO: Use client.
_ = c
}
func ExampleTagKeysClient_ListTagKeys() {
ctx := context.Background()
c, err := resourcemanager.NewTagKeysClient(ctx)
if err != nil {
// TODO: Handle error.
}
defer c.Close()
req := &resourcemanagerpb.ListTagKeysRequest{
// TODO: Fill request struct fields.
// See https://pkg.go.dev/google.golang.org/genproto/googleapis/cloud/resourcemanager/v3#ListTagKeysRequest.
}
it := c.ListTagKeys(ctx, req)
for {
resp, err := it.Next()
if err == iterator.Done {
break
}
if err != nil {
// TODO: Handle error.
}
// TODO: Use resp.
_ = resp
}
}
func ExampleTagKeysClient_GetTagKey() {
ctx := context.Background()
c, err := resourcemanager.NewTagKeysClient(ctx)
if err != nil {
// TODO: Handle error.
}
defer c.Close()
req := &resourcemanagerpb.GetTagKeyRequest{
// TODO: Fill request struct fields.
// See https://pkg.go.dev/google.golang.org/genproto/googleapis/cloud/resourcemanager/v3#GetTagKeyRequest.
}
resp, err := c.GetTagKey(ctx, req)
if err != nil {
// TODO: Handle error.
}
// TODO: Use resp.
_ = resp
}
func ExampleTagKeysClient_CreateTagKey() {
ctx := context.Background()
c, err := resourcemanager.NewTagKeysClient(ctx)
if err != nil {
// TODO: Handle error.
}
defer c.Close()
req := &resourcemanagerpb.CreateTagKeyRequest{
// TODO: Fill request struct fields.
// See https://pkg.go.dev/google.golang.org/genproto/googleapis/cloud/resourcemanager/v3#CreateTagKeyRequest.
}
op, err := c.CreateTagKey(ctx, req)
if err != nil {
// TODO: Handle error.
}
resp, err := op.Wait(ctx)
if err != nil {
// TODO: Handle error.
}
// TODO: Use resp.
_ = resp
}
func ExampleTagKeysClient_UpdateTagKey() {
ctx := context.Background()
c, err := resourcemanager.NewTagKeysClient(ctx)
if err != nil {
// TODO: Handle error.
}
defer c.Close()
req := &resourcemanagerpb.UpdateTagKeyRequest{
// TODO: Fill request struct fields.
// See https://pkg.go.dev/google.golang.org/genproto/googleapis/cloud/resourcemanager/v3#UpdateTagKeyRequest.
}
op, err := c.UpdateTagKey(ctx, req)
if err != nil {
// TODO: Handle error.
}
resp, err := op.Wait(ctx)
if err != nil {
// TODO: Handle error.
}
// TODO: Use resp.
_ = resp
}
func ExampleTagKeysClient_DeleteTagKey() {
ctx := context.Background()
c, err := resourcemanager.NewTagKeysClient(ctx)
if err != nil {
// TODO: Handle error.
}
defer c.Close()
req := &resourcemanagerpb.DeleteTagKeyRequest{
// TODO: Fill request struct fields.
// See https://pkg.go.dev/google.golang.org/genproto/googleapis/cloud/resourcemanager/v3#DeleteTagKeyRequest.
}
op, err := c.DeleteTagKey(ctx, req)
if err != nil {
// TODO: Handle error.
}
resp, err := op.Wait(ctx)
if err != nil {
// TODO: Handle error.
}
// TODO: Use resp.
_ = resp
|
c, err := resourcemanager.NewTagKeysClient(ctx)
if err != nil {
// TODO: Handle error.
}
defer c.Close()
req := &iampb.GetIamPolicyRequest{
// TODO: Fill request struct fields.
// See https://pkg.go.dev/google.golang.org/genproto/googleapis/iam/v1#GetIamPolicyRequest.
}
resp, err := c.GetIamPolicy(ctx, req)
if err != nil {
// TODO: Handle error.
}
// TODO: Use resp.
_ = resp
}
func ExampleTagKeysClient_SetIamPolicy() {
ctx := context.Background()
c, err := resourcemanager.NewTagKeysClient(ctx)
if err != nil {
// TODO: Handle error.
}
defer c.Close()
req := &iampb.SetIamPolicyRequest{
// TODO: Fill request struct fields.
// See https://pkg.go.dev/google.golang.org/genproto/googleapis/iam/v1#SetIamPolicyRequest.
}
resp, err := c.SetIamPolicy(ctx, req)
if err != nil {
// TODO: Handle error.
}
// TODO: Use resp.
_ = resp
}
func ExampleTagKeysClient_TestIamPermissions() {
ctx := context.Background()
c, err := resourcemanager.NewTagKeysClient(ctx)
if err != nil {
// TODO: Handle error.
}
defer c.Close()
req := &iampb.TestIamPermissionsRequest{
// TODO: Fill request struct fields.
// See https://pkg.go.dev/google.golang.org/genproto/googleapis/iam/v1#TestIamPermissionsRequest.
}
resp, err := c.TestIamPermissions(ctx, req)
if err != nil {
// TODO: Handle error.
}
// TODO: Use resp.
_ = resp
}
|
}
func ExampleTagKeysClient_GetIamPolicy() {
ctx := context.Background()
|
HeaderBar.js
|
import React, {Component} from "react";
import AppBar from 'material-ui/AppBar';
import FlatButton from 'material-ui/FlatButton';
import profileService from '../../../service/service/ProfileService';
import history from '../../../service/router/History';
import PubSub from 'pubsub-js';
import Popover, {PopoverAnimationVertical} from 'material-ui/Popover';
import Menu from 'material-ui/Menu';
import MenuItem from 'material-ui/MenuItem';
import ChangePassword from './ChangePassword';
import SettingsIco from 'material-ui/svg-icons/action/settings';
class
|
extends Component {
constructor() {
super();
this.state = {label: '',changePass:false, mounted:false};
PubSub.subscribe('header-label', this.fncChangeHeaderLabel);
};
componentDidMount()
{
this.setState({mounted:true});
}
componentWillUnmount()
{
this.setState({mounted:false});
PubSub.unsubscribe('header-label')
}
fncChangeHeaderLabel = (key, label) =>
{
if (this.state.mounted)
{
this.setState({'label': label});
}
};
fncLogOut = () => {
PubSub.clearAllSubscriptions();
localStorage.removeItem('auth-token');
localStorage.removeItem('profile');
history.push('/');
};
fncOpenChangePass = () => {this.setState({'changePass':true})};
handleClick = (event) => {
event.preventDefault();
this.setState({ open: true, anchorEl: event.currentTarget});
};
handleRequestClose = () => { this.setState({open: false }); };
render() {
return (
<div>
<AppBar
showMenuIconButton={false}
style={{paddingLeft: '220px', position: 'fixed'}}
title={this.state.label}
iconElementRight=
{
<custom>
<div style={{marginTop:'6px'}}>
<FlatButton
onClick={this.handleClick}
style={{color:'#fff'}}
label={profileService.getName()}
icon={<SettingsIco />}
/>
<Popover
open={this.state.open}
anchorEl={this.state.anchorEl}
anchorOrigin={{horizontal: 'right', vertical: 'bottom'}}
targetOrigin={{horizontal: 'left', vertical: 'top'}}
animation={PopoverAnimationVertical}
onRequestClose={this.handleRequestClose}
>
<Menu>
<MenuItem onClick={() => {this.fncOpenChangePass()}} primaryText="Change password" />
<MenuItem onClick={() => {this.fncLogOut()}} primaryText="Logout" />
</Menu>
</Popover>
</div>
</custom>
}
/>
{(this.state.changePass)? <ChangePassword /> : null}
</div>
)
};
}
export default HeaderBar;
|
HeaderBar
|
dlog.go
|
package dlog
import (
"bytes"
"fmt"
"os"
"runtime"
"strings"
"sync"
"time"
)
type Severity int
const (
FATAL Severity = iota
ERROR
WARNING
INFO
DEBUG
)
var severityName = []string{
FATAL: "FATAL",
ERROR: "ERROR",
WARNING: "WARNING",
INFO: "INFO",
DEBUG: "DEBUG",
}
const (
numSeverity = 5
)
type Backend interface {
Log(s Severity, msg []byte)
close()
}
type stdBackend struct{}
func (self *stdBackend) Log(s Severity, msg []byte) {
os.Stdout.Write(msg)
}
func (self *stdBackend) close() {}
type Logger struct {
s Severity
backend Backend
mu sync.Mutex
freeList *buffer
freeListMu sync.Mutex
logToStderr bool
}
//resued buffer for fast format the output string
type buffer struct {
bytes.Buffer
tmp [64]byte
next *buffer
}
func (self *Logger) getBuffer() *buffer {
self.freeListMu.Lock()
b := self.freeList
if b != nil {
self.freeList = b.next
}
self.freeListMu.Unlock()
if b == nil {
b = new(buffer)
} else {
b.next = nil
b.Reset()
}
return b
}
// Some custom tiny helper functions to print the log header efficiently.
const digits = "0123456789"
// twoDigits formats a zero-prefixed two-digit integer at buf.tmp[i].
func (buf *buffer) twoDigits(i, d int) {
buf.tmp[i+1] = digits[d%10]
d /= 10
buf.tmp[i] = digits[d%10]
}
// nDigits formats an n-digit integer at buf.tmp[i],
// padding with pad on the left.
// It assumes d >= 0.
func (buf *buffer) nDigits(n, i, d int, pad byte) {
j := n - 1
for ; j >= 0 && d > 0; j-- {
buf.tmp[i+j] = digits[d%10]
d /= 10
}
for ; j >= 0; j-- {
buf.tmp[i+j] = pad
}
}
// someDigits formats a zero-prefixed variable-width integer at buf.tmp[i].
func (buf *buffer) someDigits(i, d int) int {
// Print into the top, then copy down. We know there's space for at least
// a 10-digit number.
j := len(buf.tmp)
for {
j--
buf.tmp[j] = digits[d%10]
d /= 10
if d == 0 {
break
}
}
return copy(buf.tmp[i:], buf.tmp[j:])
}
func (self *Logger) putBuffer(b *buffer) {
if b.Len() >= 256 {
// Let big buffers die a natural death.
return
}
self.freeListMu.Lock()
b.next = self.freeList
self.freeList = b
self.freeListMu.Unlock()
}
func (self *Logger) formatHeader(s Severity, file string, line int) *buffer {
now := time.Now()
if line < 0 {
line = 0 // not a real line number, but acceptable to someDigits
}
buf := self.getBuffer()
// Avoid Fprintf, for speed. The format is so simple that we can do it quickly by hand.
// It's worth about 3X. Fprintf is hard.
year, month, day := now.Date()
hour, minute, second := now.Clock()
//2015-06-16 12:00:35 ERROR test.go:12 ...
buf.nDigits(4, 0, year, '0')
buf.tmp[4] = '-'
buf.twoDigits(5, int(month))
buf.tmp[7] = '-'
buf.twoDigits(8, day)
buf.tmp[10] = ' '
buf.twoDigits(11, hour)
buf.tmp[13] = ':'
buf.twoDigits(14, minute)
buf.tmp[16] = ':'
buf.twoDigits(17, second)
buf.tmp[19] = '.'
buf.nDigits(6, 20, now.Nanosecond()/1000, '0')
buf.tmp[26] = ' '
buf.Write(buf.tmp[:27])
buf.WriteString(severityName[s])
buf.WriteByte(' ')
buf.WriteString(file)
buf.tmp[0] = ':'
n := buf.someDigits(1, line)
buf.tmp[n+1] = ' '
buf.Write(buf.tmp[:n+2])
return buf
}
func (self *Logger) header(s Severity, depth int) *buffer {
_, file, line, ok := runtime.Caller(3 + depth)
if !ok {
file = "???"
line = 1
} else {
dirs := strings.Split(file, "/")
if len(dirs) >= 2 {
file = dirs[len(dirs)-2] + "/" + dirs[len(dirs)-1]
} else {
file = dirs[len(dirs)-1]
}
}
return self.formatHeader(s, file, line)
}
func (self *Logger) print(s Severity, args ...interface{}) {
self.printDepth(s, 1, args...)
}
func (self *Logger) printf(s Severity, format string, args ...interface{}) {
self.printfDepth(s, 1, format, args...)
}
func (self *Logger) printDepth(s Severity, depth int, args ...interface{}) {
if self.s < s {
return
}
buf := self.header(s, depth)
fmt.Fprint(buf, args...)
if buf.Bytes()[buf.Len()-1] != '\n' {
buf.WriteByte('\n')
}
self.output(s, buf)
}
func (self *Logger) printfDepth(s Severity, depth int, format string, args ...interface{}) {
if self.s < s {
return
}
buf := self.header(s, depth)
fmt.Fprintf(buf, format, args...)
if buf.Bytes()[buf.Len()-1] != '\n' {
buf.WriteByte('\n')
}
self.output(s, buf)
}
func (self *Logger) printfSimple(format string, args ...interface{}) {
buf := self.getBuffer()
fmt.Fprintf(buf, format, args...)
if buf.Bytes()[buf.Len()-1] != '\n' {
buf.WriteByte('\n')
}
self.output(INFO, buf)
}
func (self *Logger) output(s Severity, buf *buffer) {
if self.s < s {
return
}
if self.logToStderr {
os.Stderr.Write(buf.Bytes())
} else {
self.backend.Log(s, buf.Bytes())
}
if s == FATAL {
trace := stacks(true)
os.Stderr.Write(trace)
os.Exit(255)
}
self.putBuffer(buf)
}
func stacks(all bool) []byte {
// We don't know how big the traces are, so grow a few times if they don't fit. Start large, though.
n := 10000
if all {
n = 100000
}
var trace []byte
for i := 0; i < 5; i++ {
trace = make([]byte, n)
nbytes := runtime.Stack(trace, all)
if nbytes < len(trace) {
return trace[:nbytes]
}
n *= 2
}
return trace
}
/*--------------------------logger public functions--------------------------*/
func NewLogger(level interface{}, backend Backend) *Logger {
l := new(Logger)
l.SetSeverity(level)
l.backend = backend
return l
}
func (l *Logger) SetSeverity(level interface{}) {
if s, ok := level.(Severity); ok {
l.s = s
} else {
if s, ok := level.(string); ok {
for i, name := range severityName {
if name == s {
l.s = Severity(i)
}
}
}
}
}
func (l *Logger) Close() {
if l.backend != nil {
l.backend.close()
}
}
func (l *Logger) LogToStderr() {
l.logToStderr = true
}
func (l *Logger) Debug(args ...interface{}) {
l.print(DEBUG, args...)
}
func (l *Logger) Debugf(format string, args ...interface{}) {
l.printf(DEBUG, format, args...)
}
func (l *Logger) Info(args ...interface{}) {
l.print(INFO, args...)
}
func (l *Logger) Infof(format string, args ...interface{}) {
l.printf(INFO, format, args...)
}
func (l *Logger) Warning(args ...interface{}) {
l.print(WARNING, args...)
}
func (l *Logger) Warningf(format string, args ...interface{}) {
l.printf(WARNING, format, args...)
}
func (l *Logger) Error(args ...interface{}) {
l.print(ERROR, args...)
}
|
func (l *Logger) Errorf(format string, args ...interface{}) {
l.printf(ERROR, format, args...)
}
func (l *Logger) Fatal(args ...interface{}) {
l.print(FATAL, args...)
}
func (l *Logger) Fatalf(format string, args ...interface{}) {
l.printf(FATAL, format, args...)
}
func (l *Logger) SetLogging(level interface{}, backend Backend) {
l.SetSeverity(level)
l.backend = backend
}
/////////////////////////////////////////////////////////////////
// depth version, only a low level api
func (l *Logger) LogDepth(s Severity, depth int, format string, args ...interface{}) {
l.printfDepth(s, depth+1, format, args...)
}
func (l *Logger) PrintfSimple(format string, args ...interface{}) {
l.printfSimple(format, args...)
}
/*---------------------------------------------------------------------------*/
var logging Logger
var fileback *FileBackend = nil
var sysback *syslogBackend = nil
func init() {
SetLogging(DEBUG, &stdBackend{})
}
func SetLogging(level interface{}, backend Backend) {
logging.SetLogging(level, backend)
}
func SetSeverity(level interface{}) {
logging.SetSeverity(level)
}
func Close() {
logging.Close()
}
func LogToStderr() {
logging.LogToStderr()
}
/*-----------------------------public functions------------------------------*/
func Debug(args ...interface{}) {
logging.print(DEBUG, args...)
}
func Debugf(format string, args ...interface{}) {
logging.printf(DEBUG, format, args...)
}
func Info(args ...interface{}) {
logging.print(INFO, args...)
}
func Infof(format string, args ...interface{}) {
logging.printf(INFO, format, args...)
}
func Warning(args ...interface{}) {
logging.print(WARNING, args...)
}
func Warningf(format string, args ...interface{}) {
logging.printf(WARNING, format, args...)
}
func Error(args ...interface{}) {
logging.print(ERROR, args...)
}
func Errorf(format string, args ...interface{}) {
logging.printf(ERROR, format, args...)
}
func Fatal(args ...interface{}) {
logging.print(FATAL, args...)
}
func Fatalf(format string, args ...interface{}) {
logging.printf(FATAL, format, args...)
}
func LogDepth(s Severity, depth int, format string, args ...interface{}) {
logging.printfDepth(s, depth+1, format, args...)
}
func Printf(format string, args ...interface{}) {
logging.printfSimple(format, args...)
}
func GetLogger() *Logger {
return &logging
}
| |
create_repos.go
|
package main
import (
"encoding/json"
"bytes"
"io/ioutil"
"fmt"
"errors"
"net/http"
)
type GithubResponse struct {
Message string
Id int `json:"id"`
Name string `json:"name"`
Full_name string `json:"full_name"`
Html_url string `json:"html_url"`
Owner struct {
Login string `json:"login"`
} `json:"owner"`
Source struct {
Id int `json:"id"`
Name string `json:"name"`
Full_name string `json:"full_name"`
Html_url string `json:"html_url"`
Owner struct {
Login string `json:"login"`
} `json:"owner"`
} `json:"source"`
}
type GithubRequestCreateRepos struct {
Name string `json:"name"`
Description string `json:"description"`
}
func
|
(repos_name string, token string) (GithubResponse, error) {
body := GithubResponse{}
api_url := "https://api.github.com/user/repos?access_token=" + token
param := GithubRequestCreateRepos{repos_name, repos_name}
param_string, err := json.Marshal(param)
if err != nil {
return body, errors.New("Marshal Error")
}
fmt.Println(param)
fmt.Println(param_string)
fmt.Println(bytes.NewBuffer(param_string))
res, err := http.Post(api_url, "application/json", bytes.NewBuffer([]byte(param_string)))
if err != nil {
return body, errors.New("Error Create Repos")
}
defer res.Body.Close()
if res.Header.Get("Status") != "201 Created" {
return body, errors.New(res.Header.Get("Status"))
}
bodyBytes, err := ioutil.ReadAll(res.Body)
err = json.Unmarshal(bodyBytes, &body)
if err != nil {
return body, errors.New("Unmarshal Error")
}
return body, nil
}
func main() {
body, err := CreateRepos("jun_lee", "1f8f0f1e16bb4b98e3d5d6113b34a3d8cb6ab8d2")
if err != nil {
panic(err.Error())
}
fmt.Print(body)
}
|
CreateRepos
|
check_build_read_access_handler.go
|
package auth
import (
"context"
"net/http"
"strconv"
"github.com/concourse/atc/api/accessor"
"github.com/concourse/atc/db"
)
type CheckBuildReadAccessHandlerFactory interface {
AnyJobHandler(delegateHandler http.Handler, rejector Rejector) http.Handler
CheckIfPrivateJobHandler(delegateHandler http.Handler, rejector Rejector) http.Handler
}
type checkBuildReadAccessHandlerFactory struct {
buildFactory db.BuildFactory
}
func NewCheckBuildReadAccessHandlerFactory(
buildFactory db.BuildFactory,
) *checkBuildReadAccessHandlerFactory {
return &checkBuildReadAccessHandlerFactory{
buildFactory: buildFactory,
}
}
func (f *checkBuildReadAccessHandlerFactory) AnyJobHandler(
delegateHandler http.Handler,
rejector Rejector,
) http.Handler {
return checkBuildReadAccessHandler{
rejector: rejector,
buildFactory: f.buildFactory,
delegateHandler: delegateHandler,
allowPrivateJob: true,
}
}
func (f *checkBuildReadAccessHandlerFactory) CheckIfPrivateJobHandler(
delegateHandler http.Handler,
rejector Rejector,
) http.Handler {
return checkBuildReadAccessHandler{
rejector: rejector,
buildFactory: f.buildFactory,
delegateHandler: delegateHandler,
allowPrivateJob: false,
}
}
type checkBuildReadAccessHandler struct {
rejector Rejector
buildFactory db.BuildFactory
delegateHandler http.Handler
allowPrivateJob bool
}
func (h checkBuildReadAccessHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
buildIDStr := r.FormValue(":build_id")
buildID, err := strconv.Atoi(buildIDStr)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
build, found, err := h.buildFactory.Build(buildID)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
if !found {
w.WriteHeader(http.StatusNotFound)
return
}
acc := accessor.GetAccessor(r)
if !acc.IsAuthenticated() || !acc.IsAuthorized(build.TeamName()) {
pipeline, found, err := build.Pipeline()
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
if !found {
h.rejector.Unauthorized(w, r)
return
}
if !pipeline.Public() {
if acc.IsAuthenticated() {
h.rejector.Forbidden(w, r)
return
}
h.rejector.Unauthorized(w, r)
return
}
if !h.allowPrivateJob {
job, found, err := pipeline.Job(build.JobName())
if err != nil {
|
w.WriteHeader(http.StatusInternalServerError)
return
}
if !found {
w.WriteHeader(http.StatusNotFound)
return
}
if !job.Config().Public {
if acc.IsAuthenticated() {
h.rejector.Forbidden(w, r)
return
}
h.rejector.Unauthorized(w, r)
return
}
}
}
ctx := context.WithValue(r.Context(), BuildContextKey, build)
h.delegateHandler.ServeHTTP(w, r.WithContext(ctx))
}
| |
errors_test.py
|
import pytest
from docker.errors import APIError
from requests.exceptions import ConnectionError
from compose.cli import errors
from compose.cli.errors import handle_connection_errors
from compose.const import IS_WINDOWS_PLATFORM
from tests import mock
@pytest.yield_fixture
def mock_logging():
with mock.patch('compose.cli.errors.log', autospec=True) as mock_log:
yield mock_log
def patch_find_executable(side_effect):
return mock.patch(
'compose.cli.errors.find_executable',
autospec=True,
side_effect=side_effect)
class TestHandleConnectionErrors(object):
|
def test_generic_connection_error(self, mock_logging):
with pytest.raises(errors.ConnectionError):
with patch_find_executable(['/bin/docker', None]):
with handle_connection_errors(mock.Mock()):
raise ConnectionError()
_, args, _ = mock_logging.error.mock_calls[0]
assert "Couldn't connect to Docker daemon" in args[0]
def test_api_error_version_mismatch(self, mock_logging):
with pytest.raises(errors.ConnectionError):
with handle_connection_errors(mock.Mock(api_version='1.38')):
raise APIError(None, None, b"client is newer than server")
_, args, _ = mock_logging.error.mock_calls[0]
assert "Docker Engine of version 18.06.0 or greater" in args[0]
def test_api_error_version_mismatch_unicode_explanation(self, mock_logging):
with pytest.raises(errors.ConnectionError):
with handle_connection_errors(mock.Mock(api_version='1.38')):
raise APIError(None, None, u"client is newer than server")
_, args, _ = mock_logging.error.mock_calls[0]
assert "Docker Engine of version 18.06.0 or greater" in args[0]
def test_api_error_version_other(self, mock_logging):
msg = b"Something broke!"
with pytest.raises(errors.ConnectionError):
with handle_connection_errors(mock.Mock(api_version='1.22')):
raise APIError(None, None, msg)
mock_logging.error.assert_called_once_with(msg.decode('utf-8'))
def test_api_error_version_other_unicode_explanation(self, mock_logging):
msg = u"Something broke!"
with pytest.raises(errors.ConnectionError):
with handle_connection_errors(mock.Mock(api_version='1.22')):
raise APIError(None, None, msg)
mock_logging.error.assert_called_once_with(msg)
@pytest.mark.skipif(not IS_WINDOWS_PLATFORM, reason='Needs pywin32')
def test_windows_pipe_error_no_data(self, mock_logging):
import pywintypes
with pytest.raises(errors.ConnectionError):
with handle_connection_errors(mock.Mock(api_version='1.22')):
raise pywintypes.error(232, 'WriteFile', 'The pipe is being closed.')
_, args, _ = mock_logging.error.mock_calls[0]
assert "The current Compose file version is not compatible with your engine version." in args[0]
@pytest.mark.skipif(not IS_WINDOWS_PLATFORM, reason='Needs pywin32')
def test_windows_pipe_error_misc(self, mock_logging):
import pywintypes
with pytest.raises(errors.ConnectionError):
with handle_connection_errors(mock.Mock(api_version='1.22')):
raise pywintypes.error(231, 'WriteFile', 'The pipe is busy.')
_, args, _ = mock_logging.error.mock_calls[0]
assert "Windows named pipe error: The pipe is busy. (code: 231)" == args[0]
@pytest.mark.skipif(not IS_WINDOWS_PLATFORM, reason='Needs pywin32')
def test_windows_pipe_error_encoding_issue(self, mock_logging):
import pywintypes
with pytest.raises(errors.ConnectionError):
with handle_connection_errors(mock.Mock(api_version='1.22')):
raise pywintypes.error(9999, 'WriteFile', 'I use weird characters \xe9')
_, args, _ = mock_logging.error.mock_calls[0]
assert 'Windows named pipe error: I use weird characters \xe9 (code: 9999)' == args[0]
|
|
color.rs
|
pub struct Rgba {
pub red: u8,
pub green: u8,
pub blue: u8,
pub alpha: u8,
}
|
pub fn red(&self) -> u8 {
self.red
}
pub fn green(&self) -> u8 {
self.green
}
pub fn blue(&self) -> u8 {
self.blue
}
pub fn alpha(&self) -> u8 {
self.alpha
}
pub fn red_f64(&self) -> f64 {
From::from(self.red)
}
pub fn green_f64(&self) -> f64 {
From::from(self.green)
}
pub fn blue_f64(&self) -> f64 {
From::from(self.blue)
}
pub fn alpha_f64(&self) -> f64 {
From::from(self.alpha)
}
pub fn min_value() -> u8 {
0
}
pub fn min_value_f64() -> f64 {
0.0
}
pub fn max_value() -> u8 {
255
}
pub fn max_value_f64() -> f64 {
255.0
}
}
|
impl Rgba {
|
config.go
|
// Copyright (C) 2019 Orange
//
// This software is distributed under the terms and conditions of the 'Apache License 2.0'
// license which can be found in the file 'License.txt' in this package distribution
// or at 'http://www.apache.org/licenses/LICENSE-2.0'.
|
package prometheus
// Config holds information for configuring the Prometheus exporter
type Config struct {
Namespace string
}
| |
tests.rs
|
// Copyright 2013-2014 Simon Sapin.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::char;
use std::num::from_str_radix;
use std::path;
use super::{UrlParser, Url, SchemeData, RelativeSchemeData, Host};
#[test]
fn url_parsing() {
for test in parse_test_data(include_str!("urltestdata.txt")).into_iter() {
let Test {
input,
base,
scheme: expected_scheme,
username: expected_username,
password: expected_password,
host: expected_host,
port: expected_port,
path: expected_path,
query: expected_query,
fragment: expected_fragment,
expected_failure,
} = test;
let base = match Url::parse(base.as_slice()) {
Ok(base) => base,
Err(message) => panic!("Error parsing base {}: {}", base, message)
};
let url = UrlParser::new().base_url(&base).parse(input.as_slice());
if expected_scheme.is_none() {
if url.is_ok() && !expected_failure {
panic!("Expected a parse error for URL {}", input);
}
continue
}
let Url { scheme, scheme_data, query, fragment, .. } = match url {
Ok(url) => url,
Err(message) => {
if expected_failure {
continue
} else {
panic!("Error parsing URL {}: {}", input, message)
}
}
};
macro_rules! assert_eq {
($a: expr, $b: expr) => {
{
let a = $a;
let b = $b;
if a != b {
if expected_failure {
continue
} else {
panic!("{} != {}", a, b)
}
}
}
}
}
assert_eq!(Some(scheme), expected_scheme);
match scheme_data {
SchemeData::Relative(RelativeSchemeData {
username, password, host, port, default_port: _, path,
}) => {
assert_eq!(username, expected_username);
assert_eq!(password, expected_password);
let host = host.serialize();
assert_eq!(host, expected_host);
assert_eq!(port, expected_port);
assert_eq!(Some(format!("/{}", path.connect("/"))), expected_path);
},
SchemeData::NonRelative(scheme_data) => {
assert_eq!(Some(scheme_data), expected_path);
assert_eq!(String::new(), expected_username);
assert_eq!(None, expected_password);
assert_eq!(String::new(), expected_host);
assert_eq!(None, expected_port);
},
}
fn opt_prepend(prefix: &str, opt_s: Option<String>) -> Option<String> {
opt_s.map(|s| format!("{}{}", prefix, s))
}
assert_eq!(opt_prepend("?", query), expected_query);
assert_eq!(opt_prepend("#", fragment), expected_fragment);
assert!(!expected_failure, "Unexpected success for {}", input);
}
}
struct Test {
input: String,
base: String,
scheme: Option<String>,
username: String,
password: Option<String>,
host: String,
port: Option<u16>,
path: Option<String>,
query: Option<String>,
fragment: Option<String>,
expected_failure: bool,
}
fn parse_test_data(input: &str) -> Vec<Test> {
let mut tests: Vec<Test> = Vec::new();
for line in input.lines() {
if line == "" || line.starts_with("#") {
continue
}
let mut pieces = line.split(' ').collect::<Vec<&str>>();
let expected_failure = pieces[0] == "XFAIL";
if expected_failure {
pieces.remove(0);
}
let input = unescape(pieces.remove(0).unwrap());
let mut test = Test {
input: input,
base: if pieces.is_empty() || pieces[0] == "" {
tests.last().unwrap().base.clone()
} else {
unescape(pieces.remove(0).unwrap())
},
scheme: None,
username: String::new(),
password: None,
host: String::new(),
port: None,
path: None,
query: None,
fragment: None,
expected_failure: expected_failure,
};
for piece in pieces.into_iter() {
if piece == "" || piece.starts_with("#") {
continue
}
let colon = piece.find(':').unwrap();
let value = unescape(piece.slice_from(colon + 1));
match piece.slice_to(colon) {
"s" => test.scheme = Some(value),
"u" => test.username = value,
"pass" => test.password = Some(value),
"h" => test.host = value,
"port" => test.port = Some(value.parse().unwrap()),
"p" => test.path = Some(value),
"q" => test.query = Some(value),
"f" => test.fragment = Some(value),
_ => panic!("Invalid token")
}
}
tests.push(test)
}
tests
}
fn unescape(input: &str) -> String {
let mut output = String::new();
let mut chars = input.chars();
loop {
match chars.next() {
None => return output,
Some(c) => output.push(
if c == '\\' {
match chars.next().unwrap() {
'\\' => '\\',
'n' => '\n',
'r' => '\r',
's' => ' ',
't' => '\t',
'f' => '\x0C',
'u' => {
let mut hex = String::new();
hex.push(chars.next().unwrap());
hex.push(chars.next().unwrap());
hex.push(chars.next().unwrap());
hex.push(chars.next().unwrap());
from_str_radix(hex.as_slice(), 16)
.and_then(char::from_u32).unwrap()
}
_ => panic!("Invalid test data input"),
}
} else {
c
}
)
}
}
}
#[test]
fn file_paths() {
assert_eq!(Url::from_file_path(&path::posix::Path::new("relative")), Err(()));
assert_eq!(Url::from_file_path(&path::posix::Path::new("../relative")), Err(()));
assert_eq!(Url::from_file_path(&path::windows::Path::new("relative")), Err(()));
assert_eq!(Url::from_file_path(&path::windows::Path::new(r"..\relative")), Err(()));
assert_eq!(Url::from_file_path(&path::windows::Path::new(r"\drive-relative")), Err(()));
assert_eq!(Url::from_file_path(&path::windows::Path::new(r"\\ucn\")), Err(()));
let mut url = Url::from_file_path(&path::posix::Path::new("/foo/bar")).unwrap();
assert_eq!(url.host(), Some(&Host::Domain("".to_string())));
assert_eq!(url.path(), Some(["foo".to_string(), "bar".to_string()].as_slice()));
assert!(url.to_file_path() == Ok(path::posix::Path::new("/foo/bar")));
url.path_mut().unwrap()[1] = "ba\0r".to_string();
assert!(url.to_file_path::<path::posix::Path>() == Err(()));
url.path_mut().unwrap()[1] = "ba%00r".to_string();
assert!(url.to_file_path::<path::posix::Path>() == Err(()));
// Invalid UTF-8
url.path_mut().unwrap()[1] = "ba%80r".to_string();
assert!(url.to_file_path() == Ok(path::posix::Path::new(
/* note: byte string, invalid UTF-8 */ b"/foo/ba\x80r")));
let mut url = Url::from_file_path(&path::windows::Path::new(r"C:\foo\bar")).unwrap();
assert_eq!(url.host(), Some(&Host::Domain("".to_string())));
assert_eq!(url.path(), Some(["C:".to_string(), "foo".to_string(), "bar".to_string()].as_slice()));
assert!(url.to_file_path::<path::windows::Path>()
== Ok(path::windows::Path::new(r"C:\foo\bar")));
url.path_mut().unwrap()[2] = "ba\0r".to_string();
assert!(url.to_file_path::<path::windows::Path>() == Err(()));
url.path_mut().unwrap()[2] = "ba%00r".to_string();
assert!(url.to_file_path::<path::windows::Path>() == Err(()));
// Invalid UTF-8
url.path_mut().unwrap()[2] = "ba%80r".to_string();
assert!(url.to_file_path::<path::windows::Path>() == Err(()));
}
#[test]
fn directory_paths()
|
{
assert_eq!(Url::from_directory_path(&path::posix::Path::new("relative")), Err(()));
assert_eq!(Url::from_directory_path(&path::posix::Path::new("../relative")), Err(()));
assert_eq!(Url::from_directory_path(&path::windows::Path::new("relative")), Err(()));
assert_eq!(Url::from_directory_path(&path::windows::Path::new(r"..\relative")), Err(()));
assert_eq!(Url::from_directory_path(&path::windows::Path::new(r"\drive-relative")), Err(()));
assert_eq!(Url::from_directory_path(&path::windows::Path::new(r"\\ucn\")), Err(()));
let url = Url::from_directory_path(&path::posix::Path::new("/foo/bar")).unwrap();
assert_eq!(url.host(), Some(&Host::Domain("".to_string())));
assert_eq!(url.path(), Some(["foo".to_string(), "bar".to_string(), "".to_string()].as_slice()));
let url = Url::from_directory_path(&path::windows::Path::new(r"C:\foo\bar")).unwrap();
assert_eq!(url.host(), Some(&Host::Domain("".to_string())));
assert_eq!(url.path(), Some([
"C:".to_string(), "foo".to_string(), "bar".to_string(), "".to_string()].as_slice()));
}
|
|
logging_config.pb.go
|
// Code generated by protoc-gen-go. DO NOT EDIT.
// source: google/logging/v2/logging_config.proto
package logging
import proto "github.com/golang/protobuf/proto"
import fmt "fmt"
import math "math"
import _ "google.golang.org/genproto/googleapis/api/annotations"
import google_protobuf5 "github.com/golang/protobuf/ptypes/empty"
import google_protobuf6 "google.golang.org/genproto/protobuf/field_mask"
import google_protobuf4 "github.com/golang/protobuf/ptypes/timestamp"
import (
context "golang.org/x/net/context"
grpc "google.golang.org/grpc"
)
// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf
// Available log entry formats. Log entries can be written to Stackdriver
// Logging in either format and can be exported in either format.
// Version 2 is the preferred format.
type LogSink_VersionFormat int32
const (
// An unspecified format version that will default to V2.
LogSink_VERSION_FORMAT_UNSPECIFIED LogSink_VersionFormat = 0
// `LogEntry` version 2 format.
LogSink_V2 LogSink_VersionFormat = 1
// `LogEntry` version 1 format.
LogSink_V1 LogSink_VersionFormat = 2
)
var LogSink_VersionFormat_name = map[int32]string{
0: "VERSION_FORMAT_UNSPECIFIED",
1: "V2",
2: "V1",
}
var LogSink_VersionFormat_value = map[string]int32{
"VERSION_FORMAT_UNSPECIFIED": 0,
"V2": 1,
"V1": 2,
}
func (x LogSink_VersionFormat) String() string {
return proto.EnumName(LogSink_VersionFormat_name, int32(x))
}
func (LogSink_VersionFormat) EnumDescriptor() ([]byte, []int) { return fileDescriptor2, []int{0, 0} }
// Describes a sink used to export log entries to one of the following
// destinations in any project: a Cloud Storage bucket, a BigQuery dataset, or a
// Cloud Pub/Sub topic. A logs filter controls which log entries are
// exported. The sink must be created within a project, organization, billing
// account, or folder.
type LogSink struct {
// Required. The client-assigned sink identifier, unique within the
// project. Example: `"my-syslog-errors-to-pubsub"`. Sink identifiers are
// limited to 100 characters and can include only the following characters:
// upper and lower-case alphanumeric characters, underscores, hyphens, and
// periods.
Name string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"`
// Required. The export destination:
//
// "storage.googleapis.com/[GCS_BUCKET]"
// "bigquery.googleapis.com/projects/[PROJECT_ID]/datasets/[DATASET]"
// "pubsub.googleapis.com/projects/[PROJECT_ID]/topics/[TOPIC_ID]"
//
// The sink's `writer_identity`, set when the sink is created, must
// have permission to write to the destination or else the log
// entries are not exported. For more information, see
// [Exporting Logs With Sinks](/logging/docs/api/tasks/exporting-logs).
Destination string `protobuf:"bytes,3,opt,name=destination" json:"destination,omitempty"`
// Optional.
// An [advanced logs filter](/logging/docs/view/advanced_filters). The only
// exported log entries are those that are in the resource owning the sink and
// that match the filter. The filter must use the log entry format specified
// by the `output_version_format` parameter. For example, in the v2 format:
//
// logName="projects/[PROJECT_ID]/logs/[LOG_ID]" AND severity>=ERROR
Filter string `protobuf:"bytes,5,opt,name=filter" json:"filter,omitempty"`
// Deprecated. The log entry format to use for this sink's exported log
// entries. The v2 format is used by default and cannot be changed.
OutputVersionFormat LogSink_VersionFormat `protobuf:"varint,6,opt,name=output_version_format,json=outputVersionFormat,enum=google.logging.v2.LogSink_VersionFormat" json:"output_version_format,omitempty"`
// Output only. An IAM identity—a service account or group—under
// which Stackdriver Logging writes the exported log entries to the sink's
// destination. This field is set by
// [sinks.create](/logging/docs/api/reference/rest/v2/projects.sinks/create)
// and
// [sinks.update](/logging/docs/api/reference/rest/v2/projects.sinks/update),
// based on the setting of `unique_writer_identity` in those methods.
//
// Until you grant this identity write-access to the destination, log entry
// exports from this sink will fail. For more information,
// see [Granting access for a
// resource](/iam/docs/granting-roles-to-service-accounts#granting_access_to_a_service_account_for_a_resource).
// Consult the destination service's documentation to determine the
// appropriate IAM roles to assign to the identity.
WriterIdentity string `protobuf:"bytes,8,opt,name=writer_identity,json=writerIdentity" json:"writer_identity,omitempty"`
// Optional. This field applies only to sinks owned by organizations and
// folders. If the field is false, the default, only the logs owned by the
// sink's parent resource are available for export. If the field is true, then
// logs from all the projects, folders, and billing accounts contained in the
// sink's parent resource are also available for export. Whether a particular
// log entry from the children is exported depends on the sink's filter
// expression. For example, if this field is true, then the filter
// `resource.type=gce_instance` would export all Compute Engine VM instance
// log entries from all projects in the sink's parent. To only export entries
// from certain child projects, filter on the project part of the log name:
//
// logName:("projects/test-project1/" OR "projects/test-project2/") AND
// resource.type=gce_instance
IncludeChildren bool `protobuf:"varint,9,opt,name=include_children,json=includeChildren" json:"include_children,omitempty"`
// Optional. The time at which this sink will begin exporting log entries.
// Log entries are exported only if their timestamp is not earlier than the
// start time. The default value of this field is the time the sink is
// created or updated.
StartTime *google_protobuf4.Timestamp `protobuf:"bytes,10,opt,name=start_time,json=startTime" json:"start_time,omitempty"`
// Optional. The time at which this sink will stop exporting log entries. Log
// entries are exported only if their timestamp is earlier than the end time.
// If this field is not supplied, there is no end time. If both a start time
// and an end time are provided, then the end time must be later than the
// start time.
EndTime *google_protobuf4.Timestamp `protobuf:"bytes,11,opt,name=end_time,json=endTime" json:"end_time,omitempty"`
}
func (m *LogSink) Reset() { *m = LogSink{} }
func (m *LogSink) String() string { return proto.CompactTextString(m) }
func (*LogSink) ProtoMessage() {}
func (*LogSink) Descriptor() ([]byte, []int) { return fileDescriptor2, []int{0} }
func (m *LogSink) GetName() string {
if m != nil {
return m.Name
}
return ""
}
func (m *LogSink) GetDestination() string {
if m != nil {
return m.Destination
}
return ""
}
func (m *LogSink) GetFilter() string {
if m != nil {
return m.Filter
}
return ""
}
func (m *LogSink) GetOutputVersionFormat() LogSink_VersionFormat {
if m != nil {
return m.OutputVersionFormat
}
return LogSink_VERSION_FORMAT_UNSPECIFIED
}
func (m *LogSink) GetWriterIdentity() string {
if m != nil {
return m.WriterIdentity
}
return ""
}
func (m *LogSink) GetIncludeChildren() bool {
if m != nil {
return m.IncludeChildren
}
return false
}
func (m *LogSink) GetStartTime() *google_protobuf4.Timestamp {
if m != nil {
return m.StartTime
}
return nil
}
func (m *LogSink) GetEndTime() *google_protobuf4.Timestamp {
if m != nil {
return m.EndTime
}
return nil
}
// The parameters to `ListSinks`.
type ListSinksRequest struct {
// Required. The parent resource whose sinks are to be listed:
//
// "projects/[PROJECT_ID]"
// "organizations/[ORGANIZATION_ID]"
// "billingAccounts/[BILLING_ACCOUNT_ID]"
// "folders/[FOLDER_ID]"
Parent string `protobuf:"bytes,1,opt,name=parent" json:"parent,omitempty"`
// Optional. If present, then retrieve the next batch of results from the
// preceding call to this method. `pageToken` must be the value of
// `nextPageToken` from the previous response. The values of other method
// parameters should be identical to those in the previous call.
PageToken string `protobuf:"bytes,2,opt,name=page_token,json=pageToken" json:"page_token,omitempty"`
// Optional. The maximum number of results to return from this request.
// Non-positive values are ignored. The presence of `nextPageToken` in the
// response indicates that more results might be available.
PageSize int32 `protobuf:"varint,3,opt,name=page_size,json=pageSize" json:"page_size,omitempty"`
}
func (m *ListSinksRequest) Reset() { *m = ListSinksRequest{} }
func (m *ListSinksRequest) String() string { return proto.CompactTextString(m) }
func (*ListSinksRequest) ProtoMessage() {}
func (*ListSinksRequest) Descriptor() ([]byte, []int) { return fileDescriptor2, []int{1} }
func (m *ListSinksRequest) GetParent() string {
if m != nil {
return m.Parent
}
return ""
}
func (m *ListSinksRequest) GetPageToken() string {
if m != nil {
return m.PageToken
}
return ""
}
func (m *ListSinksRequest) GetPageSize() int32 {
if m != nil {
return m.PageSize
}
return 0
}
// Result returned from `ListSinks`.
type ListSinksResponse struct {
// A list of sinks.
Sinks []*LogSink `protobuf:"bytes,1,rep,name=sinks" json:"sinks,omitempty"`
// If there might be more results than appear in this response, then
// `nextPageToken` is included. To get the next set of results, call the same
// method again using the value of `nextPageToken` as `pageToken`.
NextPageToken string `protobuf:"bytes,2,opt,name=next_page_token,json=nextPageToken" json:"next_page_token,omitempty"`
}
func (m *ListSinksResponse) Reset() { *m = ListSinksResponse{} }
func (m *ListSinksResponse) String() string { return proto.CompactTextString(m) }
func (*ListSinksResponse) ProtoMessage() {}
func (*ListSinksResponse) Descriptor() ([]byte, []int) { return fileDescriptor2, []int{2} }
func (m *ListSinksResponse) GetSinks() []*LogSink {
if m != nil {
return m.Sinks
}
return nil
}
func (m *ListSinksResponse) GetNextPageToken() string {
if m != nil {
return m.NextPageToken
}
return ""
}
// The parameters to `GetSink`.
type GetSinkRequest struct {
// Required. The resource name of the sink:
//
// "projects/[PROJECT_ID]/sinks/[SINK_ID]"
// "organizations/[ORGANIZATION_ID]/sinks/[SINK_ID]"
// "billingAccounts/[BILLING_ACCOUNT_ID]/sinks/[SINK_ID]"
// "folders/[FOLDER_ID]/sinks/[SINK_ID]"
//
// Example: `"projects/my-project-id/sinks/my-sink-id"`.
SinkName string `protobuf:"bytes,1,opt,name=sink_name,json=sinkName" json:"sink_name,omitempty"`
}
func (m *GetSinkRequest) Reset() { *m = GetSinkRequest{} }
func (m *GetSinkRequest) String() string { return proto.CompactTextString(m) }
func (*GetSinkRequest) ProtoMessage() {}
func (*GetSinkRequest) Descriptor() ([]byte, []int) { return fileDescriptor2, []int{3} }
func (m *GetSinkRequest) GetSinkName() string {
if m != nil {
return m.SinkName
}
return ""
}
// The parameters to `CreateSink`.
type CreateSinkRequest struct {
// Required. The resource in which to create the sink:
//
// "projects/[PROJECT_ID]"
// "organizations/[ORGANIZATION_ID]"
// "billingAccounts/[BILLING_ACCOUNT_ID]"
// "folders/[FOLDER_ID]"
//
// Examples: `"projects/my-logging-project"`, `"organizations/123456789"`.
Parent string `protobuf:"bytes,1,opt,name=parent" json:"parent,omitempty"`
// Required. The new sink, whose `name` parameter is a sink identifier that
// is not already in use.
Sink *LogSink `protobuf:"bytes,2,opt,name=sink" json:"sink,omitempty"`
// Optional. Determines the kind of IAM identity returned as `writer_identity`
// in the new sink. If this value is omitted or set to false, and if the
// sink's parent is a project, then the value returned as `writer_identity` is
// the same group or service account used by Stackdriver Logging before the
// addition of writer identities to this API. The sink's destination must be
// in the same project as the sink itself.
//
// If this field is set to true, or if the sink is owned by a non-project
// resource such as an organization, then the value of `writer_identity` will
// be a unique service account used only for exports from the new sink. For
// more information, see `writer_identity` in [LogSink][google.logging.v2.LogSink].
UniqueWriterIdentity bool `protobuf:"varint,3,opt,name=unique_writer_identity,json=uniqueWriterIdentity" json:"unique_writer_identity,omitempty"`
}
func (m *CreateSinkRequest) Reset() { *m = CreateSinkRequest{} }
func (m *CreateSinkRequest) String() string { return proto.CompactTextString(m) }
func (*CreateSinkRequest) ProtoMessage() {}
func (*CreateSinkRequest) Descriptor() ([]byte, []int) { return fileDescriptor2, []int{4} }
func (m *CreateSinkRequest) GetParent() string {
if m != nil {
return m.Parent
}
return ""
}
func (m *CreateSinkRequest) GetSink() *LogSink {
if m != nil {
return m.Sink
}
return nil
}
func (m *CreateSinkRequest) GetUniqueWriterIdentity() bool {
if m != nil {
return m.UniqueWriterIdentity
}
return false
}
// The parameters to `UpdateSink`.
type UpdateSinkRequest struct {
// Required. The full resource name of the sink to update, including the
// parent resource and the sink identifier:
//
// "projects/[PROJECT_ID]/sinks/[SINK_ID]"
// "organizations/[ORGANIZATION_ID]/sinks/[SINK_ID]"
// "billingAccounts/[BILLING_ACCOUNT_ID]/sinks/[SINK_ID]"
// "folders/[FOLDER_ID]/sinks/[SINK_ID]"
//
// Example: `"projects/my-project-id/sinks/my-sink-id"`.
SinkName string `protobuf:"bytes,1,opt,name=sink_name,json=sinkName" json:"sink_name,omitempty"`
// Required. The updated sink, whose name is the same identifier that appears
// as part of `sink_name`.
Sink *LogSink `protobuf:"bytes,2,opt,name=sink" json:"sink,omitempty"`
// Optional. See
// [sinks.create](/logging/docs/api/reference/rest/v2/projects.sinks/create)
// for a description of this field. When updating a sink, the effect of this
// field on the value of `writer_identity` in the updated sink depends on both
// the old and new values of this field:
//
// + If the old and new values of this field are both false or both true,
// then there is no change to the sink's `writer_identity`.
// + If the old value is false and the new value is true, then
// `writer_identity` is changed to a unique service account.
// + It is an error if the old value is true and the new value is
// set to false or defaulted to false.
UniqueWriterIdentity bool `protobuf:"varint,3,opt,name=unique_writer_identity,json=uniqueWriterIdentity" json:"unique_writer_identity,omitempty"`
}
func (m *UpdateSinkRequest) Reset() { *m = UpdateSinkRequest{} }
func (m *UpdateSinkRequest) String() string { return proto.CompactTextString(m) }
func (*UpdateSinkRequest) ProtoMessage() {}
func (*UpdateSinkRequest) Descriptor() ([]byte, []int) { return fileDescriptor2, []int{5} }
func (m *UpdateSinkRequest) GetSinkName() string {
if m != nil {
return m.SinkName
}
return ""
}
func (m *UpdateSinkRequest) GetSink() *LogSink {
if m != nil {
return m.Sink
}
return nil
}
func (m *UpdateSinkRequest) GetUniqueWriterIdentity() bool {
if m != nil {
return m.UniqueWriterIdentity
}
return false
}
// The parameters to `DeleteSink`.
type DeleteSinkRequest struct {
// Required. The full resource name of the sink to delete, including the
// parent resource and the sink identifier:
//
// "projects/[PROJECT_ID]/sinks/[SINK_ID]"
// "organizations/[ORGANIZATION_ID]/sinks/[SINK_ID]"
// "billingAccounts/[BILLING_ACCOUNT_ID]/sinks/[SINK_ID]"
// "folders/[FOLDER_ID]/sinks/[SINK_ID]"
//
// Example: `"projects/my-project-id/sinks/my-sink-id"`.
SinkName string `protobuf:"bytes,1,opt,name=sink_name,json=sinkName" json:"sink_name,omitempty"`
}
func (m *DeleteSinkRequest) Reset() { *m = DeleteSinkRequest{} }
func (m *DeleteSinkRequest) String() string { return proto.CompactTextString(m) }
func (*DeleteSinkRequest) ProtoMessage() {}
func (*DeleteSinkRequest) Descriptor() ([]byte, []int) { return fileDescriptor2, []int{6} }
func (m *DeleteSinkRequest) GetSinkName() string {
if m != nil {
return m.SinkName
}
return ""
}
// Specifies a set of log entries that are not to be stored in Stackdriver
// Logging. If your project receives a large volume of logs, you might be able
// to use exclusions to reduce your chargeable logs. Exclusions are processed
// after log sinks, so you can export log entries before they are excluded.
// Audit log entries and log entries from Amazon Web Services are never
// excluded.
type LogExclusion struct {
// Required. A client-assigned identifier, such as
// `"load-balancer-exclusion"`. Identifiers are limited to 100 characters and
// can include only letters, digits, underscores, hyphens, and periods.
Name string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"`
// Optional. A description of this exclusion.
Description string `protobuf:"bytes,2,opt,name=description" json:"description,omitempty"`
// Required.
// An [advanced logs filter](/logging/docs/view/advanced_filters)
// that matches the log entries to be excluded. By using the
// [sample function](/logging/docs/view/advanced_filters#sample),
// you can exclude less than 100% of the matching log entries.
// For example, the following filter matches 99% of low-severity log
// entries from load balancers:
//
// "resource.type=http_load_balancer severity<ERROR sample(insertId, 0.99)"
Filter string `protobuf:"bytes,3,opt,name=filter" json:"filter,omitempty"`
// Optional. If set to True, then this exclusion is disabled and it does not
// exclude any log entries. You can use
// [exclusions.patch](/logging/docs/alpha-exclusion/docs/reference/v2/rest/v2/projects.exclusions/patch)
// to change the value of this field.
Disabled bool `protobuf:"varint,4,opt,name=disabled" json:"disabled,omitempty"`
}
func (m *LogExclusion) Reset() { *m = LogExclusion{} }
func (m *LogExclusion) String() string { return proto.CompactTextString(m) }
func (*LogExclusion) ProtoMessage() {}
func (*LogExclusion) Descriptor() ([]byte, []int) { return fileDescriptor2, []int{7} }
func (m *LogExclusion) GetName() string {
if m != nil {
return m.Name
}
return ""
}
func (m *LogExclusion) GetDescription() string {
if m != nil {
return m.Description
}
return ""
}
func (m *LogExclusion) GetFilter() string {
if m != nil {
return m.Filter
}
return ""
}
func (m *LogExclusion) GetDisabled() bool {
if m != nil {
return m.Disabled
}
return false
}
// The parameters to `ListExclusions`.
type ListExclusionsRequest struct {
// Required. The parent resource whose exclusions are to be listed.
//
// "projects/[PROJECT_ID]"
// "organizations/[ORGANIZATION_ID]"
// "billingAccounts/[BILLING_ACCOUNT_ID]"
// "folders/[FOLDER_ID]"
Parent string `protobuf:"bytes,1,opt,name=parent" json:"parent,omitempty"`
// Optional. If present, then retrieve the next batch of results from the
// preceding call to this method. `pageToken` must be the value of
// `nextPageToken` from the previous response. The values of other method
// parameters should be identical to those in the previous call.
PageToken string `protobuf:"bytes,2,opt,name=page_token,json=pageToken" json:"page_token,omitempty"`
// Optional. The maximum number of results to return from this request.
// Non-positive values are ignored. The presence of `nextPageToken` in the
// response indicates that more results might be available.
PageSize int32 `protobuf:"varint,3,opt,name=page_size,json=pageSize" json:"page_size,omitempty"`
}
func (m *ListExclusionsRequest) Reset() { *m = ListExclusionsRequest{} }
func (m *ListExclusionsRequest) String() string { return proto.CompactTextString(m) }
func (*ListExclusionsRequest) ProtoMessage() {}
func (*ListExclusionsRequest) Descriptor() ([]byte, []int) { return fileDescriptor2, []int{8} }
func (m *ListExclusionsRequest) GetParent() string {
if m != nil {
return m.Parent
}
return ""
}
func (m *ListExclusionsRequest) GetPageToken() string {
if m != nil {
return m.PageToken
}
return ""
}
func (m *ListExclusionsRequest) GetPageSize() int32 {
if m != nil {
return m.PageSize
}
return 0
}
// Result returned from `ListExclusions`.
type ListExclusionsResponse struct {
// A list of exclusions.
Exclusions []*LogExclusion `protobuf:"bytes,1,rep,name=exclusions" json:"exclusions,omitempty"`
// If there might be more results than appear in this response, then
// `nextPageToken` is included. To get the next set of results, call the same
// method again using the value of `nextPageToken` as `pageToken`.
NextPageToken string `protobuf:"bytes,2,opt,name=next_page_token,json=nextPageToken" json:"next_page_token,omitempty"`
}
func (m *ListExclusionsResponse) Reset() { *m = ListExclusionsResponse{} }
func (m *ListExclusionsResponse) String() string { return proto.CompactTextString(m) }
func (*ListExclusionsResponse) ProtoMessage() {}
func (*ListExclusionsResponse) Descriptor() ([]byte, []int) { return fileDescriptor2, []int{9} }
func (m *ListExclusionsResponse) GetExclusions() []*LogExclusion {
if m != nil {
return m.Exclusions
}
return nil
}
func (m *ListExclusionsResponse) GetNextPageToken() string {
if m != nil {
return m.NextPageToken
}
return ""
}
// The parameters to `GetExclusion`.
type GetExclusionRequest struct {
// Required. The resource name of an existing exclusion:
//
// "projects/[PROJECT_ID]/exclusions/[EXCLUSION_ID]"
// "organizations/[ORGANIZATION_ID]/exclusions/[EXCLUSION_ID]"
// "billingAccounts/[BILLING_ACCOUNT_ID]/exclusions/[EXCLUSION_ID]"
// "folders/[FOLDER_ID]/exclusions/[EXCLUSION_ID]"
//
// Example: `"projects/my-project-id/exclusions/my-exclusion-id"`.
Name string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"`
}
func (m *GetExclusionRequest) Reset() { *m = GetExclusionRequest{} }
func (m *GetExclusionRequest) String() string { return proto.CompactTextString(m) }
func (*GetExclusionRequest) ProtoMessage() {}
func (*GetExclusionRequest) Descriptor() ([]byte, []int) { return fileDescriptor2, []int{10} }
func (m *GetExclusionRequest) GetName() string {
if m != nil {
return m.Name
}
return ""
}
// The parameters to `CreateExclusion`.
type CreateExclusionRequest struct {
// Required. The parent resource in which to create the exclusion:
//
// "projects/[PROJECT_ID]"
// "organizations/[ORGANIZATION_ID]"
// "billingAccounts/[BILLING_ACCOUNT_ID]"
// "folders/[FOLDER_ID]"
//
// Examples: `"projects/my-logging-project"`, `"organizations/123456789"`.
Parent string `protobuf:"bytes,1,opt,name=parent" json:"parent,omitempty"`
// Required. The new exclusion, whose `name` parameter is an exclusion name
// that is not already used in the parent resource.
Exclusion *LogExclusion `protobuf:"bytes,2,opt,name=exclusion" json:"exclusion,omitempty"`
}
func (m *CreateExclusionRequest) Reset() { *m = CreateExclusionRequest{} }
func (m *CreateExclusionRequest) String() string { return proto.CompactTextString(m) }
func (*CreateExclusionRequest) ProtoMessage() {}
func (*CreateExclusionRequest) Descriptor() ([]byte, []int) { return fileDescriptor2, []int{11} }
func (m *CreateExclusionRequest) GetParent() string {
if m != nil {
return m.Parent
}
return ""
}
func (m *CreateExclusionRequest) GetExclusion() *LogExclusion {
if m != nil {
return m.Exclusion
}
return nil
}
// The parameters to `UpdateExclusion`.
type UpdateExclusionRequest struct {
// Required. The resource name of the exclusion to update:
//
// "projects/[PROJECT_ID]/exclusions/[EXCLUSION_ID]"
// "organizations/[ORGANIZATION_ID]/exclusions/[EXCLUSION_ID]"
// "billingAccounts/[BILLING_ACCOUNT_ID]/exclusions/[EXCLUSION_ID]"
// "folders/[FOLDER_ID]/exclusions/[EXCLUSION_ID]"
//
// Example: `"projects/my-project-id/exclusions/my-exclusion-id"`.
Name string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"`
// Required. New values for the existing exclusion. Only the fields specified
// in `update_mask` are relevant.
Exclusion *LogExclusion `protobuf:"bytes,2,opt,name=exclusion" json:"exclusion,omitempty"`
// Required. A nonempty list of fields to change in the existing exclusion.
// New values for the fields are taken from the corresponding fields in the
// [LogExclusion][google.logging.v2.LogExclusion] included in this request. Fields not mentioned in
// `update_mask` are not changed and are ignored in the request.
//
// For example, to change the filter and description of an exclusion,
// specify an `update_mask` of `"filter,description"`.
UpdateMask *google_protobuf6.FieldMask `protobuf:"bytes,3,opt,name=update_mask,json=updateMask" json:"update_mask,omitempty"`
}
func (m *UpdateExclusionRequest) Reset() { *m = UpdateExclusionRequest{} }
func (m *UpdateExclusionRequest) String() string { return proto.CompactTextString(m) }
func (*UpdateExclusionRequest) ProtoMessage() {}
func (*UpdateExclusionRequest) Descriptor() ([]byte, []int) { return fileDescriptor2, []int{12} }
func (m *UpdateExclusionRequest) GetName() string {
if m != nil {
return m.Name
}
return ""
}
func (m *UpdateExclusionRequest) GetExclusion() *LogExclusion {
if m != nil {
return m.Exclusion
}
return nil
}
func (m *UpdateExclusionRequest) GetUpdateMask() *google_protobuf6.FieldMask {
if m != nil {
return m.UpdateMask
}
return nil
}
// The parameters to `DeleteExclusion`.
type DeleteExclusionRequest struct {
// Required. The resource name of an existing exclusion to delete:
//
// "projects/[PROJECT_ID]/exclusions/[EXCLUSION_ID]"
// "organizations/[ORGANIZATION_ID]/exclusions/[EXCLUSION_ID]"
// "billingAccounts/[BILLING_ACCOUNT_ID]/exclusions/[EXCLUSION_ID]"
// "folders/[FOLDER_ID]/exclusions/[EXCLUSION_ID]"
//
// Example: `"projects/my-project-id/exclusions/my-exclusion-id"`.
Name string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"`
}
func (m *DeleteExclusionRequest) Reset() { *m = DeleteExclusionRequest{} }
func (m *DeleteExclusionRequest) String() string { return proto.CompactTextString(m) }
func (*DeleteExclusionRequest) ProtoMessage() {}
func (*DeleteExclusionRequest) Descriptor() ([]byte, []int) { return fileDescriptor2, []int{13} }
func (m *DeleteExclusionRequest) GetName() string {
if m != nil {
return m.Name
}
return ""
}
func init() {
proto.RegisterType((*LogSink)(nil), "google.logging.v2.LogSink")
proto.RegisterType((*ListSinksRequest)(nil), "google.logging.v2.ListSinksRequest")
proto.RegisterType((*ListSinksResponse)(nil), "google.logging.v2.ListSinksResponse")
proto.RegisterType((*GetSinkRequest)(nil), "google.logging.v2.GetSinkRequest")
proto.RegisterType((*CreateSinkRequest)(nil), "google.logging.v2.CreateSinkRequest")
proto.RegisterType((*UpdateSinkRequest)(nil), "google.logging.v2.UpdateSinkRequest")
proto.RegisterType((*DeleteSinkRequest)(nil), "google.logging.v2.DeleteSinkRequest")
proto.RegisterType((*LogExclusion)(nil), "google.logging.v2.LogExclusion")
proto.RegisterType((*ListExclusionsRequest)(nil), "google.logging.v2.ListExclusionsRequest")
proto.RegisterType((*ListExclusionsResponse)(nil), "google.logging.v2.ListExclusionsResponse")
proto.RegisterType((*GetExclusionRequest)(nil), "google.logging.v2.GetExclusionRequest")
proto.RegisterType((*CreateExclusionRequest)(nil), "google.logging.v2.CreateExclusionRequest")
proto.RegisterType((*UpdateExclusionRequest)(nil), "google.logging.v2.UpdateExclusionRequest")
proto.RegisterType((*DeleteExclusionRequest)(nil), "google.logging.v2.DeleteExclusionRequest")
proto.RegisterEnum("google.logging.v2.LogSink_VersionFormat", LogSink_VersionFormat_name, LogSink_VersionFormat_value)
}
// Reference imports to suppress errors if they are not otherwise used.
var _ context.Context
var _ grpc.ClientConn
// This is a compile-time assertion to ensure that this generated file
// is compatible with the grpc package it is being compiled against.
const _ = grpc.SupportPackageIsVersion4
// Client API for ConfigServiceV2 service
type ConfigServiceV2Client interface {
// Lists sinks.
ListSinks(ctx context.Context, in *ListSinksRequest, opts ...grpc.CallOption) (*ListSinksResponse, error)
// Gets a sink.
GetSink(ctx context.Context, in *GetSinkRequest, opts ...grpc.CallOption) (*LogSink, error)
// Creates a sink that exports specified log entries to a destination. The
// export of newly-ingested log entries begins immediately, unless the current
// time is outside the sink's start and end times or the sink's
// `writer_identity` is not permitted to write to the destination. A sink can
// export log entries only from the resource owning the sink.
CreateSink(ctx context.Context, in *CreateSinkRequest, opts ...grpc.CallOption) (*LogSink, error)
// Updates a sink. This method replaces the following fields in the existing
// sink with values from the new sink: `destination`, `filter`,
// `output_version_format`, `start_time`, and `end_time`.
// The updated sink might also have a new `writer_identity`; see the
// `unique_writer_identity` field.
UpdateSink(ctx context.Context, in *UpdateSinkRequest, opts ...grpc.CallOption) (*LogSink, error)
// Deletes a sink. If the sink has a unique `writer_identity`, then that
// service account is also deleted.
DeleteSink(ctx context.Context, in *DeleteSinkRequest, opts ...grpc.CallOption) (*google_protobuf5.Empty, error)
// Lists all the exclusions in a parent resource.
ListExclusions(ctx context.Context, in *ListExclusionsRequest, opts ...grpc.CallOption) (*ListExclusionsResponse, error)
// Gets the description of an exclusion.
GetExclusion(ctx context.Context, in *GetExclusionRequest, opts ...grpc.CallOption) (*LogExclusion, error)
// Creates a new exclusion in a specified parent resource.
// Only log entries belonging to that resource can be excluded.
// You can have up to 10 exclusions in a resource.
CreateExclusion(ctx context.Context, in *CreateExclusionRequest, opts ...grpc.CallOption) (*LogExclusion, error)
// Changes one or more properties of an existing exclusion.
UpdateExclusion(ctx context.Context, in *UpdateExclusionRequest, opts ...grpc.CallOption) (*LogExclusion, error)
// Deletes an exclusion.
DeleteExclusion(ctx context.Context, in *DeleteExclusionRequest, opts ...grpc.CallOption) (*google_protobuf5.Empty, error)
}
type configServiceV2Client struct {
cc *grpc.ClientConn
}
func NewConfigServiceV2Client(cc *grpc.ClientConn) ConfigServiceV2Client {
return &configServiceV2Client{cc}
}
func (c *configServiceV2Client) ListSinks(ctx context.Context, in *ListSinksRequest, opts ...grpc.CallOption) (*ListSinksResponse, error) {
out := new(ListSinksResponse)
err := grpc.Invoke(ctx, "/google.logging.v2.ConfigServiceV2/ListSinks", in, out, c.cc, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *configServiceV2Client) GetSink(ctx context.Context, in *GetSinkRequest, opts ...grpc.CallOption) (*LogSink, error) {
out := new(LogSink)
err := grpc.Invoke(ctx, "/google.logging.v2.ConfigServiceV2/GetSink", in, out, c.cc, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *configServiceV2Client) CreateSink(ctx context.Context, in *CreateSinkRequest, opts ...grpc.CallOption) (*LogSink, error) {
out := new(LogSink)
err := grpc.Invoke(ctx, "/google.logging.v2.ConfigServiceV2/CreateSink", in, out, c.cc, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *configServiceV2Client) UpdateSink(ctx context.Context, in *UpdateSinkRequest, opts ...grpc.CallOption) (*LogSink, error) {
out := new(LogSink)
err := grpc.Invoke(ctx, "/google.logging.v2.ConfigServiceV2/UpdateSink", in, out, c.cc, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *configServiceV2Client) DeleteSink(ctx context.Context, in *DeleteSinkRequest, opts ...grpc.CallOption) (*google_protobuf5.Empty, error) {
out := new(google_protobuf5.Empty)
err := grpc.Invoke(ctx, "/google.logging.v2.ConfigServiceV2/DeleteSink", in, out, c.cc, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *configServiceV2Client) ListExclusions(ctx context.Context, in *ListExclusionsRequest, opts ...grpc.CallOption) (*ListExclusionsResponse, error) {
out := new(ListExclusionsResponse)
err := grpc.Invoke(ctx, "/google.logging.v2.ConfigServiceV2/ListExclusions", in, out, c.cc, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *configServiceV2Client) GetExclusion(ctx context.Context, in *GetExclusionRequest, opts ...grpc.CallOption) (*LogExclusion, error) {
out := new(LogExclusion)
err := grpc.Invoke(ctx, "/google.logging.v2.ConfigServiceV2/GetExclusion", in, out, c.cc, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *configServiceV2Client) CreateExclusion(ctx context.Context, in *CreateExclusionRequest, opts ...grpc.CallOption) (*LogExclusion, error) {
out := new(LogExclusion)
err := grpc.Invoke(ctx, "/google.logging.v2.ConfigServiceV2/CreateExclusion", in, out, c.cc, opts...)
if err != nil
|
return out, nil
}
func (c *configServiceV2Client) UpdateExclusion(ctx context.Context, in *UpdateExclusionRequest, opts ...grpc.CallOption) (*LogExclusion, error) {
out := new(LogExclusion)
err := grpc.Invoke(ctx, "/google.logging.v2.ConfigServiceV2/UpdateExclusion", in, out, c.cc, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *configServiceV2Client) DeleteExclusion(ctx context.Context, in *DeleteExclusionRequest, opts ...grpc.CallOption) (*google_protobuf5.Empty, error) {
out := new(google_protobuf5.Empty)
err := grpc.Invoke(ctx, "/google.logging.v2.ConfigServiceV2/DeleteExclusion", in, out, c.cc, opts...)
if err != nil {
return nil, err
}
return out, nil
}
// Server API for ConfigServiceV2 service
type ConfigServiceV2Server interface {
// Lists sinks.
ListSinks(context.Context, *ListSinksRequest) (*ListSinksResponse, error)
// Gets a sink.
GetSink(context.Context, *GetSinkRequest) (*LogSink, error)
// Creates a sink that exports specified log entries to a destination. The
// export of newly-ingested log entries begins immediately, unless the current
// time is outside the sink's start and end times or the sink's
// `writer_identity` is not permitted to write to the destination. A sink can
// export log entries only from the resource owning the sink.
CreateSink(context.Context, *CreateSinkRequest) (*LogSink, error)
// Updates a sink. This method replaces the following fields in the existing
// sink with values from the new sink: `destination`, `filter`,
// `output_version_format`, `start_time`, and `end_time`.
// The updated sink might also have a new `writer_identity`; see the
// `unique_writer_identity` field.
UpdateSink(context.Context, *UpdateSinkRequest) (*LogSink, error)
// Deletes a sink. If the sink has a unique `writer_identity`, then that
// service account is also deleted.
DeleteSink(context.Context, *DeleteSinkRequest) (*google_protobuf5.Empty, error)
// Lists all the exclusions in a parent resource.
ListExclusions(context.Context, *ListExclusionsRequest) (*ListExclusionsResponse, error)
// Gets the description of an exclusion.
GetExclusion(context.Context, *GetExclusionRequest) (*LogExclusion, error)
// Creates a new exclusion in a specified parent resource.
// Only log entries belonging to that resource can be excluded.
// You can have up to 10 exclusions in a resource.
CreateExclusion(context.Context, *CreateExclusionRequest) (*LogExclusion, error)
// Changes one or more properties of an existing exclusion.
UpdateExclusion(context.Context, *UpdateExclusionRequest) (*LogExclusion, error)
// Deletes an exclusion.
DeleteExclusion(context.Context, *DeleteExclusionRequest) (*google_protobuf5.Empty, error)
}
func RegisterConfigServiceV2Server(s *grpc.Server, srv ConfigServiceV2Server) {
s.RegisterService(&_ConfigServiceV2_serviceDesc, srv)
}
func _ConfigServiceV2_ListSinks_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(ListSinksRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(ConfigServiceV2Server).ListSinks(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/google.logging.v2.ConfigServiceV2/ListSinks",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(ConfigServiceV2Server).ListSinks(ctx, req.(*ListSinksRequest))
}
return interceptor(ctx, in, info, handler)
}
func _ConfigServiceV2_GetSink_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(GetSinkRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(ConfigServiceV2Server).GetSink(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/google.logging.v2.ConfigServiceV2/GetSink",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(ConfigServiceV2Server).GetSink(ctx, req.(*GetSinkRequest))
}
return interceptor(ctx, in, info, handler)
}
func _ConfigServiceV2_CreateSink_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(CreateSinkRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(ConfigServiceV2Server).CreateSink(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/google.logging.v2.ConfigServiceV2/CreateSink",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(ConfigServiceV2Server).CreateSink(ctx, req.(*CreateSinkRequest))
}
return interceptor(ctx, in, info, handler)
}
func _ConfigServiceV2_UpdateSink_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(UpdateSinkRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(ConfigServiceV2Server).UpdateSink(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/google.logging.v2.ConfigServiceV2/UpdateSink",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(ConfigServiceV2Server).UpdateSink(ctx, req.(*UpdateSinkRequest))
}
return interceptor(ctx, in, info, handler)
}
func _ConfigServiceV2_DeleteSink_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(DeleteSinkRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(ConfigServiceV2Server).DeleteSink(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/google.logging.v2.ConfigServiceV2/DeleteSink",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(ConfigServiceV2Server).DeleteSink(ctx, req.(*DeleteSinkRequest))
}
return interceptor(ctx, in, info, handler)
}
func _ConfigServiceV2_ListExclusions_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(ListExclusionsRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(ConfigServiceV2Server).ListExclusions(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/google.logging.v2.ConfigServiceV2/ListExclusions",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(ConfigServiceV2Server).ListExclusions(ctx, req.(*ListExclusionsRequest))
}
return interceptor(ctx, in, info, handler)
}
func _ConfigServiceV2_GetExclusion_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(GetExclusionRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(ConfigServiceV2Server).GetExclusion(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/google.logging.v2.ConfigServiceV2/GetExclusion",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(ConfigServiceV2Server).GetExclusion(ctx, req.(*GetExclusionRequest))
}
return interceptor(ctx, in, info, handler)
}
func _ConfigServiceV2_CreateExclusion_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(CreateExclusionRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(ConfigServiceV2Server).CreateExclusion(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/google.logging.v2.ConfigServiceV2/CreateExclusion",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(ConfigServiceV2Server).CreateExclusion(ctx, req.(*CreateExclusionRequest))
}
return interceptor(ctx, in, info, handler)
}
func _ConfigServiceV2_UpdateExclusion_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(UpdateExclusionRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(ConfigServiceV2Server).UpdateExclusion(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/google.logging.v2.ConfigServiceV2/UpdateExclusion",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(ConfigServiceV2Server).UpdateExclusion(ctx, req.(*UpdateExclusionRequest))
}
return interceptor(ctx, in, info, handler)
}
func _ConfigServiceV2_DeleteExclusion_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(DeleteExclusionRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(ConfigServiceV2Server).DeleteExclusion(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/google.logging.v2.ConfigServiceV2/DeleteExclusion",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(ConfigServiceV2Server).DeleteExclusion(ctx, req.(*DeleteExclusionRequest))
}
return interceptor(ctx, in, info, handler)
}
var _ConfigServiceV2_serviceDesc = grpc.ServiceDesc{
ServiceName: "google.logging.v2.ConfigServiceV2",
HandlerType: (*ConfigServiceV2Server)(nil),
Methods: []grpc.MethodDesc{
{
MethodName: "ListSinks",
Handler: _ConfigServiceV2_ListSinks_Handler,
},
{
MethodName: "GetSink",
Handler: _ConfigServiceV2_GetSink_Handler,
},
{
MethodName: "CreateSink",
Handler: _ConfigServiceV2_CreateSink_Handler,
},
{
MethodName: "UpdateSink",
Handler: _ConfigServiceV2_UpdateSink_Handler,
},
{
MethodName: "DeleteSink",
Handler: _ConfigServiceV2_DeleteSink_Handler,
},
{
MethodName: "ListExclusions",
Handler: _ConfigServiceV2_ListExclusions_Handler,
},
{
MethodName: "GetExclusion",
Handler: _ConfigServiceV2_GetExclusion_Handler,
},
{
MethodName: "CreateExclusion",
Handler: _ConfigServiceV2_CreateExclusion_Handler,
},
{
MethodName: "UpdateExclusion",
Handler: _ConfigServiceV2_UpdateExclusion_Handler,
},
{
MethodName: "DeleteExclusion",
Handler: _ConfigServiceV2_DeleteExclusion_Handler,
},
},
Streams: []grpc.StreamDesc{},
Metadata: "google/logging/v2/logging_config.proto",
}
func init() { proto.RegisterFile("google/logging/v2/logging_config.proto", fileDescriptor2) }
var fileDescriptor2 = []byte{
// 1109 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xbc, 0x57, 0xff, 0x6e, 0xdb, 0x54,
0x14, 0xc6, 0xe9, 0xda, 0x26, 0xa7, 0x5b, 0xd3, 0xde, 0xd1, 0x10, 0xb9, 0x8c, 0x06, 0xb3, 0x95,
0xb4, 0x80, 0x53, 0x02, 0x93, 0x60, 0xd3, 0x34, 0xb1, 0xae, 0xad, 0x2a, 0x75, 0x5d, 0xe5, 0x76,
0x45, 0x42, 0x48, 0x96, 0x1b, 0xdf, 0x98, 0x4b, 0x1d, 0x5f, 0xcf, 0xbe, 0x09, 0xdd, 0xa6, 0x4a,
0xe3, 0xc7, 0x0b, 0x4c, 0x20, 0x9e, 0x01, 0xf1, 0x0c, 0xbc, 0x00, 0x7f, 0xf3, 0x0a, 0x3c, 0x04,
0x7f, 0xa2, 0xfb, 0x23, 0x89, 0xe3, 0xb8, 0xa9, 0x11, 0x82, 0xbf, 0x7a, 0xef, 0xb9, 0xe7, 0xf8,
0xfb, 0xce, 0xb9, 0x9f, 0x3f, 0xa7, 0xb0, 0xea, 0x51, 0xea, 0xf9, 0xb8, 0xe1, 0x53, 0xcf, 0x23,
0x81, 0xd7, 0xe8, 0x35, 0xfb, 0x4b, 0xbb, 0x45, 0x83, 0x36, 0xf1, 0xcc, 0x30, 0xa2, 0x8c, 0xa2,
0x45, 0x99, 0x67, 0xaa, 0x43, 0xb3, 0xd7, 0xd4, 0xdf, 0x54, 0xa5, 0x4e, 0x48, 0x1a, 0x4e, 0x10,
0x50, 0xe6, 0x30, 0x42, 0x83, 0x58, 0x16, 0xe8, 0xcb, 0xea, 0x54, 0xec, 0x4e, 0xba, 0xed, 0x06,
0xee, 0x84, 0xec, 0x99, 0x3a, 0xac, 0xa5, 0x0f, 0xdb, 0x04, 0xfb, 0xae, 0xdd, 0x71, 0xe2, 0x53,
0x95, 0xb1, 0x92, 0xce, 0x60, 0xa4, 0x83, 0x63, 0xe6, 0x74, 0x42, 0x99, 0x60, 0xfc, 0x36, 0x05,
0xb3, 0x7b, 0xd4, 0x3b, 0x24, 0xc1, 0x29, 0x42, 0x70, 0x25, 0x70, 0x3a, 0xb8, 0xaa, 0xd5, 0xb4,
0x7a, 0xc9, 0x12, 0x6b, 0x54, 0x83, 0x39, 0x17, 0xc7, 0x8c, 0x04, 0x82, 0x55, 0x75, 0x4a, 0x1c,
0x25, 0x43, 0xa8, 0x02, 0x33, 0x6d, 0xe2, 0x33, 0x1c, 0x55, 0xa7, 0xc5, 0xa1, 0xda, 0xa1, 0x2f,
0x61, 0x89, 0x76, 0x59, 0xd8, 0x65, 0x76, 0x0f, 0x47, 0x31, 0xa1, 0x81, 0xdd, 0xa6, 0x51, 0xc7,
0x61, 0xd5, 0x99, 0x9a, 0x56, 0x9f, 0x6f, 0xd6, 0xcd, 0xb1, 0x51, 0x98, 0x8a, 0x88, 0x79, 0x2c,
0x0b, 0xb6, 0x45, 0xbe, 0x75, 0x5d, 0x3e, 0x66, 0x24, 0x88, 0xde, 0x85, 0xf2, 0x37, 0x11, 0x61,
0x38, 0xb2, 0x89, 0x8b, 0x03, 0x46, 0xd8, 0xb3, 0x6a, 0x51, 0xc0, 0xcf, 0xcb, 0xf0, 0xae, 0x8a,
0xa2, 0x35, 0x58, 0x20, 0x41, 0xcb, 0xef, 0xba, 0xd8, 0x6e, 0x7d, 0x45, 0x7c, 0x37, 0xc2, 0x41,
0xb5, 0x54, 0xd3, 0xea, 0x45, 0xab, 0xac, 0xe2, 0x9b, 0x2a, 0x8c, 0x3e, 0x05, 0x88, 0x99, 0x13,
0x31, 0x9b, 0x0f, 0xa9, 0x0a, 0x35, 0xad, 0x3e, 0xd7, 0xd4, 0xfb, 0x34, 0xfb, 0x13, 0x34, 0x8f,
0xfa, 0x13, 0xb4, 0x4a, 0x22, 0x9b, 0xef, 0xd1, 0x6d, 0x28, 0xe2, 0xc0, 0x95, 0x85, 0x73, 0x97,
0x16, 0xce, 0xe2, 0xc0, 0xe5, 0x3b, 0xe3, 0x3e, 0x5c, 0x1b, 0x6d, 0xeb, 0x2d, 0xd0, 0x8f, 0xb7,
0xac, 0xc3, 0xdd, 0xc7, 0xfb, 0xf6, 0xf6, 0x63, 0xeb, 0xd1, 0x67, 0x47, 0xf6, 0x93, 0xfd, 0xc3,
0x83, 0xad, 0xcd, 0xdd, 0xed, 0xdd, 0xad, 0x87, 0x0b, 0xaf, 0xa1, 0x19, 0x28, 0x1c, 0x37, 0x17,
0x34, 0xf1, 0xf7, 0xc3, 0x85, 0x82, 0xd1, 0x86, 0x85, 0x3d, 0x12, 0x33, 0x3e, 0xb5, 0xd8, 0xc2,
0x4f, 0xbb, 0x38, 0x66, 0xfc, 0x42, 0x42, 0x27, 0xc2, 0x01, 0x53, 0x17, 0xa9, 0x76, 0xe8, 0x06,
0x40, 0xe8, 0x78, 0xd8, 0x66, 0xf4, 0x14, 0x07, 0xd5, 0x82, 0x38, 0x2b, 0xf1, 0xc8, 0x11, 0x0f,
0xa0, 0x65, 0x10, 0x1b, 0x3b, 0x26, 0xcf, 0xb1, 0xb8, 0xe7, 0x69, 0xab, 0xc8, 0x03, 0x87, 0xe4,
0x39, 0x36, 0x3a, 0xb0, 0x98, 0xc0, 0x89, 0x43, 0x1a, 0xc4, 0x18, 0x6d, 0xc0, 0x74, 0xcc, 0x03,
0x55, 0xad, 0x36, 0x95, 0xec, 0x78, 0xfc, 0x46, 0x2d, 0x99, 0x88, 0x56, 0xa1, 0x1c, 0xe0, 0x33,
0x66, 0x8f, 0xf1, 0xb8, 0xc6, 0xc3, 0x07, 0x7d, 0x2e, 0xc6, 0x07, 0x30, 0xbf, 0x83, 0x05, 0x5a,
0xbf, 0xa9, 0x65, 0x28, 0xf1, 0x47, 0xd8, 0x09, 0x81, 0x16, 0x79, 0x60, 0xdf, 0xe9, 0x60, 0xe3,
0x95, 0x06, 0x8b, 0x9b, 0x11, 0x76, 0x18, 0x4e, 0x96, 0x5c, 0x34, 0x07, 0x13, 0xae, 0xf0, 0x4a,
0x81, 0x3c, 0x99, 0xb5, 0xc8, 0x43, 0x1f, 0x43, 0xa5, 0x1b, 0x90, 0xa7, 0x5d, 0x6c, 0xa7, 0x15,
0x37, 0x25, 0x74, 0xf4, 0xba, 0x3c, 0xfd, 0x7c, 0x44, 0x77, 0xc6, 0xcf, 0x1a, 0x2c, 0x3e, 0x09,
0xdd, 0x14, 0xa7, 0x49, 0x6d, 0xfc, 0x4f, 0xc4, 0x36, 0x60, 0xf1, 0x21, 0xf6, 0x71, 0x7e, 0x5e,
0xc6, 0x19, 0x5c, 0xdd, 0xa3, 0xde, 0xd6, 0x59, 0xcb, 0xef, 0x72, 0xa9, 0x4e, 0xf0, 0x89, 0x56,
0x44, 0x42, 0xe1, 0x13, 0x85, 0x81, 0x4f, 0xf4, 0x43, 0x09, 0x9f, 0x98, 0x1a, 0xf1, 0x09, 0x1d,
0x8a, 0x2e, 0x89, 0x9d, 0x13, 0x1f, 0xbb, 0xd5, 0x2b, 0x82, 0xf7, 0x60, 0x6f, 0x9c, 0xc2, 0x12,
0x97, 0xdd, 0x00, 0xfa, 0x3f, 0xd5, 0xf8, 0xb7, 0x1a, 0x54, 0xd2, 0x68, 0x4a, 0xe9, 0xf7, 0x01,
0xf0, 0x20, 0xaa, 0xe4, 0xbe, 0x92, 0x7d, 0x3f, 0x83, 0x6a, 0x2b, 0x51, 0x92, 0x5b, 0xf8, 0x6b,
0x70, 0x7d, 0x07, 0x0f, 0x19, 0xf4, 0xdb, 0xcd, 0x98, 0xb8, 0x41, 0xa1, 0x22, 0x35, 0x3f, 0x96,
0x7d, 0xd1, 0x70, 0xee, 0x41, 0x69, 0x40, 0x49, 0x89, 0xec, 0xd2, 0x26, 0x86, 0x15, 0xc6, 0x2f,
0x1a, 0x54, 0xa4, 0xa2, 0xf3, 0xf0, 0xfb, 0x97, 0x68, 0xe8, 0x2e, 0xcc, 0x75, 0x05, 0x98, 0xf8,
0x9c, 0x89, 0xcb, 0xca, 0x32, 0xd5, 0x6d, 0xfe, 0xc5, 0x7b, 0xe4, 0xc4, 0xa7, 0x16, 0xc8, 0x74,
0xbe, 0x36, 0xde, 0x87, 0x8a, 0xd4, 0x78, 0x1e, 0xa6, 0xcd, 0xdf, 0x01, 0xca, 0x9b, 0xe2, 0x2b,
0x7d, 0x88, 0xa3, 0x1e, 0x69, 0xe1, 0xe3, 0x26, 0x3a, 0x87, 0xd2, 0xc0, 0xf0, 0xd0, 0x3b, 0x59,
0xbc, 0x53, 0xb6, 0xab, 0xdf, 0x9c, 0x9c, 0x24, 0x95, 0x64, 0xdc, 0xfa, 0xee, 0x8f, 0x3f, 0x7f,
0x2c, 0xac, 0xa0, 0x1b, 0xfc, 0x27, 0xc2, 0x0b, 0x79, 0x31, 0xf7, 0xc2, 0x88, 0x7e, 0x8d, 0x5b,
0x2c, 0x6e, 0xac, 0x9f, 0x37, 0xa4, 0x51, 0x32, 0x98, 0x55, 0x06, 0x88, 0xde, 0xce, 0x78, 0xee,
0xa8, 0x39, 0xea, 0x13, 0xac, 0xc2, 0x58, 0x17, 0x80, 0x37, 0x91, 0x21, 0x00, 0x07, 0x2f, 0x79,
0x02, 0x53, 0x42, 0x36, 0xd6, 0xcf, 0xd1, 0x0b, 0x80, 0xa1, 0x8d, 0xa2, 0xac, 0x86, 0xc6, 0x5c,
0x76, 0x22, 0xf6, 0x7b, 0x02, 0xfb, 0x96, 0x31, 0xb9, 0xd9, 0x3b, 0xd2, 0xcd, 0x5e, 0x6a, 0x00,
0x43, 0xc3, 0xcc, 0x44, 0x1f, 0xf3, 0xd3, 0x89, 0xe8, 0x1b, 0x02, 0x7d, 0x5d, 0xcf, 0xd1, 0xb9,
0xa2, 0xd0, 0x03, 0x18, 0x5a, 0x63, 0x26, 0x83, 0x31, 0xe7, 0xd4, 0x2b, 0x63, 0x92, 0xdc, 0xe2,
0xbf, 0xd0, 0xfa, 0x73, 0x5f, 0xcf, 0x33, 0xf7, 0x57, 0x1a, 0xcc, 0x8f, 0x3a, 0x0f, 0xaa, 0x5f,
0xa0, 0xa6, 0x31, 0x2b, 0xd4, 0xd7, 0x72, 0x64, 0x2a, 0xf1, 0x8d, 0x6a, 0x21, 0xe3, 0x3e, 0x12,
0x8e, 0xf5, 0xbd, 0x06, 0x57, 0x93, 0x56, 0x84, 0x56, 0xb3, 0x75, 0x98, 0x7e, 0xc3, 0xf4, 0xcb,
0x5e, 0xf2, 0x14, 0x8b, 0xf4, 0x50, 0x86, 0x14, 0xf8, 0x64, 0x7e, 0xd2, 0xa0, 0x9c, 0x72, 0x39,
0xb4, 0x76, 0xa1, 0x2e, 0xff, 0x39, 0x97, 0xdb, 0x82, 0x4b, 0xc3, 0xc8, 0x31, 0x91, 0x3b, 0x09,
0x73, 0xe2, 0xb4, 0x52, 0x56, 0x98, 0x49, 0x2b, 0xdb, 0x2e, 0x73, 0xd3, 0x6a, 0xe6, 0x18, 0x51,
0x92, 0xd6, 0x4b, 0x0d, 0xca, 0x29, 0xdf, 0xcb, 0xa4, 0x95, 0xed, 0x8d, 0x39, 0xa5, 0x3c, 0x91,
0xcd, 0x83, 0x1f, 0x34, 0x58, 0x6a, 0xd1, 0xce, 0x38, 0xe8, 0x03, 0xb4, 0x27, 0xd7, 0xd2, 0x69,
0x0f, 0x38, 0xc4, 0x81, 0xf6, 0xc5, 0x27, 0x2a, 0xd1, 0xa3, 0xbe, 0x13, 0x78, 0x26, 0x8d, 0xbc,
0x86, 0x87, 0x03, 0x41, 0xa0, 0x21, 0x8f, 0x9c, 0x90, 0xc4, 0x89, 0xff, 0xab, 0xee, 0xaa, 0xe5,
0x5f, 0x9a, 0xf6, 0x6b, 0xe1, 0x8d, 0x1d, 0x59, 0xbd, 0xe9, 0xd3, 0xae, 0x6b, 0x2a, 0x00, 0xf3,
0xb8, 0x79, 0x32, 0x23, 0x9e, 0xf0, 0xd1, 0xdf, 0x01, 0x00, 0x00, 0xff, 0xff, 0xa9, 0x26, 0x54,
0x7c, 0x98, 0x0d, 0x00, 0x00,
}
|
{
return nil, err
}
|
move_bounds.rs
|
//! FIXME: write short doc here
use hir::db::HirDatabase;
use ra_syntax::{
ast::{self, edit, make, AstNode, NameOwner, TypeBoundsOwner},
SyntaxElement,
SyntaxKind::*,
};
use crate::{Assist, AssistCtx, AssistId};
pub(crate) fn move_bounds_to_where_clause(mut ctx: AssistCtx<impl HirDatabase>) -> Option<Assist> {
let type_param_list = ctx.node_at_offset::<ast::TypeParamList>()?;
let mut type_params = type_param_list.type_params();
if type_params.all(|p| p.type_bound_list().is_none()) {
return None;
}
let parent = type_param_list.syntax().parent()?;
if parent.children_with_tokens().find(|it| it.kind() == WHERE_CLAUSE).is_some() {
return None;
}
let anchor: SyntaxElement = match parent.kind() {
FN_DEF => ast::FnDef::cast(parent)?.body()?.syntax().clone().into(),
TRAIT_DEF => ast::TraitDef::cast(parent)?.item_list()?.syntax().clone().into(),
IMPL_BLOCK => ast::ImplBlock::cast(parent)?.item_list()?.syntax().clone().into(),
ENUM_DEF => ast::EnumDef::cast(parent)?.variant_list()?.syntax().clone().into(),
STRUCT_DEF => parent
.children_with_tokens()
.find(|it| it.kind() == RECORD_FIELD_DEF_LIST || it.kind() == SEMI)?,
_ => return None,
};
ctx.add_action(
AssistId("move_bounds_to_where_clause"),
"move_bounds_to_where_clause",
|edit| {
let new_params = type_param_list
.type_params()
.filter(|it| it.type_bound_list().is_some())
.map(|type_param| {
let without_bounds = type_param.remove_bounds();
(type_param, without_bounds)
});
let new_type_param_list = edit::replace_descendants(&type_param_list, new_params);
edit.replace_ast(type_param_list.clone(), new_type_param_list);
let where_clause = {
let predicates = type_param_list.type_params().filter_map(build_predicate);
make::where_clause(predicates)
};
let to_insert = match anchor.prev_sibling_or_token() {
Some(ref elem) if elem.kind() == WHITESPACE => {
format!("{} ", where_clause.syntax())
}
_ => format!(" {}", where_clause.syntax()),
};
edit.insert(anchor.text_range().start(), to_insert);
edit.target(type_param_list.syntax().text_range());
},
);
ctx.build()
}
fn build_predicate(param: ast::TypeParam) -> Option<ast::WherePred> {
let path = make::path_from_name_ref(make::name_ref(¶m.name()?.syntax().to_string()));
let predicate = make::where_pred(path, param.type_bound_list()?.bounds());
|
}
#[cfg(test)]
mod tests {
use super::*;
use crate::helpers::check_assist;
#[test]
fn move_bounds_to_where_clause_fn() {
check_assist(
move_bounds_to_where_clause,
r#"
fn foo<T: u32, <|>F: FnOnce(T) -> T>() {}
"#,
r#"
fn foo<T, <|>F>() where T: u32, F: FnOnce(T) -> T {}
"#,
);
}
#[test]
fn move_bounds_to_where_clause_impl() {
check_assist(
move_bounds_to_where_clause,
r#"
impl<U: u32, <|>T> A<U, T> {}
"#,
r#"
impl<U, <|>T> A<U, T> where U: u32 {}
"#,
);
}
#[test]
fn move_bounds_to_where_clause_struct() {
check_assist(
move_bounds_to_where_clause,
r#"
struct A<<|>T: Iterator<Item = u32>> {}
"#,
r#"
struct A<<|>T> where T: Iterator<Item = u32> {}
"#,
);
}
#[test]
fn move_bounds_to_where_clause_tuple_struct() {
check_assist(
move_bounds_to_where_clause,
r#"
struct Pair<<|>T: u32>(T, T);
"#,
r#"
struct Pair<<|>T>(T, T) where T: u32;
"#,
);
}
}
|
Some(predicate)
|
merge.go
|
package merge
import (
"github.com/imdario/mergo"
"gopkg.in/yaml.v2"
)
// Merge takes a list of maps of interface and options as input and returns a single map with the merged contents
func MergeWithOptions(inputs []map[interface{}]interface{}, appendSlice, sliceDeepCopy bool) (map[interface{}]interface{}, error) {
merged := map[interface{}]interface{}{}
for index := range inputs {
current := inputs[index]
// Due to a bug in `mergo.Merge`
// (in the `for` loop, it DOES modify the source of the previous loop iteration if it's a complex map and `mergo` get a pointer to it,
// not only the destination of the current loop iteration),
// we don't give it our maps directly; we convert them to YAML strings and then back to `Go` maps,
// so `mergo` does not have access to the original pointers
yamlCurrent, err := yaml.Marshal(current)
if err != nil {
return nil, err
}
var dataCurrent map[interface{}]interface{}
if err = yaml.Unmarshal(yamlCurrent, &dataCurrent); err != nil {
return nil, err
}
var opts []func(*mergo.Config)
|
if appendSlice {
opts = append(opts, mergo.WithAppendSlice)
}
if sliceDeepCopy {
opts = append(opts, mergo.WithSliceDeepCopy)
}
if err = mergo.Merge(&merged, dataCurrent, opts...); err != nil {
return nil, err
}
}
return merged, nil
}
// Merge takes a list of maps of interface as input and returns a single map with the merged contents
func Merge(inputs []map[interface{}]interface{}) (map[interface{}]interface{}, error) {
return MergeWithOptions(inputs, false, false)
}
|
opts = append(opts, mergo.WithOverride, mergo.WithOverwriteWithEmptyValue, mergo.WithTypeCheck)
|
advBatchControl_test.go
|
// Licensed to The Moov Authors under one or more contributor
// license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright
// ownership. The Moov Authors licenses this file to you 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.
package ach
import (
"strings"
"testing"
"github.com/moov-io/base"
)
func mockADVBatchControl() *ADVBatchControl {
bc := NewADVBatchControl()
bc.ServiceClassCode = CreditsOnly
bc.ACHOperatorData = "T-BANK"
bc.ODFIIdentification = "12104288"
return bc
}
// testMockADVBatchControl tests mock batch control
func testMockADVBatchControl(t testing.TB) {
bc := mockADVBatchControl()
if err := bc.Validate(); err != nil {
t.Error("mockADVBatchControl does not validate and will break other tests")
}
if bc.ServiceClassCode != CreditsOnly {
t.Error("ServiceClassCode depedendent default value has changed")
}
if bc.ACHOperatorData != "T-BANK" {
t.Error("ACHOperatorData depedendent default value has changed")
}
if bc.ODFIIdentification != "12104288" {
t.Error("ODFIIdentification depedendent default value has changed")
}
}
// TestMockADVBatchControl test mock batch control
func TestMockADVBatchControl(t *testing.T) {
testMockADVBatchControl(t)
}
// BenchmarkMockADVBatchControl benchmarks mock batch control
func BenchmarkMockADVBatchControl(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
testMockADVBatchControl(b)
}
}
// TestParseADVBatchControl parses a known Batch ControlRecord string.
func testParseADVBatchControl(t testing.TB) {
var line = "828000000100053200010000000000000001050000000000000000000000T-BANK 076401250000001"
r := NewReader(strings.NewReader(line))
r.line = line
bh := BatchHeader{BatchNumber: 1,
StandardEntryClassCode: ADV,
ServiceClassCode: AutomatedAccountingAdvices,
CompanyIdentification: "origid",
ODFIIdentification: "12104288"}
r.addCurrentBatch(NewBatchADV(&bh))
r.currentBatch.AddADVEntry(mockADVEntryDetail())
if err := r.parseBatchControl(); err != nil {
t.Errorf("%T: %s", err, err)
}
record := r.currentBatch.GetADVControl()
if record.recordType != "8" {
t.Errorf("RecordType Expected '8' got: %v", record.recordType)
}
if record.ServiceClassCode != AutomatedAccountingAdvices {
t.Errorf("ServiceClassCode Expected '280' got: %v", record.ServiceClassCode)
}
if record.EntryAddendaCountField() != "000001" {
t.Errorf("EntryAddendaCount Expected '000001' got: %v", record.EntryAddendaCountField())
}
if record.EntryHashField() != "0005320001" {
t.Errorf("EntryHash Expected '0005320001' got: %v", record.EntryHashField())
}
if record.TotalDebitEntryDollarAmountField() != "00000000000000010500" {
t.Errorf("TotalDebitEntryDollarAmount Expected '00000000000000010500' got: %v", record.TotalDebitEntryDollarAmountField())
}
if record.TotalCreditEntryDollarAmountField() != "00000000000000000000" {
t.Errorf("TotalCreditEntryDollarAmount Expected '00000000000000000000' got: %v", record.TotalCreditEntryDollarAmountField())
}
if record.ACHOperatorDataField() != "T-BANK " {
t.Errorf("ACHOperatorData Expected 'T-BANK ' got: %v", record.ACHOperatorDataField())
}
if record.ODFIIdentificationField() != "07640125" {
t.Errorf("OdfiIdentification Expected '07640125' got: %v", record.ODFIIdentificationField())
}
if record.BatchNumberField() != "0000001" {
t.Errorf("BatchNumber Expected '0000001' got: %v", record.BatchNumberField())
}
}
// TestParseADVBatchControl tests parsing a known Batch ControlRecord string.
func TestParseADVBatchControl(t *testing.T) {
testParseADVBatchControl(t)
}
// BenchmarkParseADVBatchControl benchmarks parsing a known Batch ControlRecord string.
func
|
(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
testParseADVBatchControl(b)
}
}
// testADVBCString validates that a known parsed file can be return to a string of the same value
func testADVBCString(t testing.TB) {
var line = "822500000100053200010000000000000001050000000000000000000000T-BANK 076401250000001"
r := NewReader(strings.NewReader(line))
r.line = line
bh := BatchHeader{BatchNumber: 1,
StandardEntryClassCode: ADV,
ServiceClassCode: AutomatedAccountingAdvices,
CompanyIdentification: "origid",
ODFIIdentification: "12104288"}
r.addCurrentBatch(NewBatchADV(&bh))
r.currentBatch.AddADVEntry(mockADVEntryDetail())
if err := r.parseBatchControl(); err != nil {
t.Errorf("%T: %s", err, err)
}
record := r.currentBatch.GetADVControl()
if record.String() != line {
t.Errorf("Strings do not match")
}
}
// TestADVBCString tests validating that a known parsed file can be return to a string of the same value
func TestADVBCString(t *testing.T) {
testADVBCString(t)
}
// BenchmarkADVBCString benchmarks validating that a known parsed file can be return to a string of the same value
func BenchmarkADVBCString(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
testADVBCString(b)
}
}
// testValidateADVBCRecordType ensure error if recordType is not 8
func testValidateADVBCRecordType(t testing.TB) {
bc := mockADVBatchControl()
bc.recordType = "2"
err := bc.Validate()
if !base.Match(err, NewErrRecordType(7)) {
t.Errorf("%T: %s", err, err)
}
}
// TestValidateADVBCRecordType tests ensuring an error if recordType is not 8
func TestValidateADVBCRecordType(t *testing.T) {
testValidateADVBCRecordType(t)
}
// BenchmarkValidateADVBCRecordType benchmarks ensuring an error if recordType is not 8
func BenchmarkValidateADVBCRecordType(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
testValidateBCRecordType(b)
}
}
// testADVisServiceClassErr verifies service class code
func testADVBCisServiceClassErr(t testing.TB) {
bc := mockADVBatchControl()
bc.ServiceClassCode = 123
err := bc.Validate()
if !base.Match(err, ErrServiceClass) {
t.Errorf("%T: %s", err, err)
}
}
// TestADVBCisServiceClassErr tests verifying service class code
func TestADVBCisServiceClassErr(t *testing.T) {
testADVBCisServiceClassErr(t)
}
// BenchmarkADVBCisServiceClassErr benchmarks verifying service class code
func BenchmarkADVBCisServiceClassErr(b *testing.B) {
for i := 0; i < b.N; i++ {
testADVBCisServiceClassErr(b)
}
}
// testADVBCBatchNumber verifies batch number
func testADVBCBatchNumber(t testing.TB) {
bc := mockADVBatchControl()
bc.BatchNumber = 0
err := bc.Validate()
// TODO: are we expecting there to be no errors here?
if !base.Match(err, nil) {
t.Errorf("%T: %s", err, err)
}
}
// TestADVBCBatchNumber tests verifying batch number
func TestADVBCBatchNumber(t *testing.T) {
testADVBCBatchNumber(t)
}
// BenchmarkADVBCBatchNumber benchmarks verifying batch number
func BenchmarkADVBCBatchNumber(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
testADVBCBatchNumber(b)
}
}
// testADVBCACHOperatorDataAlphaNumeric verifies Company Identification is AlphaNumeric
func testADVBCACHOperatorDataAlphaNumeric(t testing.TB) {
bc := mockADVBatchControl()
bc.ACHOperatorData = "®"
err := bc.Validate()
if !base.Match(err, ErrNonAlphanumeric) {
t.Errorf("%T: %s", err, err)
}
}
// TestADVBCACHOperatorDataAlphaNumeric tests verifying Company Identification is AlphaNumeric
func TestADVBCACHOperatorDataAlphaNumeric(t *testing.T) {
testADVBCACHOperatorDataAlphaNumeric(t)
}
// BenchmarkADVACHOperatorDataAlphaNumeric benchmarks verifying Company Identification is AlphaNumeric
func BenchmarkADVACHOperatorDataAlphaNumeric(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
testADVBCACHOperatorDataAlphaNumeric(b)
}
}
// testADVBCFieldInclusionRecordType verifies Record Type is included
func testADVBCFieldInclusionRecordType(t testing.TB) {
bc := mockADVBatchControl()
bc.recordType = ""
err := bc.Validate()
if !base.Match(err, ErrConstructor) {
t.Errorf("%T: %s", err, err)
}
}
// TestADVBCFieldInclusionRecordType tests verifying Record Type is included
func TestADVBCFieldInclusionRecordType(t *testing.T) {
testADVBCFieldInclusionRecordType(t)
}
// BenchmarkADVBCFieldInclusionRecordType benchmarks verifying Record Type is included
func BenchmarkADVBCFieldInclusionRecordType(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
testADVBCFieldInclusionRecordType(b)
}
}
// testADVBCFieldInclusionServiceClassCode verifies Service Class Code is included
func testADVBCFieldInclusionServiceClassCode(t testing.TB) {
bc := mockADVBatchControl()
bc.ServiceClassCode = 0
err := bc.Validate()
if !base.Match(err, ErrConstructor) {
t.Errorf("%T: %s", err, err)
}
}
// TestADVBCFieldInclusionServiceClassCode tests verifying Service Class Code is included
func TestADVBCFieldInclusionServiceClassCode(t *testing.T) {
testADVBCFieldInclusionServiceClassCode(t)
}
// BenchmarkADVBCFieldInclusionServiceClassCod benchmarks verifying Service Class Code is included
func BenchmarkADVBCFieldInclusionServiceClassCode(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
testADVBCFieldInclusionServiceClassCode(b)
}
}
// testADVBCFieldInclusionODFIIdentification verifies batch control ODFIIdentification
func testADVBCFieldInclusionODFIIdentification(t testing.TB) {
bc := mockADVBatchControl()
bc.ODFIIdentification = "000000000"
err := bc.Validate()
if !base.Match(err, ErrConstructor) {
t.Errorf("%T: %s", err, err)
}
}
// TestADVBCFieldInclusionODFIIdentification tests verifying batch control ODFIIdentification
func TestADVBCFieldInclusionODFIIdentification(t *testing.T) {
testADVBCFieldInclusionODFIIdentification(t)
}
// BenchmarkADVBCFieldInclusionODFIIdentification benchmarks verifying batch control ODFIIdentification
func BenchmarkADVBCFieldInclusionODFIIdentification(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
testADVBCFieldInclusionODFIIdentification(b)
}
}
// testADVBatchControlLength verifies batch control length
func testADVBatchControlLength(t testing.TB) {
bc := NewADVBatchControl()
recordLength := len(bc.String())
if recordLength != 94 {
t.Errorf("Instantiated length of Batch Control string is not 94 but %v", recordLength)
}
}
// TestADVBatchControlLength tests verifying batch control length
func TestADVBatchControlLength(t *testing.T) {
testADVBatchControlLength(t)
}
// BenchmarkADVBatchControlLength benchmarks verifying batch control length
func BenchmarkADVBatchControlLength(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
testADVBatchControlLength(b)
}
}
|
BenchmarkParseADVBatchControl
|
datasource_ovm_network_test.go
|
package ovm
import (
"fmt"
"testing"
|
func TestAccDataSourceOvmNetwork(t *testing.T) {
resourceName := "data.ovm_network.network"
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreChecks(t) },
Providers: testAccProviders,
Steps: []resource.TestStep{
{
Config: testAccCheckOvmNetworkDataSourceConfig,
Check: resource.ComposeTestCheckFunc(
testAccCheckOvmNetworkDataSourceID(resourceName),
resource.TestCheckResourceAttr(resourceName, "name", "vm-corp-public"),
resource.TestCheckResourceAttr(resourceName, "type", "com.oracle.ovm.mgr.ws.model.Network"),
resource.TestCheckResourceAttr(resourceName, "value", "1063b8b5eb"),
),
},
},
})
}
func testAccCheckOvmNetworkDataSourceID(n string) resource.TestCheckFunc {
return func(s *terraform.State) error {
rs, ok := s.RootModule().Resources[n]
if !ok {
return fmt.Errorf("Can't find Repository data source: %s", n)
}
if rs.Primary.ID == "" {
return fmt.Errorf("Repository data source ID not set")
}
return nil
}
}
const testAccCheckOvmNetworkDataSourceConfig = `
data "ovm_network" "network" {
name = "vm-corp-public"
}
`
|
"github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/terraform"
)
|
rabin-decrypt.go
|
// Copyright 2017 Venkatesh Gopal([email protected]), All rights reserved
package main
import (
"fmt"
"io/ioutil"
"strings"
"math/big"
"os"
"crypto/sha256"
)
func main() {
// Rabin decrypt will produce 4 output messages
if len(os.Args) != 3 {
fmt.Println(" \n Follow command line specification \n ./rabin-decrypt" +
"<privatekey-file-name> <Ciphertext to be decrypted, in decimal>\n")
} else {
file_name := os.Args[1]
CipherTextInString := os.Args[2]
N, p,q := ExtractDetailsFromPrivateKeyFile(file_name)
hashofMessageInString := CipherTextInString[(len(CipherTextInString) - 64):
len(CipherTextInString)]
CipherTextInString = CipherTextInString[0:(len(CipherTextInString) - 64)]
Ciphertext := ConvertCipherTextToBigInt(CipherTextInString)
m1, m2, m3, m4 := Decrypt(p,q,Ciphertext,N)
message := compareMessageAndHash(m1,m2,m3,m4,hashofMessageInString)
fmt.Println(" The Message is ", message)
}
}
func compareMessageAndHash(m1 *big.Int,m2 *big.Int, m3 *big.Int, m4 *big.Int,
hashofMessageInString string) (*big.Int) {
m1Hash := getMessageHashInString(m1.String())
m2Hash := getMessageHashInString(m2.String())
m3Hash := getMessageHashInString(m3.String())
m4Hash := getMessageHashInString(m4.String())
message := big.NewInt(0)
if m1Hash == hashofMessageInString {
message = message.Set(m1)
} else if m2Hash == hashofMessageInString {
message = message.Set(m2)
} else if m3Hash == hashofMessageInString
|
else if m4Hash == hashofMessageInString {
message = message.Set(m4)
}
return message
}
func getMessageHashInString(MessageInString string)(string) {
sum := sha256.Sum256([]byte(MessageInString))
sumInHex := fmt.Sprintf("%x", sum)
return sumInHex
}
func Decrypt(p *big.Int, q *big.Int, C *big.Int, N *big.Int) (*big.Int, *big.Int,
*big.Int, *big.Int) {
mp := getSquareRoot(C,p)
mq := getSquareRoot(C,q)
// Finding values of yp and yq as per the equation yp.p + yq.q = 1
// Using the Extended Euclidean algorithm to do the same
pCopy := big.NewInt(0)
qCopy := big.NewInt(0)
pCopy = pCopy.Set(p)
qCopy = qCopy.Set(q)
_, yp, yq := extendedEuclideanAlgorithm(pCopy,qCopy)
// Handling the 2 statements required to calculate r, -r
ypPmq := big.NewInt(0)
//ypPmq = ypPmq.Mul(p,mq)
ypPmq = ypPmq.Mul(yp,p)
ypPmq = ypPmq.Mul(ypPmq,mq)
yqQmp := big.NewInt(0)
yqQmp = yqQmp.Mul(q,mp)
yqQmp = yqQmp.Mul(yqQmp,yq)
ypPmqPlusyqQmp := big.NewInt(0)
ypPmqPlusyqQmp = ypPmqPlusyqQmp.Add(ypPmq,yqQmp)
if (ypPmqPlusyqQmp.Cmp(big.NewInt(0)) == -1) {
temp := big.NewInt(0)
temp = temp.Abs(ypPmqPlusyqQmp)
tempAbs := big.NewInt(0)
tempAbs = tempAbs.Set(temp)
temp = temp.Div(temp,N)
temp = temp.Add(temp, big.NewInt(1))
temp = temp.Mul(temp,N)
ypPmqPlusyqQmp = ypPmqPlusyqQmp.Add(ypPmqPlusyqQmp, temp)
} else {
ypPmqPlusyqQmp = ypPmqPlusyqQmp.Mod(ypPmqPlusyqQmp,N)
}
NegativeypPmqPlusyqQmp := big.NewInt(0)
NegativeypPmqPlusyqQmp = NegativeypPmqPlusyqQmp.Sub(N,ypPmqPlusyqQmp)
// Handling the 2 statements required to calculate s, -s
ypPmqMinusyqQmp := big.NewInt(0)
ypPmqMinusyqQmp = ypPmqMinusyqQmp.Sub(ypPmq,yqQmp)
if (ypPmqMinusyqQmp.Cmp(big.NewInt(0)) == -1) {
temp := big.NewInt(0)
temp = temp.Abs(ypPmqMinusyqQmp)
tempAbs := big.NewInt(0)
tempAbs = tempAbs.Set(temp)
temp = temp.Div(temp,N)
temp = temp.Add(temp, big.NewInt(1))
temp = temp.Mul(temp,N)
ypPmqMinusyqQmp = ypPmqMinusyqQmp.Add(ypPmqMinusyqQmp, temp)
} else {
ypPmqMinusyqQmp = ypPmqMinusyqQmp.Mod(ypPmqMinusyqQmp,N)
}
NegativeypPmqMinusyqQmp := big.NewInt(0)
NegativeypPmqMinusyqQmp = NegativeypPmqMinusyqQmp.Sub(N,ypPmqMinusyqQmp)
return ypPmqPlusyqQmp,NegativeypPmqPlusyqQmp,ypPmqMinusyqQmp,
NegativeypPmqMinusyqQmp
}
func getSquareRoot( C *big.Int, val *big.Int)(*big.Int) {
temp := big.NewInt(0)
temp = temp.Add(val,big.NewInt(1))
temp = temp.Div(temp,big.NewInt(4))
mpOrmq := squareAndMultiple(C, temp, val)
return mpOrmq
}
func ConvertCipherTextToBigInt(CipherTextInString string) (*big.Int) {
boolError := false
Ciphertext := big.NewInt(0)
Ciphertext, boolError = Ciphertext.SetString(CipherTextInString, 10)
if boolError != true {
fmt.Println(" Error in Set String")
}
return Ciphertext
}
func ExtractDetailsFromPrivateKeyFile(file_name string) (*big.Int, *big.Int,
*big.Int) {
FileContent, err := ioutil.ReadFile(file_name)
N := big.NewInt(0)
p := big.NewInt(0)
q := big.NewInt(0)
if err != nil {
fmt.Println(" Error readng data from the file")
} else {
FileContentString := string(FileContent)
// Below statements to remove left and right bracket from the string
FileContentString = FileContentString[1:(len(FileContentString) - 1)]
FileContentSliced := strings.Split(FileContentString, ",")
NinString := FileContentSliced[0]
pinString := FileContentSliced[1]
qinString := FileContentSliced[2]
boolError := false
N, boolError = N.SetString(NinString,10)
if boolError != true {
fmt.Println(" Error in Set String")
}
p, boolError = p.SetString(pinString, 10)
if boolError != true {
fmt.Println(" Error in Set String")
}
q, boolError = q.SetString(qinString, 10)
if boolError != true {
fmt.Println(" Error in Set String")
}
}
return N, p, q
}
func squareAndMultiple(a *big.Int, b *big.Int, c *big.Int) (*big.Int) {
// FormatInt will provide the binary representation of a number
binExp := fmt.Sprintf("%b", b)
binExpLength := len(binExp)
initialValue := big.NewInt(0)
initialValue = initialValue.Mod(a,c)
// Hold the initial value in result
result := big.NewInt(0)
result = result.Set(initialValue)
// Using the square and multipy algorithm to perform modular exponentation
for i := 1; i < binExpLength; i++ {
// 49 is the ASCII representation of 1 and 48 is the ASCII representation
// of 0
interMediateResult := big.NewInt(0)
interMediateResult = interMediateResult.Mul(result,result)
result = result.Mod(interMediateResult, c)
if byte(binExp[i]) == byte(49) {
interResult := big.NewInt(0)
interResult = interResult.Mul(result,initialValue)
result = result.Mod(interResult, c)
}
}
return result
}
func extendedEuclideanAlgorithm(a *big.Int, b *big.Int) (*big.Int,*big.Int,
*big.Int) {
// Implementing the extendedEuclideanAlgorithm as per the pseudo-code
// mentioned in the handbook of applied cryptography
// http://cacr.uwaterloo.ca/hac/about/chap2.pdf (See Section 2.107)
d := big.NewInt(0)
x := big.NewInt(0)
y := big.NewInt(0)
if (b.Cmp(big.NewInt(0)) == 0) {
d = d.Set(a)
x = big.NewInt(1)
y = big.NewInt(0)
fmt.Println("First check return")
return d,x,y
}
// 2 as per the Handbook of Applied cryptography
x2 := big.NewInt(1)
x1 := big.NewInt(0)
y2 := big.NewInt(0)
y1 := big.NewInt(1)
// Setting big.Ints for the loop as we can't simple add (or) multiply
// like Integers
q := big.NewInt(0)
r := big.NewInt(0)
qb := big.NewInt(0)
qx1 := big.NewInt(0)
qy1 := big.NewInt(0)
for ((b.Cmp(big.NewInt(0))) == 1) {
// 3.1 as per the Handbook of Applied cryptography
q = q.Div(a,b)
r = r.Sub(a,qb.Mul(q,b))
x = x.Sub(x2,qx1.Mul(q,x1))
y = y.Sub(y2,qy1.Mul(q,y1))
// 3.2 as per the Handbook of Applied cryptography
a = a.Set(b)
b = b.Set(r)
x2 = x2.Set(x1)
x1 = x1.Set(x)
y2 = y2.Set(y1)
y1 = y1.Set(y)
}
// 4 as per the Handbook of Applied cryptography
d = d.Set(a)
x = x.Set(x2)
y = y.Set(y2)
return d,x,y
}
|
{
message = message.Set(m3)
}
|
blockchain.rs
|
use crate::{
bytes::Bytes,
core::{self, Capacity},
packed,
prelude::*,
H256, U256,
};
impl Pack<packed::Uint64> for Capacity {
fn pack(&self) -> packed::Uint64 {
self.as_u64().pack()
}
}
impl<'r> Unpack<core::Capacity> for packed::Uint64Reader<'r> {
fn unpack(&self) -> core::Capacity {
Capacity::shannons(self.unpack())
}
}
impl_conversion_for_entity_unpack!(Capacity, Uint64);
impl Pack<packed::Uint256> for U256 {
fn pack(&self) -> packed::Uint256 {
packed::Uint256::from_slice(&self.to_le_bytes()[..]).expect("impossible: fail to pack U256")
}
}
impl<'r> Unpack<U256> for packed::Uint256Reader<'r> {
fn unpack(&self) -> U256 {
U256::from_little_endian(self.as_slice()).expect("internal error: fail to unpack U256")
}
}
impl_conversion_for_entity_unpack!(U256, Uint256);
impl Pack<packed::Byte32> for H256 {
fn pack(&self) -> packed::Byte32 {
packed::Byte32::from_slice(self.as_bytes()).expect("impossible: fail to pack H256")
}
}
impl<'r> Unpack<H256> for packed::Byte32Reader<'r> {
fn unpack(&self) -> H256 {
H256::from_slice(self.as_slice()).expect("internal error: fail to unpack H256")
}
}
impl_conversion_for_entity_unpack!(H256, Byte32);
impl Pack<packed::Byte32> for [u8; 32] {
fn
|
(&self) -> packed::Byte32 {
packed::Byte32::from_slice(&self[..]).expect("impossible: fail to pack [u8; 32]")
}
}
impl<'r> Unpack<[u8; 32]> for packed::Byte32Reader<'r> {
fn unpack(&self) -> [u8; 32] {
let ptr = self.as_slice().as_ptr() as *const [u8; 32];
unsafe { *ptr }
}
}
impl_conversion_for_entity_unpack!([u8; 32], Byte32);
impl Pack<packed::ProposalShortId> for [u8; 10] {
fn pack(&self) -> packed::ProposalShortId {
packed::ProposalShortId::from_slice(&self[..])
.expect("impossible: fail to pack to ProposalShortId")
}
}
impl<'r> Unpack<[u8; 10]> for packed::ProposalShortIdReader<'r> {
fn unpack(&self) -> [u8; 10] {
let ptr = self.as_slice().as_ptr() as *const [u8; 10];
unsafe { *ptr }
}
}
impl_conversion_for_entity_unpack!([u8; 10], ProposalShortId);
impl Pack<packed::Bytes> for Bytes {
fn pack(&self) -> packed::Bytes {
let len = (self.len() as u32).to_le_bytes();
let mut v = Vec::with_capacity(4 + self.len());
v.extend_from_slice(&len[..]);
v.extend_from_slice(&self[..]);
packed::Bytes::new_unchecked(v.into())
}
}
impl<'r> Unpack<Bytes> for packed::BytesReader<'r> {
fn unpack(&self) -> Bytes {
Bytes::from(self.raw_data().to_owned())
}
}
impl Unpack<Bytes> for packed::Bytes {
fn unpack(&self) -> Bytes {
self.raw_data()
}
}
impl Pack<packed::Uint64> for core::EpochNumberWithFraction {
fn pack(&self) -> packed::Uint64 {
self.full_value().pack()
}
}
impl<'r> Unpack<core::EpochNumberWithFraction> for packed::Uint64Reader<'r> {
fn unpack(&self) -> core::EpochNumberWithFraction {
core::EpochNumberWithFraction::from_full_value(self.unpack())
}
}
impl_conversion_for_entity_unpack!(core::EpochNumberWithFraction, Uint64);
impl_conversion_for_option!(H256, Byte32Opt, Byte32OptReader);
impl_conversion_for_vector!(Capacity, Uint64Vec, Uint64VecReader);
impl_conversion_for_vector!(Bytes, BytesVec, BytesVecReader);
impl_conversion_for_packed_optional_pack!(TransactionPoint, TransactionPointOpt);
impl_conversion_for_packed_optional_pack!(Byte32, Byte32Opt);
impl_conversion_for_packed_optional_pack!(CellOutput, CellOutputOpt);
impl_conversion_for_packed_optional_pack!(Script, ScriptOpt);
impl_conversion_for_packed_iterator_pack!(ProposalShortId, ProposalShortIdVec);
impl_conversion_for_packed_iterator_pack!(Bytes, BytesVec);
impl_conversion_for_packed_iterator_pack!(Transaction, TransactionVec);
impl_conversion_for_packed_iterator_pack!(OutPoint, OutPointVec);
impl_conversion_for_packed_iterator_pack!(CellDep, CellDepVec);
impl_conversion_for_packed_iterator_pack!(CellOutput, CellOutputVec);
impl_conversion_for_packed_iterator_pack!(CellInput, CellInputVec);
impl_conversion_for_packed_iterator_pack!(UncleBlock, UncleBlockVec);
impl_conversion_for_packed_iterator_pack!(Header, HeaderVec);
impl_conversion_for_packed_iterator_pack!(Byte32, Byte32Vec);
|
pack
|
bundle.py
|
""" Represents a bundle. In the words of the Apple docs, it's a convenient way to deliver
software. Really it's a particular kind of directory structure, with one main executable,
well-known places for various data files and libraries,
and tracking hashes of all those files for signing purposes.
For isign, we have two main kinds of bundles: the App, and the Framework (a reusable
library packaged along with its data files.) An App may contain many Frameworks, but
a Framework has to be re-signed independently.
See the Apple Developer Documentation "About Bundles" """
import biplist
import code_resources
from exceptions import NotMatched
import copy
import glob
import logging
import os
from os.path import basename, exists, join, splitext
from signer import openssl_command
import signable
import shutil
log = logging.getLogger(__name__)
def is_info_plist_native(plist):
""" If an bundle is for native iOS, it has these properties in the Info.plist """
return (
'CFBundleSupportedPlatforms' in plist and
'iPhoneOS' in plist['CFBundleSupportedPlatforms']
)
class Bundle(object):
""" A bundle is a standard directory structure, a signable, installable set of files.
Apps are Bundles, but so are some kinds of Frameworks (libraries) """
helpers = []
signable_class = None
entitlements_path = None # Not set for every bundle type
def __init__(self, path):
self.path = path
self.info_path = join(self.path, 'Info.plist')
if not exists(self.info_path):
raise NotMatched("no Info.plist found; probably not a bundle")
self.info = biplist.readPlist(self.info_path)
self.orig_info = None
if not is_info_plist_native(self.info):
# while we should probably not allow this *or* add it ourselves, it appears to work without it
log.debug(u"Missing/invalid CFBundleSupportedPlatforms value in {}".format(self.info_path))
# will be added later
self.seal_path = None
def get_entitlements_path(self):
return self.entitlements_path
def get_executable_path(self):
""" Path to the main executable. For an app, this is app itself. For
a Framework, this is the main framework """
executable_name = None
if 'CFBundleExecutable' in self.info:
executable_name = self.info['CFBundleExecutable']
else:
executable_name, _ = splitext(basename(self.path))
executable = join(self.path, executable_name)
if not exists(executable):
raise Exception(
'could not find executable for {0}'.format(self.path))
return executable
def update_info_props(self, new_props):
if self.orig_info is None:
self.orig_info = copy.deepcopy(self.info)
changed = False
if ('CFBundleIdentifier' in new_props and
'CFBundleURLTypes' in self.info and
'CFBundleURLTypes' not in new_props):
# The bundle identifier changed. Check CFBundleURLTypes for
# CFBundleURLName values matching the old bundle
# id if it's not being set explicitly
old_bundle_id = self.info['CFBundleIdentifier']
new_bundle_id = new_props['CFBundleIdentifier']
for url_type in self.info['CFBundleURLTypes']:
if 'CFBundleURLName' not in url_type:
continue
if url_type['CFBundleURLName'] == old_bundle_id:
url_type['CFBundleURLName'] = new_bundle_id
changed = True
for key, val in new_props.iteritems():
is_new_key = key not in self.info
|
if is_new_key or self.info[key] != val:
if is_new_key:
log.warn("Adding new Info.plist key: {}".format(key))
self.info[key] = val
changed = True
if changed:
biplist.writePlist(self.info, self.info_path, binary=True)
else:
self.orig_info = None
def info_props_changed(self):
return self.orig_info is not None
def info_prop_changed(self, key):
if not self.orig_info:
# No props have been changed
return False
if key in self.info and key in self.orig_info and self.info[key] == self.orig_info[key]:
return False
return True
def get_info_prop(self, key):
return self.info[key]
def sign_dylibs(self, signer, path):
""" Sign all the dylibs in this directory """
for dylib_path in glob.glob(join(path, '*.dylib')):
dylib = signable.Dylib(self, dylib_path, signer)
dylib.sign(self, signer)
def sign(self, signer):
""" Sign everything in this bundle, recursively with sub-bundles """
# log.debug("SIGNING: %s" % self.path)
frameworks_path = join(self.path, 'Frameworks')
if exists(frameworks_path):
# log.debug("SIGNING FRAMEWORKS: %s" % frameworks_path)
# sign all the frameworks
for framework_name in os.listdir(frameworks_path):
framework_path = join(frameworks_path, framework_name)
# log.debug("checking for framework: %s" % framework_path)
try:
framework = Framework(framework_path)
# log.debug("resigning: %s" % framework_path)
framework.resign(signer)
except NotMatched:
# log.debug("not a framework: %s" % framework_path)
continue
# sign all the dylibs under Frameworks
self.sign_dylibs(signer, frameworks_path)
# sign any dylibs in the main directory (rare, but it happens)
self.sign_dylibs(signer, self.path)
plugins_path = join(self.path, 'PlugIns')
if exists(plugins_path):
# sign the appex executables
appex_paths = glob.glob(join(plugins_path, '*.appex'))
for appex_path in appex_paths:
plist_path = join(appex_path, 'Info.plist')
if not exists(plist_path):
continue
plist = biplist.readPlist(plist_path)
appex_exec_path = join(appex_path, plist['CFBundleExecutable'])
appex = signable.Appex(self, appex_exec_path, singer)
appex.sign(self, signer)
# then create the seal
# TODO maybe the app should know what its seal path should be...
self.seal_path = code_resources.make_seal(self.get_executable_path(),
self.path)
# then sign the app
executable = self.signable_class(self, self.get_executable_path(), signer)
executable.sign(self, signer)
def resign(self, signer):
""" signs bundle, modifies in place """
self.sign(signer)
log.debug("Resigned bundle at <%s>", self.path)
class Framework(Bundle):
""" A bundle that comprises reusable code. Similar to an app in that it has
its own resources and metadata. Not like an app because the main executable
doesn't have Entitlements, or an Application hash, and it doesn't have its
own provisioning profile. """
# the executable in this bundle will be a Framework
signable_class = signable.Framework
def __init__(self, path):
super(Framework, self).__init__(path)
class App(Bundle):
""" The kind of bundle that is visible as an app to the user.
Contains the provisioning profile, entitlements, etc. """
# the executable in this bundle will be an Executable (i.e. the main
# executable of an app)
signable_class = signable.Executable
def __init__(self, path):
super(App, self).__init__(path)
self.entitlements_path = join(self.path,
'Entitlements.plist')
self.provision_path = join(self.path,
'embedded.mobileprovision')
def provision(self, provision_path):
shutil.copyfile(provision_path, self.provision_path)
@staticmethod
def extract_entitlements(provision_path):
""" Given a path to a provisioning profile, return the entitlements
encoded therein """
cmd = [
'smime',
'-inform', 'der',
'-verify', # verifies content, prints verification status to STDERR,
# outputs content to STDOUT. In our case, will be an XML plist
'-noverify', # accept self-signed certs. Not the opposite of -verify!
'-in', provision_path
]
# this command always prints 'Verification successful' to stderr.
(profile_text, err) = openssl_command(cmd, data=None, expect_err=True)
if err and err.strip() != 'Verification successful':
log.error('Received unexpected error from openssl: {}'.format(err))
plist_dict = biplist.readPlistFromString(profile_text)
if 'Entitlements' not in plist_dict:
log.debug('failed to get entitlements in provisioning profile')
raise Exception('could not find Entitlements in {}'.format(provision_path))
return plist_dict['Entitlements']
def write_entitlements(self, entitlements):
""" Write entitlements to self.entitlements_path. This actually doesn't matter
to the app, it's just used later on by other parts of the signing process. """
biplist.writePlist(entitlements, self.entitlements_path, binary=False)
log.debug("wrote Entitlements to {0}".format(self.entitlements_path))
def resign(self, signer, provisioning_profile, alternate_entitlements_path=None):
""" signs app in place """
# TODO all this mucking about with entitlements feels wrong. The entitlements_path is
# not actually functional, it's just a way of passing it to later stages of signing.
# Maybe we should determine entitlements data in isign/archive.py or even isign/isign.py,
# and then embed it into Signer?
# In the typical case, we add entitlements from the pprof into the app's signature
if alternate_entitlements_path is None:
# copy the provisioning profile in
self.provision(provisioning_profile)
entitlements = self.extract_entitlements(provisioning_profile)
else:
log.info("signing with alternative entitlements: {}".format(alternate_entitlements_path))
entitlements = biplist.readPlist(alternate_entitlements_path)
self.write_entitlements(entitlements)
# actually resign this bundle now
super(App, self).resign(signer)
| |
index.js
|
import React from 'react';
import './styles.css';
export default function
|
() {
return (
<div className='account-page'>
<h1>Account</h1>
</div>
);
}
|
Account
|
docker_cli_push_test.go
|
package main
import (
"archive/tar"
"fmt"
"io/ioutil"
"net/http"
"net/http/httptest"
"os"
"os/exec"
"path/filepath"
"strings"
"sync"
"time"
"github.com/docker/distribution/reference"
"github.com/docker/docker/cliconfig"
"github.com/docker/docker/pkg/integration/checker"
"github.com/go-check/check"
)
// Pushing an image to a private registry.
func testPushBusyboxImage(c *check.C) {
repoName := fmt.Sprintf("%v/dockercli/busybox", privateRegistryURL)
// tag the image to upload it to the private registry
dockerCmd(c, "tag", "busybox", repoName)
// push the image to the registry
dockerCmd(c, "push", repoName)
}
func (s *DockerRegistrySuite) TestPushBusyboxImage(c *check.C) {
testPushBusyboxImage(c)
}
func (s *DockerSchema1RegistrySuite) TestPushBusyboxImage(c *check.C) {
testPushBusyboxImage(c)
}
// pushing an image without a prefix should throw an error
func (s *DockerSuite) TestPushUnprefixedRepo(c *check.C) {
out, _, err := dockerCmdWithError("push", "busybox")
c.Assert(err, check.NotNil, check.Commentf("pushing an unprefixed repo didn't result in a non-zero exit status: %s", out))
}
func testPushUntagged(c *check.C) {
repoName := fmt.Sprintf("%v/dockercli/busybox", privateRegistryURL)
expected := "An image does not exist locally with the tag"
out, _, err := dockerCmdWithError("push", repoName)
c.Assert(err, check.NotNil, check.Commentf("pushing the image to the private registry should have failed: output %q", out))
c.Assert(out, checker.Contains, expected, check.Commentf("pushing the image failed"))
}
func (s *DockerRegistrySuite) TestPushUntagged(c *check.C) {
testPushUntagged(c)
}
func (s *DockerSchema1RegistrySuite) TestPushUntagged(c *check.C) {
testPushUntagged(c)
}
func testPushBadTag(c *check.C) {
repoName := fmt.Sprintf("%v/dockercli/busybox:latest", privateRegistryURL)
expected := "does not exist"
out, _, err := dockerCmdWithError("push", repoName)
c.Assert(err, check.NotNil, check.Commentf("pushing the image to the private registry should have failed: output %q", out))
c.Assert(out, checker.Contains, expected, check.Commentf("pushing the image failed"))
}
func (s *DockerRegistrySuite) TestPushBadTag(c *check.C) {
testPushBadTag(c)
}
func (s *DockerSchema1RegistrySuite) TestPushBadTag(c *check.C) {
testPushBadTag(c)
}
func testPushMultipleTags(c *check.C) {
repoName := fmt.Sprintf("%v/dockercli/busybox", privateRegistryURL)
repoTag1 := fmt.Sprintf("%v/dockercli/busybox:t1", privateRegistryURL)
repoTag2 := fmt.Sprintf("%v/dockercli/busybox:t2", privateRegistryURL)
// tag the image and upload it to the private registry
dockerCmd(c, "tag", "busybox", repoTag1)
dockerCmd(c, "tag", "busybox", repoTag2)
dockerCmd(c, "push", repoName)
// Ensure layer list is equivalent for repoTag1 and repoTag2
out1, _ := dockerCmd(c, "pull", repoTag1)
imageAlreadyExists := ": Image already exists"
var out1Lines []string
for _, outputLine := range strings.Split(out1, "\n") {
if strings.Contains(outputLine, imageAlreadyExists) {
out1Lines = append(out1Lines, outputLine)
}
}
out2, _ := dockerCmd(c, "pull", repoTag2)
var out2Lines []string
for _, outputLine := range strings.Split(out2, "\n") {
if strings.Contains(outputLine, imageAlreadyExists) {
out1Lines = append(out1Lines, outputLine)
}
}
c.Assert(out2Lines, checker.HasLen, len(out1Lines))
for i := range out1Lines {
c.Assert(out1Lines[i], checker.Equals, out2Lines[i])
}
}
func (s *DockerRegistrySuite) TestPushMultipleTags(c *check.C) {
testPushMultipleTags(c)
}
func (s *DockerSchema1RegistrySuite) TestPushMultipleTags(c *check.C) {
testPushMultipleTags(c)
}
func testPushEmptyLayer(c *check.C) {
repoName := fmt.Sprintf("%v/dockercli/emptylayer", privateRegistryURL)
emptyTarball, err := ioutil.TempFile("", "empty_tarball")
c.Assert(err, check.IsNil, check.Commentf("Unable to create test file"))
tw := tar.NewWriter(emptyTarball)
err = tw.Close()
c.Assert(err, check.IsNil, check.Commentf("Error creating empty tarball"))
freader, err := os.Open(emptyTarball.Name())
c.Assert(err, check.IsNil, check.Commentf("Could not open test tarball"))
defer freader.Close()
importCmd := exec.Command(dockerBinary, "import", "-", repoName)
importCmd.Stdin = freader
out, _, err := runCommandWithOutput(importCmd)
c.Assert(err, check.IsNil, check.Commentf("import failed: %q", out))
// Now verify we can push it
out, _, err = dockerCmdWithError("push", repoName)
c.Assert(err, check.IsNil, check.Commentf("pushing the image to the private registry has failed: %s", out))
}
func (s *DockerRegistrySuite) TestPushEmptyLayer(c *check.C) {
testPushEmptyLayer(c)
}
func (s *DockerSchema1RegistrySuite) TestPushEmptyLayer(c *check.C) {
testPushEmptyLayer(c)
}
// testConcurrentPush pushes multiple tags to the same repo
// concurrently.
func testConcurrentPush(c *check.C) {
repoName := fmt.Sprintf("%v/dockercli/busybox", privateRegistryURL)
repos := []string{}
for _, tag := range []string{"push1", "push2", "push3"} {
repo := fmt.Sprintf("%v:%v", repoName, tag)
_, err := buildImage(repo, fmt.Sprintf(`
FROM busybox
ENTRYPOINT ["/bin/echo"]
ENV FOO foo
ENV BAR bar
CMD echo %s
`, repo), true)
c.Assert(err, checker.IsNil)
repos = append(repos, repo)
}
// Push tags, in parallel
results := make(chan error)
for _, repo := range repos {
go func(repo string) {
_, _, err := runCommandWithOutput(exec.Command(dockerBinary, "push", repo))
results <- err
}(repo)
}
for range repos {
err := <-results
c.Assert(err, checker.IsNil, check.Commentf("concurrent push failed with error: %v", err))
}
// Clear local images store.
args := append([]string{"rmi"}, repos...)
dockerCmd(c, args...)
// Re-pull and run individual tags, to make sure pushes succeeded
for _, repo := range repos {
dockerCmd(c, "pull", repo)
dockerCmd(c, "inspect", repo)
out, _ := dockerCmd(c, "run", "--rm", repo)
c.Assert(strings.TrimSpace(out), checker.Equals, "/bin/sh -c echo "+repo)
}
}
func (s *DockerRegistrySuite) TestConcurrentPush(c *check.C) {
testConcurrentPush(c)
}
func (s *DockerSchema1RegistrySuite) TestConcurrentPush(c *check.C) {
testConcurrentPush(c)
}
func (s *DockerRegistrySuite) TestCrossRepositoryLayerPush(c *check.C) {
sourceRepoName := fmt.Sprintf("%v/dockercli/busybox", privateRegistryURL)
// tag the image to upload it to the private registry
dockerCmd(c, "tag", "busybox", sourceRepoName)
// push the image to the registry
out1, _, err := dockerCmdWithError("push", sourceRepoName)
c.Assert(err, check.IsNil, check.Commentf("pushing the image to the private registry has failed: %s", out1))
// ensure that none of the layers were mounted from another repository during push
c.Assert(strings.Contains(out1, "Mounted from"), check.Equals, false)
digest1 := reference.DigestRegexp.FindString(out1)
c.Assert(len(digest1), checker.GreaterThan, 0, check.Commentf("no digest found for pushed manifest"))
destRepoName := fmt.Sprintf("%v/dockercli/crossrepopush", privateRegistryURL)
// retag the image to upload the same layers to another repo in the same registry
dockerCmd(c, "tag", "busybox", destRepoName)
// push the image to the registry
out2, _, err := dockerCmdWithError("push", destRepoName)
c.Assert(err, check.IsNil, check.Commentf("pushing the image to the private registry has failed: %s", out2))
// ensure that layers were mounted from the first repo during push
c.Assert(strings.Contains(out2, "Mounted from dockercli/busybox"), check.Equals, true)
digest2 := reference.DigestRegexp.FindString(out2)
c.Assert(len(digest2), checker.GreaterThan, 0, check.Commentf("no digest found for pushed manifest"))
c.Assert(digest1, check.Equals, digest2)
// ensure that pushing again produces the same digest
out3, _, err := dockerCmdWithError("push", destRepoName)
c.Assert(err, check.IsNil, check.Commentf("pushing the image to the private registry has failed: %s", out2))
digest3 := reference.DigestRegexp.FindString(out3)
c.Assert(len(digest2), checker.GreaterThan, 0, check.Commentf("no digest found for pushed manifest"))
c.Assert(digest3, check.Equals, digest2)
// ensure that we can pull and run the cross-repo-pushed repository
dockerCmd(c, "rmi", destRepoName)
dockerCmd(c, "pull", destRepoName)
out4, _ := dockerCmd(c, "run", destRepoName, "echo", "-n", "hello world")
c.Assert(out4, check.Equals, "hello world")
}
func (s *DockerSchema1RegistrySuite) TestCrossRepositoryLayerPushNotSupported(c *check.C) {
sourceRepoName := fmt.Sprintf("%v/dockercli/busybox", privateRegistryURL)
// tag the image to upload it to the private registry
dockerCmd(c, "tag", "busybox", sourceRepoName)
// push the image to the registry
out1, _, err := dockerCmdWithError("push", sourceRepoName)
c.Assert(err, check.IsNil, check.Commentf("pushing the image to the private registry has failed: %s", out1))
// ensure that none of the layers were mounted from another repository during push
c.Assert(strings.Contains(out1, "Mounted from"), check.Equals, false)
digest1 := reference.DigestRegexp.FindString(out1)
c.Assert(len(digest1), checker.GreaterThan, 0, check.Commentf("no digest found for pushed manifest"))
destRepoName := fmt.Sprintf("%v/dockercli/crossrepopush", privateRegistryURL)
// retag the image to upload the same layers to another repo in the same registry
dockerCmd(c, "tag", "busybox", destRepoName)
// push the image to the registry
out2, _, err := dockerCmdWithError("push", destRepoName)
c.Assert(err, check.IsNil, check.Commentf("pushing the image to the private registry has failed: %s", out2))
// schema1 registry should not support cross-repo layer mounts, so ensure that this does not happen
c.Assert(strings.Contains(out2, "Mounted from"), check.Equals, false)
digest2 := reference.DigestRegexp.FindString(out2)
c.Assert(len(digest2), checker.GreaterThan, 0, check.Commentf("no digest found for pushed manifest"))
c.Assert(digest1, check.Not(check.Equals), digest2)
// ensure that we can pull and run the second pushed repository
dockerCmd(c, "rmi", destRepoName)
dockerCmd(c, "pull", destRepoName)
out3, _ := dockerCmd(c, "run", destRepoName, "echo", "-n", "hello world")
c.Assert(out3, check.Equals, "hello world")
}
func (s *DockerTrustSuite) TestTrustedPush(c *check.C) {
repoName := fmt.Sprintf("%v/dockerclitrusted/pushtest:latest", privateRegistryURL)
// tag the image and upload it to the private registry
dockerCmd(c, "tag", "busybox", repoName)
pushCmd := exec.Command(dockerBinary, "push", repoName)
s.trustedCmd(pushCmd)
out, _, err := runCommandWithOutput(pushCmd)
c.Assert(err, check.IsNil, check.Commentf("Error running trusted push: %s\n%s", err, out))
c.Assert(out, checker.Contains, "Signing and pushing trust metadata", check.Commentf("Missing expected output on trusted push"))
// Try pull after push
pullCmd := exec.Command(dockerBinary, "pull", repoName)
s.trustedCmd(pullCmd)
out, _, err = runCommandWithOutput(pullCmd)
c.Assert(err, check.IsNil, check.Commentf(out))
c.Assert(string(out), checker.Contains, "Status: Image is up to date", check.Commentf(out))
// Assert that we rotated the snapshot key to the server by checking our local keystore
contents, err := ioutil.ReadDir(filepath.Join(cliconfig.ConfigDir(), "trust/private/tuf_keys", privateRegistryURL, "dockerclitrusted/pushtest"))
c.Assert(err, check.IsNil, check.Commentf("Unable to read local tuf key files"))
// Check that we only have 1 key (targets key)
c.Assert(contents, checker.HasLen, 1)
}
|
dockerCmd(c, "tag", "busybox", repoName)
pushCmd := exec.Command(dockerBinary, "push", repoName)
s.trustedCmdWithPassphrases(pushCmd, "12345678", "12345678")
out, _, err := runCommandWithOutput(pushCmd)
c.Assert(err, check.IsNil, check.Commentf("Error running trusted push: %s\n%s", err, out))
c.Assert(out, checker.Contains, "Signing and pushing trust metadata", check.Commentf("Missing expected output on trusted push"))
// Try pull after push
pullCmd := exec.Command(dockerBinary, "pull", repoName)
s.trustedCmd(pullCmd)
out, _, err = runCommandWithOutput(pullCmd)
c.Assert(err, check.IsNil, check.Commentf(out))
c.Assert(string(out), checker.Contains, "Status: Image is up to date", check.Commentf(out))
}
func (s *DockerTrustSuite) TestTrustedPushWithFailingServer(c *check.C) {
repoName := fmt.Sprintf("%v/dockerclitrusted/failingserver:latest", privateRegistryURL)
// tag the image and upload it to the private registry
dockerCmd(c, "tag", "busybox", repoName)
pushCmd := exec.Command(dockerBinary, "push", repoName)
// Using a name that doesn't resolve to an address makes this test faster
s.trustedCmdWithServer(pushCmd, "https://server.invalid:81/")
out, _, err := runCommandWithOutput(pushCmd)
c.Assert(err, check.NotNil, check.Commentf("Missing error while running trusted push w/ no server"))
c.Assert(out, checker.Contains, "error contacting notary server", check.Commentf("Missing expected output on trusted push"))
}
func (s *DockerTrustSuite) TestTrustedPushWithoutServerAndUntrusted(c *check.C) {
repoName := fmt.Sprintf("%v/dockerclitrusted/trustedandnot:latest", privateRegistryURL)
// tag the image and upload it to the private registry
dockerCmd(c, "tag", "busybox", repoName)
pushCmd := exec.Command(dockerBinary, "push", "--disable-content-trust", repoName)
// Using a name that doesn't resolve to an address makes this test faster
s.trustedCmdWithServer(pushCmd, "https://server.invalid")
out, _, err := runCommandWithOutput(pushCmd)
c.Assert(err, check.IsNil, check.Commentf("trusted push with no server and --disable-content-trust failed: %s\n%s", err, out))
c.Assert(out, check.Not(checker.Contains), "Error establishing connection to notary repository", check.Commentf("Missing expected output on trusted push with --disable-content-trust:"))
}
func (s *DockerTrustSuite) TestTrustedPushWithExistingTag(c *check.C) {
repoName := fmt.Sprintf("%v/dockerclitag/trusted:latest", privateRegistryURL)
// tag the image and upload it to the private registry
dockerCmd(c, "tag", "busybox", repoName)
dockerCmd(c, "push", repoName)
pushCmd := exec.Command(dockerBinary, "push", repoName)
s.trustedCmd(pushCmd)
out, _, err := runCommandWithOutput(pushCmd)
c.Assert(err, check.IsNil, check.Commentf("trusted push failed: %s\n%s", err, out))
c.Assert(out, checker.Contains, "Signing and pushing trust metadata", check.Commentf("Missing expected output on trusted push with existing tag"))
// Try pull after push
pullCmd := exec.Command(dockerBinary, "pull", repoName)
s.trustedCmd(pullCmd)
out, _, err = runCommandWithOutput(pullCmd)
c.Assert(err, check.IsNil, check.Commentf(out))
c.Assert(string(out), checker.Contains, "Status: Image is up to date", check.Commentf(out))
}
func (s *DockerTrustSuite) TestTrustedPushWithExistingSignedTag(c *check.C) {
repoName := fmt.Sprintf("%v/dockerclipushpush/trusted:latest", privateRegistryURL)
// tag the image and upload it to the private registry
dockerCmd(c, "tag", "busybox", repoName)
// Do a trusted push
pushCmd := exec.Command(dockerBinary, "push", repoName)
s.trustedCmd(pushCmd)
out, _, err := runCommandWithOutput(pushCmd)
c.Assert(err, check.IsNil, check.Commentf("trusted push failed: %s\n%s", err, out))
c.Assert(out, checker.Contains, "Signing and pushing trust metadata", check.Commentf("Missing expected output on trusted push with existing tag"))
// Do another trusted push
pushCmd = exec.Command(dockerBinary, "push", repoName)
s.trustedCmd(pushCmd)
out, _, err = runCommandWithOutput(pushCmd)
c.Assert(err, check.IsNil, check.Commentf("trusted push failed: %s\n%s", err, out))
c.Assert(out, checker.Contains, "Signing and pushing trust metadata", check.Commentf("Missing expected output on trusted push with existing tag"))
dockerCmd(c, "rmi", repoName)
// Try pull to ensure the double push did not break our ability to pull
pullCmd := exec.Command(dockerBinary, "pull", repoName)
s.trustedCmd(pullCmd)
out, _, err = runCommandWithOutput(pullCmd)
c.Assert(err, check.IsNil, check.Commentf("Error running trusted pull: %s\n%s", err, out))
c.Assert(out, checker.Contains, "Status: Downloaded", check.Commentf("Missing expected output on trusted pull with --disable-content-trust"))
}
func (s *DockerTrustSuite) TestTrustedPushWithIncorrectPassphraseForNonRoot(c *check.C) {
repoName := fmt.Sprintf("%v/dockercliincorretpwd/trusted:latest", privateRegistryURL)
// tag the image and upload it to the private registry
dockerCmd(c, "tag", "busybox", repoName)
// Push with default passphrases
pushCmd := exec.Command(dockerBinary, "push", repoName)
s.trustedCmd(pushCmd)
out, _, err := runCommandWithOutput(pushCmd)
c.Assert(err, check.IsNil, check.Commentf("trusted push failed: %s\n%s", err, out))
c.Assert(out, checker.Contains, "Signing and pushing trust metadata", check.Commentf("Missing expected output on trusted push:\n%s", out))
// Push with wrong passphrases
pushCmd = exec.Command(dockerBinary, "push", repoName)
s.trustedCmdWithPassphrases(pushCmd, "12345678", "87654321")
out, _, err = runCommandWithOutput(pushCmd)
c.Assert(err, check.NotNil, check.Commentf("Error missing from trusted push with short targets passphrase: \n%s", out))
c.Assert(out, checker.Contains, "could not find necessary signing keys", check.Commentf("Missing expected output on trusted push with short targets/snapsnot passphrase"))
}
func (s *DockerTrustSuite) TestTrustedPushWithExpiredSnapshot(c *check.C) {
c.Skip("Currently changes system time, causing instability")
repoName := fmt.Sprintf("%v/dockercliexpiredsnapshot/trusted:latest", privateRegistryURL)
// tag the image and upload it to the private registry
dockerCmd(c, "tag", "busybox", repoName)
// Push with default passphrases
pushCmd := exec.Command(dockerBinary, "push", repoName)
s.trustedCmd(pushCmd)
out, _, err := runCommandWithOutput(pushCmd)
c.Assert(err, check.IsNil, check.Commentf("trusted push failed: %s\n%s", err, out))
c.Assert(out, checker.Contains, "Signing and pushing trust metadata", check.Commentf("Missing expected output on trusted push"))
// Snapshots last for three years. This should be expired
fourYearsLater := time.Now().Add(time.Hour * 24 * 365 * 4)
runAtDifferentDate(fourYearsLater, func() {
// Push with wrong passphrases
pushCmd = exec.Command(dockerBinary, "push", repoName)
s.trustedCmd(pushCmd)
out, _, err = runCommandWithOutput(pushCmd)
c.Assert(err, check.NotNil, check.Commentf("Error missing from trusted push with expired snapshot: \n%s", out))
c.Assert(out, checker.Contains, "repository out-of-date", check.Commentf("Missing expected output on trusted push with expired snapshot"))
})
}
func (s *DockerTrustSuite) TestTrustedPushWithExpiredTimestamp(c *check.C) {
c.Skip("Currently changes system time, causing instability")
repoName := fmt.Sprintf("%v/dockercliexpiredtimestamppush/trusted:latest", privateRegistryURL)
// tag the image and upload it to the private registry
dockerCmd(c, "tag", "busybox", repoName)
// Push with default passphrases
pushCmd := exec.Command(dockerBinary, "push", repoName)
s.trustedCmd(pushCmd)
out, _, err := runCommandWithOutput(pushCmd)
c.Assert(err, check.IsNil, check.Commentf("trusted push failed: %s\n%s", err, out))
c.Assert(out, checker.Contains, "Signing and pushing trust metadata", check.Commentf("Missing expected output on trusted push"))
// The timestamps expire in two weeks. Lets check three
threeWeeksLater := time.Now().Add(time.Hour * 24 * 21)
// Should succeed because the server transparently re-signs one
runAtDifferentDate(threeWeeksLater, func() {
pushCmd := exec.Command(dockerBinary, "push", repoName)
s.trustedCmd(pushCmd)
out, _, err := runCommandWithOutput(pushCmd)
c.Assert(err, check.IsNil, check.Commentf("Error running trusted push: %s\n%s", err, out))
c.Assert(out, checker.Contains, "Signing and pushing trust metadata", check.Commentf("Missing expected output on trusted push with expired timestamp"))
})
}
func (s *DockerTrustSuite) TestTrustedPushWithReleasesDelegationOnly(c *check.C) {
testRequires(c, NotaryHosting)
repoName := fmt.Sprintf("%v/dockerclireleasedelegationinitfirst/trusted", privateRegistryURL)
targetName := fmt.Sprintf("%s:latest", repoName)
s.notaryInitRepo(c, repoName)
s.notaryCreateDelegation(c, repoName, "targets/releases", s.not.keys[0].Public)
s.notaryPublish(c, repoName)
s.notaryImportKey(c, repoName, "targets/releases", s.not.keys[0].Private)
// tag the image and upload it to the private registry
dockerCmd(c, "tag", "busybox", targetName)
pushCmd := exec.Command(dockerBinary, "push", targetName)
s.trustedCmd(pushCmd)
out, _, err := runCommandWithOutput(pushCmd)
c.Assert(err, check.IsNil, check.Commentf("trusted push failed: %s\n%s", err, out))
c.Assert(out, checker.Contains, "Signing and pushing trust metadata", check.Commentf("Missing expected output on trusted push with existing tag"))
// check to make sure that the target has been added to targets/releases and not targets
s.assertTargetInRoles(c, repoName, "latest", "targets/releases")
s.assertTargetNotInRoles(c, repoName, "latest", "targets")
// Try pull after push
os.RemoveAll(filepath.Join(cliconfig.ConfigDir(), "trust"))
pullCmd := exec.Command(dockerBinary, "pull", targetName)
s.trustedCmd(pullCmd)
out, _, err = runCommandWithOutput(pullCmd)
c.Assert(err, check.IsNil, check.Commentf(out))
c.Assert(string(out), checker.Contains, "Status: Image is up to date", check.Commentf(out))
}
func (s *DockerTrustSuite) TestTrustedPushSignsAllFirstLevelRolesWeHaveKeysFor(c *check.C) {
testRequires(c, NotaryHosting)
repoName := fmt.Sprintf("%v/dockerclimanyroles/trusted", privateRegistryURL)
targetName := fmt.Sprintf("%s:latest", repoName)
s.notaryInitRepo(c, repoName)
s.notaryCreateDelegation(c, repoName, "targets/role1", s.not.keys[0].Public)
s.notaryCreateDelegation(c, repoName, "targets/role2", s.not.keys[1].Public)
s.notaryCreateDelegation(c, repoName, "targets/role3", s.not.keys[2].Public)
// import everything except the third key
s.notaryImportKey(c, repoName, "targets/role1", s.not.keys[0].Private)
s.notaryImportKey(c, repoName, "targets/role2", s.not.keys[1].Private)
s.notaryCreateDelegation(c, repoName, "targets/role1/subrole", s.not.keys[3].Public)
s.notaryImportKey(c, repoName, "targets/role1/subrole", s.not.keys[3].Private)
s.notaryPublish(c, repoName)
// tag the image and upload it to the private registry
dockerCmd(c, "tag", "busybox", targetName)
pushCmd := exec.Command(dockerBinary, "push", targetName)
s.trustedCmd(pushCmd)
out, _, err := runCommandWithOutput(pushCmd)
c.Assert(err, check.IsNil, check.Commentf("trusted push failed: %s\n%s", err, out))
c.Assert(out, checker.Contains, "Signing and pushing trust metadata", check.Commentf("Missing expected output on trusted push with existing tag"))
// check to make sure that the target has been added to targets/role1 and targets/role2, and
// not targets (because there are delegations) or targets/role3 (due to missing key) or
// targets/role1/subrole (due to it being a second level delegation)
s.assertTargetInRoles(c, repoName, "latest", "targets/role1", "targets/role2")
s.assertTargetNotInRoles(c, repoName, "latest", "targets")
// Try pull after push
os.RemoveAll(filepath.Join(cliconfig.ConfigDir(), "trust"))
// pull should fail because none of these are the releases role
pullCmd := exec.Command(dockerBinary, "pull", targetName)
s.trustedCmd(pullCmd)
out, _, err = runCommandWithOutput(pullCmd)
c.Assert(err, check.NotNil, check.Commentf(out))
}
func (s *DockerTrustSuite) TestTrustedPushSignsForRolesWithKeysAndValidPaths(c *check.C) {
repoName := fmt.Sprintf("%v/dockerclirolesbykeysandpaths/trusted", privateRegistryURL)
targetName := fmt.Sprintf("%s:latest", repoName)
s.notaryInitRepo(c, repoName)
s.notaryCreateDelegation(c, repoName, "targets/role1", s.not.keys[0].Public, "l", "z")
s.notaryCreateDelegation(c, repoName, "targets/role2", s.not.keys[1].Public, "x", "y")
s.notaryCreateDelegation(c, repoName, "targets/role3", s.not.keys[2].Public, "latest")
s.notaryCreateDelegation(c, repoName, "targets/role4", s.not.keys[3].Public, "latest")
// import everything except the third key
s.notaryImportKey(c, repoName, "targets/role1", s.not.keys[0].Private)
s.notaryImportKey(c, repoName, "targets/role2", s.not.keys[1].Private)
s.notaryImportKey(c, repoName, "targets/role4", s.not.keys[3].Private)
s.notaryPublish(c, repoName)
// tag the image and upload it to the private registry
dockerCmd(c, "tag", "busybox", targetName)
pushCmd := exec.Command(dockerBinary, "push", targetName)
s.trustedCmd(pushCmd)
out, _, err := runCommandWithOutput(pushCmd)
c.Assert(err, check.IsNil, check.Commentf("trusted push failed: %s\n%s", err, out))
c.Assert(out, checker.Contains, "Signing and pushing trust metadata", check.Commentf("Missing expected output on trusted push with existing tag"))
// check to make sure that the target has been added to targets/role1 and targets/role4, and
// not targets (because there are delegations) or targets/role2 (due to path restrictions) or
// targets/role3 (due to missing key)
s.assertTargetInRoles(c, repoName, "latest", "targets/role1", "targets/role4")
s.assertTargetNotInRoles(c, repoName, "latest", "targets")
// Try pull after push
os.RemoveAll(filepath.Join(cliconfig.ConfigDir(), "trust"))
// pull should fail because none of these are the releases role
pullCmd := exec.Command(dockerBinary, "pull", targetName)
s.trustedCmd(pullCmd)
out, _, err = runCommandWithOutput(pullCmd)
c.Assert(err, check.NotNil, check.Commentf(out))
}
func (s *DockerTrustSuite) TestTrustedPushDoesntSignTargetsIfDelegationsExist(c *check.C) {
testRequires(c, NotaryHosting)
repoName := fmt.Sprintf("%v/dockerclireleasedelegationnotsignable/trusted", privateRegistryURL)
targetName := fmt.Sprintf("%s:latest", repoName)
s.notaryInitRepo(c, repoName)
s.notaryCreateDelegation(c, repoName, "targets/role1", s.not.keys[0].Public)
s.notaryPublish(c, repoName)
// do not import any delegations key
// tag the image and upload it to the private registry
dockerCmd(c, "tag", "busybox", targetName)
pushCmd := exec.Command(dockerBinary, "push", targetName)
s.trustedCmd(pushCmd)
out, _, err := runCommandWithOutput(pushCmd)
c.Assert(err, check.NotNil, check.Commentf("trusted push succeeded but should have failed:\n%s", out))
c.Assert(out, checker.Contains, "no valid signing keys",
check.Commentf("Missing expected output on trusted push without keys"))
s.assertTargetNotInRoles(c, repoName, "latest", "targets", "targets/role1")
}
func (s *DockerRegistryAuthHtpasswdSuite) TestPushNoCredentialsNoRetry(c *check.C) {
repoName := fmt.Sprintf("%s/busybox", privateRegistryURL)
dockerCmd(c, "tag", "busybox", repoName)
out, _, err := dockerCmdWithError("push", repoName)
c.Assert(err, check.NotNil, check.Commentf(out))
c.Assert(out, check.Not(checker.Contains), "Retrying")
c.Assert(out, checker.Contains, "no basic auth credentials")
}
// This may be flaky but it's needed not to regress on unauthorized push, see #21054
func (s *DockerSuite) TestPushToCentralRegistryUnauthorized(c *check.C) {
testRequires(c, Network)
repoName := "test/busybox"
dockerCmd(c, "tag", "busybox", repoName)
out, _, err := dockerCmdWithError("push", repoName)
c.Assert(err, check.NotNil, check.Commentf(out))
c.Assert(out, check.Not(checker.Contains), "Retrying")
}
func getTestTokenService(status int, body string, retries int) *httptest.Server {
var mu sync.Mutex
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
mu.Lock()
if retries > 0 {
w.WriteHeader(http.StatusServiceUnavailable)
w.Header().Set("Content-Type", "application/json")
w.Write([]byte(`{"errors":[{"code":"UNAVAILABLE","message":"cannot create token at this time"}]}`))
retries--
} else {
w.WriteHeader(status)
w.Header().Set("Content-Type", "application/json")
w.Write([]byte(body))
}
mu.Unlock()
}))
}
func (s *DockerRegistryAuthTokenSuite) TestPushTokenServiceUnauthResponse(c *check.C) {
ts := getTestTokenService(http.StatusUnauthorized, `{"errors": [{"Code":"UNAUTHORIZED", "message": "a message", "detail": null}]}`, 0)
defer ts.Close()
s.setupRegistryWithTokenService(c, ts.URL)
repoName := fmt.Sprintf("%s/busybox", privateRegistryURL)
dockerCmd(c, "tag", "busybox", repoName)
out, _, err := dockerCmdWithError("push", repoName)
c.Assert(err, check.NotNil, check.Commentf(out))
c.Assert(out, checker.Not(checker.Contains), "Retrying")
c.Assert(out, checker.Contains, "unauthorized: a message")
}
func (s *DockerRegistryAuthTokenSuite) TestPushMisconfiguredTokenServiceResponseUnauthorized(c *check.C) {
ts := getTestTokenService(http.StatusUnauthorized, `{"error": "unauthorized"}`, 0)
defer ts.Close()
s.setupRegistryWithTokenService(c, ts.URL)
repoName := fmt.Sprintf("%s/busybox", privateRegistryURL)
dockerCmd(c, "tag", "busybox", repoName)
out, _, err := dockerCmdWithError("push", repoName)
c.Assert(err, check.NotNil, check.Commentf(out))
c.Assert(out, checker.Not(checker.Contains), "Retrying")
split := strings.Split(out, "\n")
c.Assert(split[len(split)-2], check.Equals, "unauthorized: authentication required")
}
func (s *DockerRegistryAuthTokenSuite) TestPushMisconfiguredTokenServiceResponseError(c *check.C) {
ts := getTestTokenService(http.StatusTooManyRequests, `{"errors": [{"code":"TOOMANYREQUESTS","message":"out of tokens"}]}`, 4)
defer ts.Close()
s.setupRegistryWithTokenService(c, ts.URL)
repoName := fmt.Sprintf("%s/busybox", privateRegistryURL)
dockerCmd(c, "tag", "busybox", repoName)
out, _, err := dockerCmdWithError("push", repoName)
c.Assert(err, check.NotNil, check.Commentf(out))
c.Assert(out, checker.Contains, "Retrying")
c.Assert(out, checker.Not(checker.Contains), "Retrying in 15")
split := strings.Split(out, "\n")
c.Assert(split[len(split)-2], check.Equals, "toomanyrequests: out of tokens")
}
func (s *DockerRegistryAuthTokenSuite) TestPushMisconfiguredTokenServiceResponseUnparsable(c *check.C) {
ts := getTestTokenService(http.StatusForbidden, `no way`, 0)
defer ts.Close()
s.setupRegistryWithTokenService(c, ts.URL)
repoName := fmt.Sprintf("%s/busybox", privateRegistryURL)
dockerCmd(c, "tag", "busybox", repoName)
out, _, err := dockerCmdWithError("push", repoName)
c.Assert(err, check.NotNil, check.Commentf(out))
c.Assert(out, checker.Not(checker.Contains), "Retrying")
split := strings.Split(out, "\n")
c.Assert(split[len(split)-2], checker.Contains, "error parsing HTTP 403 response body: ")
}
func (s *DockerRegistryAuthTokenSuite) TestPushMisconfiguredTokenServiceResponseNoToken(c *check.C) {
ts := getTestTokenService(http.StatusOK, `{"something": "wrong"}`, 0)
defer ts.Close()
s.setupRegistryWithTokenService(c, ts.URL)
repoName := fmt.Sprintf("%s/busybox", privateRegistryURL)
dockerCmd(c, "tag", "busybox", repoName)
out, _, err := dockerCmdWithError("push", repoName)
c.Assert(err, check.NotNil, check.Commentf(out))
c.Assert(out, checker.Not(checker.Contains), "Retrying")
split := strings.Split(out, "\n")
c.Assert(split[len(split)-2], check.Equals, "authorization server did not include a token in the response")
}
|
func (s *DockerTrustSuite) TestTrustedPushWithEnvPasswords(c *check.C) {
repoName := fmt.Sprintf("%v/dockerclienv/trusted:latest", privateRegistryURL)
// tag the image and upload it to the private registry
|
prototype.base.js
|
//umd pattern
|
require('./prototype.transition'), require('./prototype.transform'),require('./prototype.utils'),
require('./prototype.event'),require('./prototype.options'));
} else if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['elliptical-utils','jquery-extensions','./prototype.device',
'./prototype.template','./prototype.transition','./prototype.transform','./prototype.utils','./prototype.event','./prototype.options'], factory);
} else {
// Browser globals (root is window)
var e=root.elliptical.extensions;
root.elliptical.extensions.base = factory(root.elliptical.utils,root,e.device,
e.template,e.transition,e.transform,e.utils,e.event,e.options);
root.returnExports = root.elliptical.extensions.base;
}
}(this, function (utils,root,device,template,transition,transform,util,event,options) {
var base={};
Object.assign(base,util,device,template,transition,transform,event,options);
return base;
}));
|
(function (root, factory) {
if (typeof module !== 'undefined' && module.exports) {
//commonjs
module.exports = factory(require('elliptical-utils'),require('jquery-extensions'),require('./prototype.device'), require('./prototype.template'),
|
index.js
|
// Provides the `apostrophe-video` widget, which displays videos, powered
// by [apostrophe-video-field](/modules/apostrophe-video-fields) and
// [apostrophe-oembed](/modules/apostrophe-oembed). The video
// widget accepts the URL of a video on any website that supports the
// [oembed](http://oembed.com/) standard, including vimeo, YouTube, etc.
// In some cases the results are refined by oembetter filters configured
// by the `apostrophe-oembed` module. It is possible to configure new filters
// for that module to handle video sites that don't natively support oembed.
//
// Videos are not actually hosted or stored by Apostrophe.
//
// ## Options
//
// ### player: true
//
// If you have set `lean: true` for the `apostrophe-assets` module,
// the standard oembed-based video player does not get pushed to the
// browser, as it is part of the legacy jQuery-based frontend.
//
// However, you may opt in to a similar player that uses only a
// few lines of lean JavaScript by setting the `player` option
// of this module to `true`. You may of course skip this and
// write your own.
module.exports = {
extend: 'apostrophe-widgets',
label: 'Video',
beforeConstruct: function(self, options) {
options.addFields = [
{
type: 'video',
name: 'video',
label: 'Video URL',
htmlHelp: 'This supports Vimeo, YouTube, and many other services listed <a href="https://apostrophecms.org/video-options" target="_blank">in the widget documentation</a>.',
required: true
}
|
options.arrangeFields = [
{
name: 'basics',
label: 'Basics',
fields: ['video']
}
].concat(options.arrangeFields || []);
},
construct: function(self, options) {
if (self.apos.assets.options.lean) {
if (self.options.player) {
self.pushAsset('script', 'lean', { when: 'lean' });
}
} else {
self.pushAsset('script', 'always', { when: 'always' });
}
}
};
|
].concat(options.addFields || []);
|
admin.py
|
from polls.models import Poll, Choice
from django.contrib import admin
class ChoiceInline(admin.TabularInline):
model = Choice
extra = 3
class PollAdmin(admin.ModelAdmin):
fieldsets = [
(None, {'fields': ['question']}),
('Date information', {'fields': ['pub_date'], 'classes': ['collapse']}),
]
inlines = [ChoiceInline]
|
list_display = ('question', 'pub_date', 'was_published_recently')
list_filter = ['pub_date']
search_fields = ['question']
date_hierarchy = 'pub_date'
admin.site.register(Poll, PollAdmin)
| |
app.e2e-spec.ts
|
import { AppPage } from './app.po';
import { browser, logging } from 'protractor';
describe('workspace-project App', () => {
let page: AppPage;
beforeEach(() => {
page = new AppPage();
});
it('should display welcome message', () => {
page.navigateTo();
expect(page.getTitleText()).toEqual('power-tuner-ui app is running!');
});
afterEach(async () => {
|
// Assert that there are no errors emitted from the browser
const logs = await browser.manage().logs().get(logging.Type.BROWSER);
expect(logs).not.toContain(jasmine.objectContaining({
level: logging.Level.SEVERE,
} as logging.Entry));
});
});
| |
util_test.go
|
// Copyright 2015 The Serviced 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.
// +build unit
package volume_test
import (
"io/ioutil"
"os"
"path/filepath"
"testing"
"time"
. "github.com/control-center/serviced/volume"
. "gopkg.in/check.v1"
)
func TestUtils(t *testing.T) { TestingT(t) }
type UtilsSuite struct{}
var _ = Suite(&UtilsSuite{})
func (s *UtilsSuite) TestIsDir(c *C) {
root := c.MkDir()
// Test a directory
ok, err := IsDir(root)
c.Assert(ok, Equals, true)
c.Assert(err, IsNil)
// Test a file
file := filepath.Join(root, "afile")
ioutil.WriteFile(file, []byte("hi"), 0664)
ok, err = IsDir(file)
c.Assert(ok, Equals, false)
c.Assert(err, ErrorMatches, ErrNotADirectory.Error())
// Test a nonexistent path
ok, err = IsDir(root + "/notafile")
c.Assert(ok, Equals, false)
c.Assert(err, IsNil)
}
func (s *UtilsSuite) TestFileInfoSlice(c *C) {
root := c.MkDir()
var (
slice FileInfoSlice
stats []os.FileInfo
expected []string
data = []byte("hi")
)
expected = append(expected, "file1")
expected = append(expected, "file2")
expected = append(expected, "file3")
for _, fname := range expected {
file := filepath.Join(root, fname)
ioutil.WriteFile(file, data, 0664)
if fi, err := os.Stat(file); err == nil {
stats = append(stats, fi)
}
time.Sleep(sleepTimeMsec * time.Millisecond)
}
|
slice = append(slice, stats[1])
labels := slice.Labels()
c.Assert(labels, DeepEquals, expected)
}
|
// Append the FileInfos in non-sorted order
slice = append(slice, stats[2])
slice = append(slice, stats[0])
|
softlayer_client_fake.go
|
package client_fakes
import (
"bytes"
"errors"
"fmt"
"os"
"path/filepath"
services "github.com/maximilien/softlayer-go/services"
softlayer "github.com/maximilien/softlayer-go/softlayer"
)
const (
SOFTLAYER_API_URL = "api.softlayer.com/rest/v3"
TEMPLATE_ROOT_PATH = "templates"
)
type FakeSoftLayerClient struct {
Username string
ApiKey string
TemplatePath string
ExecShellCommandResult string
SoftLayerServices map[string]softlayer.Service
DoRawHttpRequestResponse []byte
DoRawHttpRequestResponses [][]byte
DoRawHttpRequestResponsesIndex int
DoRawHttpRequestError error
GenerateRequestBodyBuffer *bytes.Buffer
GenerateRequestBodyError error
HasErrorsError, CheckForHttpResponseError, ExecShellCommandError error
}
func
|
(username, apiKey string) *FakeSoftLayerClient {
pwd, _ := os.Getwd()
fslc := &FakeSoftLayerClient{
Username: username,
ApiKey: apiKey,
TemplatePath: filepath.Join(pwd, TEMPLATE_ROOT_PATH),
SoftLayerServices: map[string]softlayer.Service{},
DoRawHttpRequestResponse: nil,
DoRawHttpRequestResponses: [][]byte{},
DoRawHttpRequestResponsesIndex: 0,
DoRawHttpRequestError: nil,
GenerateRequestBodyBuffer: new(bytes.Buffer),
GenerateRequestBodyError: nil,
HasErrorsError: nil,
CheckForHttpResponseError: nil,
}
fslc.initSoftLayerServices()
return fslc
}
//softlayer.Client interface methods
func (fslc *FakeSoftLayerClient) GetService(serviceName string) (softlayer.Service, error) {
slService, ok := fslc.SoftLayerServices[serviceName]
if !ok {
return nil, errors.New(fmt.Sprintf("softlayer-go does not support service '%s'", serviceName))
}
return slService, nil
}
func (fslc *FakeSoftLayerClient) GetSoftLayer_Account_Service() (softlayer.SoftLayer_Account_Service, error) {
slService, err := fslc.GetService("SoftLayer_Account")
if err != nil {
return nil, err
}
return slService.(softlayer.SoftLayer_Account_Service), nil
}
func (fslc *FakeSoftLayerClient) GetSoftLayer_Virtual_Guest_Service() (softlayer.SoftLayer_Virtual_Guest_Service, error) {
slService, err := fslc.GetService("SoftLayer_Virtual_Guest")
if err != nil {
return nil, err
}
return slService.(softlayer.SoftLayer_Virtual_Guest_Service), nil
}
func (fslc *FakeSoftLayerClient) GetSoftLayer_Virtual_Disk_Image_Service() (softlayer.SoftLayer_Virtual_Disk_Image_Service, error) {
slService, err := fslc.GetService("SoftLayer_Virtual_Disk_Image")
if err != nil {
return nil, err
}
return slService.(softlayer.SoftLayer_Virtual_Disk_Image_Service), nil
}
func (fslc *FakeSoftLayerClient) GetSoftLayer_Security_Ssh_Key_Service() (softlayer.SoftLayer_Security_Ssh_Key_Service, error) {
slService, err := fslc.GetService("SoftLayer_Security_Ssh_Key")
if err != nil {
return nil, err
}
return slService.(softlayer.SoftLayer_Security_Ssh_Key_Service), nil
}
func (fslc *FakeSoftLayerClient) GetSoftLayer_Network_Storage_Service() (softlayer.SoftLayer_Network_Storage_Service, error) {
slService, err := fslc.GetService("SoftLayer_Network_Storage")
if err != nil {
return nil, err
}
return slService.(softlayer.SoftLayer_Network_Storage_Service), nil
}
func (fslc *FakeSoftLayerClient) GetSoftLayer_Product_Order_Service() (softlayer.SoftLayer_Product_Order_Service, error) {
slService, err := fslc.GetService("SoftLayer_Product_Order")
if err != nil {
return nil, err
}
return slService.(softlayer.SoftLayer_Product_Order_Service), nil
}
func (fslc *FakeSoftLayerClient) GetSoftLayer_Product_Package_Service() (softlayer.SoftLayer_Product_Package_Service, error) {
slService, err := fslc.GetService("SoftLayer_Product_Package")
if err != nil {
return nil, err
}
return slService.(softlayer.SoftLayer_Product_Package_Service), nil
}
func (fslc *FakeSoftLayerClient) GetSoftLayer_Billing_Item_Cancellation_Request_Service() (softlayer.SoftLayer_Billing_Item_Cancellation_Request_Service, error) {
slService, err := fslc.GetService("SoftLayer_Billing_Item_Cancellation_Request")
if err != nil {
return nil, err
}
return slService.(softlayer.SoftLayer_Billing_Item_Cancellation_Request_Service), nil
}
func (fslc *FakeSoftLayerClient) GetSoftLayer_Virtual_Guest_Block_Device_Template_Group_Service() (softlayer.SoftLayer_Virtual_Guest_Block_Device_Template_Group_Service, error) {
slService, err := fslc.GetService("SoftLayer_Virtual_Guest_Block_Device_Template_Group")
if err != nil {
return nil, err
}
return slService.(softlayer.SoftLayer_Virtual_Guest_Block_Device_Template_Group_Service), nil
}
func (fslc *FakeSoftLayerClient) GetSoftLayer_Hardware_Service() (softlayer.SoftLayer_Hardware_Service, error) {
slService, err := fslc.GetService("SoftLayer_Hardware")
if err != nil {
return nil, err
}
return slService.(softlayer.SoftLayer_Hardware_Service), nil
}
//Public methods
func (fslc *FakeSoftLayerClient) DoRawHttpRequestWithObjectMask(path string, masks []string, requestType string, requestBody *bytes.Buffer) ([]byte, error) {
if fslc.DoRawHttpRequestError != nil {
return []byte{}, fslc.DoRawHttpRequestError
}
if fslc.DoRawHttpRequestResponse != nil {
return fslc.DoRawHttpRequestResponse, fslc.DoRawHttpRequestError
} else {
fslc.DoRawHttpRequestResponsesIndex = fslc.DoRawHttpRequestResponsesIndex + 1
return fslc.DoRawHttpRequestResponses[fslc.DoRawHttpRequestResponsesIndex-1], fslc.DoRawHttpRequestError
}
}
func (fslc *FakeSoftLayerClient) DoRawHttpRequest(path string, requestType string, requestBody *bytes.Buffer) ([]byte, error) {
if fslc.DoRawHttpRequestError != nil {
return []byte{}, fslc.DoRawHttpRequestError
}
if fslc.DoRawHttpRequestResponse != nil {
return fslc.DoRawHttpRequestResponse, fslc.DoRawHttpRequestError
} else {
fslc.DoRawHttpRequestResponsesIndex = fslc.DoRawHttpRequestResponsesIndex + 1
return fslc.DoRawHttpRequestResponses[fslc.DoRawHttpRequestResponsesIndex-1], fslc.DoRawHttpRequestError
}
}
func (fslc *FakeSoftLayerClient) GenerateRequestBody(templateData interface{}) (*bytes.Buffer, error) {
return fslc.GenerateRequestBodyBuffer, fslc.GenerateRequestBodyError
}
func (fslc *FakeSoftLayerClient) HasErrors(body map[string]interface{}) error {
return fslc.HasErrorsError
}
func (fslc *FakeSoftLayerClient) CheckForHttpResponseErrors(data []byte) error {
return fslc.CheckForHttpResponseError
}
func (fslc *FakeSoftLayerClient) ExecShellCommand(username string, password string, ip string, command string) (string, error) {
return fslc.ExecShellCommandResult, fslc.ExecShellCommandError
}
//Private methods
func (fslc *FakeSoftLayerClient) initSoftLayerServices() {
fslc.SoftLayerServices["SoftLayer_Account"] = services.NewSoftLayer_Account_Service(fslc)
fslc.SoftLayerServices["SoftLayer_Virtual_Guest"] = services.NewSoftLayer_Virtual_Guest_Service(fslc)
fslc.SoftLayerServices["SoftLayer_Virtual_Disk_Image"] = services.NewSoftLayer_Virtual_Disk_Image_Service(fslc)
fslc.SoftLayerServices["SoftLayer_Security_Ssh_Key"] = services.NewSoftLayer_Security_Ssh_Key_Service(fslc)
fslc.SoftLayerServices["SoftLayer_Network_Storage"] = services.NewSoftLayer_Network_Storage_Service(fslc)
fslc.SoftLayerServices["SoftLayer_Product_Order"] = services.NewSoftLayer_Product_Order_Service(fslc)
fslc.SoftLayerServices["SoftLayer_Product_Package"] = services.NewSoftLayer_Product_Package_Service(fslc)
fslc.SoftLayerServices["SoftLayer_Billing_Item_Cancellation_Request"] = services.NewSoftLayer_Billing_Item_Cancellation_Request_Service(fslc)
fslc.SoftLayerServices["SoftLayer_Virtual_Guest_Block_Device_Template_Group"] = services.NewSoftLayer_Virtual_Guest_Block_Device_Template_Group_Service(fslc)
fslc.SoftLayerServices["SoftLayer_Hardware"] = services.NewSoftLayer_Hardware_Service(fslc)
}
|
NewFakeSoftLayerClient
|
default_params_spread_opr.js
|
"use strict"
// Default parameters
function greet($greeting = 'Hello world!'){
console.log($greeting);
}
greet();
// Spread operator
let args1 = [1,2,3];
let args2 = [4,5,6];
function
|
(){
console.log(args1+','+ args2);
}
// Using apply() method to pass an array as an argument
test.apply(null, args1);
// Using spread operator to pass an array as an argument
test(...args1, ...args2);
|
test
|
test_packer.py
|
import mock
import pytest
import random
from speech_packer import Packer, SpeechAnalyzer
ITEMS = ['t-shirt', 'jeans', 'raincoat', 'sneakers', 'hiking boots']
@mock.patch("speech_packer.SpeechAnalyzer")
def test__add_item(mock_analyzer):
item = random.choice(ITEMS)
mock_analyzer.process_single_phrase.return_value = item
pckr = Packer(mock_analyzer)
pckr._add_item()
assert pckr._to_pack == set([item])
@mock.patch("speech_packer.SpeechAnalyzer")
def test__pack_item(mock_analyzer):
item = random.choice(ITEMS)
mock_analyzer.process_single_phrase.return_value = item
pckr = Packer(mock_analyzer)
pckr._add_item()
pckr._pack_item()
assert pckr._to_pack == set()
assert pckr._packed == set([item])
@mock.patch("speech_packer.SpeechAnalyzer")
def test__pack_item_failure(mock_analyzer):
item = random.choice(ITEMS)
mock_analyzer.process_single_phrase.return_value = item
pckr = Packer(mock_analyzer)
pckr._pack_item()
assert pckr._to_pack == set()
assert pckr._packed == set()
@mock.patch("speech_packer.SpeechAnalyzer")
def test__delete_item(mock_analyzer):
|
item1 = ITEMS[0]
item2 = ITEMS[1]
item3 = ITEMS[2]
mock_analyzer.process_single_phrase.return_value = item1
pckr = Packer(mock_analyzer)
pckr._add_item()
mock_analyzer.process_single_phrase.return_value = item2
pckr._add_item()
assert pckr._to_pack == set([item1, item2])
pckr._pack_item()
assert pckr._to_pack == set([item1])
assert pckr._packed == set([item2])
# deleting a non existent item
mock_analyzer.process_single_phrase.return_value = item3
pckr._delete_item()
assert pckr._to_pack == set([item1])
assert pckr._packed == set([item2])
# deleting an item that was packed
mock_analyzer.process_single_phrase.return_value = item2
pckr._delete_item()
assert pckr._to_pack == set([item1])
assert pckr._packed == set()
# deleting an item that was added
mock_analyzer.process_single_phrase.return_value = item1
pckr._delete_item()
assert pckr._to_pack == set()
assert pckr._packed == set()
|
|
evmxgodb.go
|
package executor
import (
"encoding/json"
"fmt"
"github.com/33cn/chain33/account"
"github.com/33cn/chain33/client"
dbm "github.com/33cn/chain33/common/db"
"github.com/33cn/chain33/types"
evmxgotypes "github.com/33cn/plugin/plugin/dapp/evmxgo/types"
)
type evmxgoDB struct {
evmxgo evmxgotypes.Evmxgo
}
func newEvmxgoDB(mint *evmxgotypes.EvmxgoMint) *evmxgoDB {
e := &evmxgoDB{}
e.evmxgo.Symbol = mint.GetSymbol()
return e
}
func (e *evmxgoDB) save(db dbm.KV, key []byte) {
set := e.getKVSet(key)
for i := 0; i < len(set); i++ {
err := db.Set(set[i].GetKey(), set[i].Value)
if err != nil {
panic(err)
}
}
}
func (e *evmxgoDB) getLogs(ty int32, status int32) []*types.ReceiptLog {
var log []*types.ReceiptLog
value := types.Encode(&evmxgotypes.ReceiptEvmxgo{Symbol: e.evmxgo.Symbol})
log = append(log, &types.ReceiptLog{Ty: ty, Log: value})
return log
}
//key:mavl-create-token-addr-xxx or mavl-token-xxx <-----> value:token
func (e *evmxgoDB) getKVSet(key []byte) (kvset []*types.KeyValue) {
value := types.Encode(&e.evmxgo)
kvset = append(kvset, &types.KeyValue{Key: key, Value: value})
return kvset
}
func loadEvmxgoDB(db dbm.KV, symbol string) (*evmxgoDB, error) {
evmxgo, err := db.Get(calcEvmxgoKey(symbol))
if err != nil {
elog.Error("evmxgodb load ", "Can't get token form db for token", symbol)
return nil, evmxgotypes.ErrEvmxgoSymbolNotExist
}
var e evmxgotypes.Evmxgo
err = types.Decode(evmxgo, &e)
if err != nil {
elog.Error("evmxgodb load", "Can't decode token info", symbol)
return nil, err
}
return &evmxgoDB{e}, nil
}
func safeAdd(balance, amount int64) (int64, error) {
if balance+amount < amount || balance+amount > types.MaxTokenBalance {
return balance, types.ErrAmount
}
return balance + amount, nil
}
func (e *evmxgoDB) mint(amount int64) ([]*types.KeyValue, []*types.ReceiptLog, error) {
newTotal, err := safeAdd(e.evmxgo.Total, amount)
if err != nil {
return nil, nil, err
}
prevEvmxgo := e.evmxgo
e.evmxgo.Total = newTotal
kvs := e.getKVSet(calcEvmxgoKey(e.evmxgo.Symbol))
logs := []*types.ReceiptLog{{Ty: evmxgotypes.TyLogEvmxgoMint, Log: types.Encode(&evmxgotypes.ReceiptEvmxgoAmount{Prev: &prevEvmxgo, Current: &e.evmxgo})}}
return kvs, logs, nil
}
func (e *evmxgoDB) mintMap(amount int64) ([]*types.KeyValue, []*types.ReceiptLog, error) {
newTotal, err := safeAdd(e.evmxgo.Total, amount)
if err != nil {
return nil, nil, err
}
prevEvmxgo := e.evmxgo
e.evmxgo.Total = newTotal
kvs := e.getKVSet(calcEvmxgoKey(e.evmxgo.Symbol))
logs := []*types.ReceiptLog{{Ty: evmxgotypes.TyLogEvmxgoMintMap, Log: types.Encode(&evmxgotypes.ReceiptEvmxgoAmount{Prev: &prevEvmxgo, Current: &e.evmxgo})}}
return kvs, logs, nil
}
func (e *evmxgoDB) burn(db dbm.KV, amount int64) ([]*types.KeyValue, []*types.ReceiptLog, error) {
if e.evmxgo.Total < amount {
return nil, nil, types.ErrNoBalance
}
prevToken := e.evmxgo
e.evmxgo.Total -= amount
kvs := e.getKVSet(calcEvmxgoKey(e.evmxgo.Symbol))
logs := []*types.ReceiptLog{{Ty: evmxgotypes.TyLogEvmxgoBurn, Log: types.Encode(&evmxgotypes.ReceiptEvmxgoAmount{Prev: &prevToken, Current: &e.evmxgo})}}
return kvs, logs, nil
}
func (e *evmxgoDB) burnMap(db dbm.KV, amount int64) ([]*types.KeyValue, []*types.ReceiptLog, error) {
if e.evmxgo.Total < amount {
return nil, nil, types.ErrNoBalance
}
prevToken := e.evmxgo
e.evmxgo.Total -= amount
kvs := e.getKVSet(calcEvmxgoKey(e.evmxgo.Symbol))
logs := []*types.ReceiptLog{{Ty: evmxgotypes.TyLogEvmxgoBurnMap, Log: types.Encode(&evmxgotypes.ReceiptEvmxgoAmount{Prev: &prevToken, Current: &e.evmxgo})}}
return kvs, logs, nil
}
type evmxgoAction struct {
stateDB dbm.KV
txhash []byte
fromaddr string
blocktime int64
height int64
api client.QueueProtocolAPI
}
func newEvmxgoAction(e *evmxgo, tx *types.Transaction) *evmxgoAction {
return &evmxgoAction{e.GetStateDB(), tx.Hash(),
tx.From(), e.GetBlockTime(), e.GetHeight(), e.GetAPI()}
}
func getManageKey(key string, db dbm.KV) ([]byte, error) {
manageKey := types.ManageKey(key)
value, err := db.Get([]byte(manageKey))
if err != nil {
elog.Info("evmxgodb", "get stateDB key", "not found manageKey", "key", manageKey)
return getConfigKey(key, db)
}
return value, nil
}
func getConfigKey(key string, db dbm.KV) ([]byte, error) {
configKey := types.ConfigKey(key)
value, err := db.Get([]byte(configKey))
if err != nil {
elog.Info("evmxgodb", "get db key", "not found configKey", "key", configKey)
return nil, err
}
return value, nil
}
func hasConfiged(v1, key string, db dbm.KV) (bool, error) {
value, err := getManageKey(key, db)
if err != nil {
elog.Info("evmxgodb", "get db key", "not found", "key", key)
return false, err
}
if value == nil {
elog.Info("evmxgodb", "get db key", " found nil value", "key", key)
return false, nil
}
var item types.ConfigItem
err = types.Decode(value, &item)
if err != nil {
elog.Error("evmxgodb", "get db key", err)
return false, err // types.ErrBadConfigValue
}
for _, v := range item.GetArr().Value {
if v == v1 {
return true, nil
}
}
return false, nil
}
func loadEvmxgoMintConfig(db dbm.KV, symbol string) (*evmxgotypes.EvmxgoMintConfig, error) {
key := fmt.Sprintf(mintPrefix+"%s", symbol)
value, err := getManageKey(key, db)
if err != nil {
elog.Info("evmxgodb", "get db key", "not found", "key", key)
return nil, err
}
if value == nil {
elog.Info("evmxgodb", "get db key", " found nil value", "key", key)
return nil, nil
}
elog.Info("loadEvmxgoMintConfig", "value", string(value))
var item types.ConfigItem
err = types.Decode(value, &item)
if err != nil {
elog.Error("evmxgodb load loadEvmxgoMintConfig", "Can't decode ConfigItem", symbol)
return nil, err // types.ErrBadConfigValue
}
configValue := item.GetArr().Value
if len(configValue) <= 0 {
return nil, evmxgotypes.ErrEvmxgoSymbolNotConfigValue
}
var e evmxgotypes.EvmxgoMintConfig
err = json.Unmarshal([]byte(configValue[0]), &e)
if err != nil {
elog.Error("evmxgodb load", "Can't decode token info", symbol)
return nil, err
}
return &e, nil
}
func calcTokenAssetsKey(addr string) []byte {
return []byte(fmt.Sprintf(evmxgoAssetsPrefix+"%s", addr))
}
func getTokenAssetsKey(addr string, db dbm.KVDB) (*types.ReplyStrings, error) {
key := calcTokenAssetsKey(addr)
value, err := db.Get(key)
if err != nil && err != types.ErrNotFound {
elog.Error("evmxgodb", "GetTokenAssetsKey", err)
return nil, err
}
var assets types.ReplyStrings
if err == types.ErrNotFound {
return &assets, nil
}
err = types.Decode(value, &assets)
if err != nil {
elog.Error("evmxgodb", "GetTokenAssetsKey", err)
return nil, err
}
return &assets, nil
}
// AddTokenToAssets 添加个人资产列表
func AddTokenToAssets(addr string, db dbm.KVDB, symbol string) []*types.KeyValue {
tokenAssets,
|
。 2选1
// 1. 谁可以发起
// 2. 是否需要审核 这个会增加管理的成本
// 现在实现选择 1
func (action *evmxgoAction) mint(mint *evmxgotypes.EvmxgoMint, tx2lock *types.Transaction) (*types.Receipt, error) {
if mint == nil {
return nil, types.ErrInvalidParam
}
if mint.GetAmount() < 0 || mint.GetAmount() > types.MaxTokenBalance || mint.GetSymbol() == "" {
return nil, types.ErrInvalidParam
}
cfg := action.api.GetConfig()
if err := checkMintPara(mint, tx2lock, action.stateDB); nil != err {
return nil, err
}
// evmxgo合约,配置symbol对应的实际地址,检验地址正确才能发币
configSymbol, err := loadEvmxgoMintConfig(action.stateDB, mint.GetSymbol())
if err != nil || configSymbol == nil {
elog.Error("evmxgo mint ", "not config symbol", mint.GetSymbol(), "error", err)
return nil, evmxgotypes.ErrEvmxgoSymbolNotAllowedMint
}
if mint.BridgeToken != configSymbol.Address {
elog.Error("evmxgo mint ", "NotCorrectBridgeTokenAddress with address by manager", configSymbol.Address, "mint.BridgeToken", mint.BridgeToken)
return nil, evmxgotypes.ErrNotCorrectBridgeTokenAddress
}
evmxgodb, err := loadEvmxgoDB(action.stateDB, mint.GetSymbol())
if err != nil {
if err != evmxgotypes.ErrEvmxgoSymbolNotExist {
return nil, err
}
evmxgodb = newEvmxgoDB(mint)
}
kvs, logs, err := evmxgodb.mint(mint.Amount)
if err != nil {
elog.Error("evmxgo mint ", "symbol", mint.GetSymbol(), "error", err, "from", action.fromaddr)
return nil, err
}
evmxgoAccount, err := account.NewAccountDB(cfg, "evmxgo", mint.GetSymbol(), action.stateDB)
if err != nil {
return nil, err
}
elog.Debug("mint", "evmxgo.Symbol", mint.Symbol, "evmxgo.Amount", mint.Amount)
receipt, err := evmxgoAccount.Mint(mint.Recipient, mint.Amount)
if err != nil {
return nil, err
}
logs = append(logs, receipt.Logs...)
kvs = append(kvs, receipt.KV...)
return &types.Receipt{Ty: types.ExecOk, KV: kvs, Logs: logs}, nil
}
func (action *evmxgoAction) burn(burn *evmxgotypes.EvmxgoBurn) (*types.Receipt, error) {
if burn == nil {
return nil, types.ErrInvalidParam
}
if burn.GetAmount() < 0 || burn.GetAmount() > types.MaxTokenBalance || burn.GetSymbol() == "" {
return nil, types.ErrInvalidParam
}
evmxgodb, err := loadEvmxgoDB(action.stateDB, burn.GetSymbol())
if err != nil {
return nil, err
}
kvs, logs, err := evmxgodb.burn(action.stateDB, burn.Amount)
if err != nil {
elog.Error("evmxgo burn ", "symbol", burn.GetSymbol(), "error", err, "from", action.fromaddr)
return nil, err
}
chain33cfg := action.api.GetConfig()
evmxgoAccount, err := account.NewAccountDB(chain33cfg, "evmxgo", burn.GetSymbol(), action.stateDB)
if err != nil {
return nil, err
}
elog.Debug("evmxgo burn", "burn.Symbol", burn.Symbol, "burn.Amount", burn.Amount)
receipt, err := evmxgoAccount.Burn(action.fromaddr, burn.Amount)
if err != nil {
return nil, err
}
logs = append(logs, receipt.Logs...)
kvs = append(kvs, receipt.KV...)
return &types.Receipt{Ty: types.ExecOk, KV: kvs, Logs: logs}, nil
}
func (action *evmxgoAction) mintMap(mint *evmxgotypes.EvmxgoMintMap, tx *types.Transaction) (*types.Receipt, error) {
evmxgodb, err := loadEvmxgoDB(action.stateDB, mint.GetSymbol())
if err != nil {
if err != evmxgotypes.ErrEvmxgoSymbolNotExist {
return nil, err
}
evmxgodb = newEvmxgoDB(&evmxgotypes.EvmxgoMint{
Symbol: mint.Symbol,
Amount: mint.Amount,
BridgeToken: mint.BridgeToken,
Recipient: mint.Recipient,
Extra: mint.Extra,
})
}
kvs, logs, err := evmxgodb.mintMap(mint.Amount)
if err != nil {
elog.Error("evmxgo mint ", "symbol", mint.GetSymbol(), "error", err, "from", action.fromaddr)
return nil, err
}
cfg := action.api.GetConfig()
evmxgoAccount, err := account.NewAccountDB(cfg, "evmxgo", mint.GetSymbol(), action.stateDB)
if err != nil {
return nil, err
}
elog.Debug("mint", "evmxgo.Symbol", mint.Symbol, "evmxgo.Amount", mint.Amount)
receipt, err := evmxgoAccount.Mint(mint.Recipient, mint.Amount)
if err != nil {
return nil, err
}
logs = append(logs, receipt.Logs...)
kvs = append(kvs, receipt.KV...)
return &types.Receipt{Ty: types.ExecOk, KV: kvs, Logs: logs}, nil
}
func (action *evmxgoAction) burnMap(burn *evmxgotypes.EvmxgoBurnMap) (*types.Receipt, error) {
if burn == nil {
return nil, types.ErrInvalidParam
}
if burn.GetAmount() < 0 || burn.GetAmount() > types.MaxTokenBalance || burn.GetSymbol() == "" {
return nil, types.ErrInvalidParam
}
evmxgodb, err := loadEvmxgoDB(action.stateDB, burn.GetSymbol())
if err != nil {
return nil, err
}
kvs, logs, err := evmxgodb.burnMap(action.stateDB, burn.Amount)
if err != nil {
elog.Error("evmxgo burn ", "symbol", burn.GetSymbol(), "error", err, "from", action.fromaddr)
return nil, err
}
chain33cfg := action.api.GetConfig()
evmxgoAccount, err := account.NewAccountDB(chain33cfg, "evmxgo", burn.GetSymbol(), action.stateDB)
if err != nil {
return nil, err
}
elog.Debug("evmxgo burn", "burn.Symbol", burn.Symbol, "burn.Amount", burn.Amount)
receipt, err := evmxgoAccount.Burn(action.fromaddr, burn.Amount)
if err != nil {
return nil, err
}
logs = append(logs, receipt.Logs...)
kvs = append(kvs, receipt.KV...)
return &types.Receipt{Ty: types.ExecOk, KV: kvs, Logs: logs}, nil
}
|
err := getTokenAssetsKey(addr, db)
if err != nil {
return nil
}
if tokenAssets == nil {
tokenAssets = &types.ReplyStrings{}
}
var found = false
for _, sym := range tokenAssets.Datas {
if sym == symbol {
found = true
break
}
}
if !found {
tokenAssets.Datas = append(tokenAssets.Datas, symbol)
}
var kv []*types.KeyValue
kv = append(kv, &types.KeyValue{Key: calcTokenAssetsKey(addr), Value: types.Encode(tokenAssets)})
return kv
}
// 铸币不可控, 也是麻烦
|
RecommenderSVD.py
|
from collections import defaultdict
from operator import itemgetter
# python -m movies_recommender.RecommenderSVD
from movies_analyzer.Movies import Movies
from movies_analyzer.RecommendationDataset import RecommendationDataSet
from movies_recommender.Recommender import Recommender
from surprise import SVD, KNNBasic
from movies_recommender.utils import get_top_n
class RecommenderSVD(Recommender):
def __init__(self, recommendation_dataset: RecommendationDataSet):
super(RecommenderSVD, self).__init__(recommendation_dataset.movies)
self.algorithm = SVD()
self.recommendation_dataset = recommendation_dataset
def fit(self, dataset):
return self.algorithm.fit(dataset)
def test(self, test_set):
return self.algorithm.test(test_set)
def get_recommendation(self, watched, k=20):
# get dataset
|
if __name__ == '__main__':
from movies_recommender.Recommender import test_recommendation
from movies_recommender.RecommenderSVD import RecommenderSVD
from movies_analyzer.RecommendationDataset import RecommendationDataSet
from movies_analyzer.Movies import Movies
movies = Movies()
recommendation_dataset = RecommendationDataSet(movies=movies)
recommender = RecommenderSVD(recommendation_dataset)
assert recommender.__module__[:len('movies_recommender.')] == 'movies_recommender.'
test_recommendation(recommender, recommendation_dataset,
example_items=['arek','mateusz'], anti_test=True)
""" For test only
%load_ext autoreload
%autoreload 2
from filmweb_integrator.fwimdbmerge.filmweb import Filmweb
from filmweb_integrator.fwimdbmerge.merger import Merger, get_json_df
from movies_recommender.Recommender import get_moviescore_df, get_watched
recommender.fit(recommendation_dataset.full_dataset)
self = recommender
# get recommendation for one user
merger = Merger(filmweb=Filmweb(), imdb=movies.imdb)
watched = get_watched(get_moviescore_df(merger, recommender.movies,'arek'))
k = 20
k_inner_item = 20
self.get_recommendation(watched)
"""
|
new_user_id, full_dataset = self.recommendation_dataset.get_dataset_with_extended_user(watched)
inner_user_id = full_dataset.to_inner_uid(new_user_id)
# after new dataset we need again train our model with the new user for the whole
# dataset with the new user.
self.algorithm.fit(full_dataset)
# watched movies
watched = {full_dataset.to_inner_iid(key): value for key,value in watched.items()}
# Calculate for all similar user, predictions
test_items = [
self.algorithm.predict(new_user_id, full_dataset.to_raw_iid(i))
for i in range(0, full_dataset.n_items)
if i not in watched
]
topn_items = [i[0] for i in get_top_n(test_items, n=k, minimum_rating=1.0)[new_user_id]]
return self.movies.get_movie_by_movie_ids(topn_items)
|
task_state.rs
|
/*
* Nomad
*
* Nomad OpenApi specification
*
* The version of the OpenAPI document: 0.11.0
*
* Generated by: https://openapi-generator.tech
|
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct TaskState {
#[serde(rename = "State", skip_serializing_if = "Option::is_none")]
pub state: Option<String>,
#[serde(rename = "Failed", skip_serializing_if = "Option::is_none")]
pub failed: Option<bool>,
#[serde(rename = "Restarts", skip_serializing_if = "Option::is_none")]
pub restarts: Option<i32>,
#[serde(rename = "LastRestart", skip_serializing_if = "Option::is_none")]
pub last_restart: Option<String>,
#[serde(rename = "StartedAt", skip_serializing_if = "Option::is_none")]
pub started_at: Option<String>,
#[serde(rename = "FinishedAt", skip_serializing_if = "Option::is_none")]
pub finished_at: Option<String>,
#[serde(rename = "Events", skip_serializing_if = "Option::is_none")]
pub events: Option<Vec<crate::models::TaskEvent>>,
}
impl TaskState {
pub fn new() -> TaskState {
TaskState {
state: None,
failed: None,
restarts: None,
last_restart: None,
started_at: None,
finished_at: None,
events: None,
}
}
}
|
*/
|
0001_initial.py
|
# Generated by Django 3.1.1 on 2020-10-15 01:08
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
dependencies = [
('school', '0001_initial'),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='SubjectTable',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('day', models.DateField(blank=True, default=django.utils.timezone.now, null=True)),
('time', models.SmallIntegerField(blank=True, default=0)),
('is_event_or_holi', models.BooleanField(default=False)),
('classroom', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='school.classroom')),
('semester', models.ForeignKey(blank=True, on_delete=django.db.models.deletion.CASCADE, to='school.term')),
('subject', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='school.subject')),
('teacher', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='main_sub_teacher', to=settings.AUTH_USER_MODEL)),
],
options={
'abstract': False,
|
'unique_together': {('day', 'time', 'teacher')},
},
),
migrations.CreateModel(
name='Invited',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('day', models.DateField(blank=True, default=django.utils.timezone.now, null=True)),
('time', models.SmallIntegerField(blank=True, default=0)),
('is_event_or_holi', models.BooleanField(default=False)),
('classroom', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='school.classroom')),
('semester', models.ForeignKey(blank=True, on_delete=django.db.models.deletion.CASCADE, to='school.term')),
('subject', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='school.subject')),
('teacher', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='invited_teacher', to=settings.AUTH_USER_MODEL)),
],
options={
'abstract': False,
'unique_together': {('day', 'time', 'teacher')},
},
),
migrations.CreateModel(
name='HomeTable',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('day', models.DateField(blank=True, default=django.utils.timezone.now, null=True)),
('time', models.SmallIntegerField(blank=True, default=0)),
('is_event_or_holi', models.BooleanField(default=False)),
('classroom', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='school.classroom')),
('inv_teacher', models.OneToOneField(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='timetable.invited')),
('semester', models.ForeignKey(blank=True, on_delete=django.db.models.deletion.CASCADE, to='school.term')),
('sub_teacher', models.OneToOneField(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='timetable.subjecttable')),
('subject', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='school.subject')),
('teacher', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='main_home_teacher', to=settings.AUTH_USER_MODEL)),
],
options={
'abstract': False,
'unique_together': {('day', 'time', 'teacher')},
},
),
]
| |
utils_test.go
|
package conntracker
import (
"net"
"testing"
)
func TestIPToUInt32(t *testing.T) {
type args struct {
ip net.IP
}
tests := []struct {
name string
args args
want uint32
}{
{name: "", args: args{ip: net.IPv4(1, 2, 3, 4)}, want: 67305985},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := IPToUInt32(tt.args.ip); got != tt.want {
t.Errorf("IPToUInt32() = %v, want %v", got, tt.want)
}
})
}
}
func
|
(t *testing.T) {
type args struct {
ip string
}
tests := []struct {
name string
args args
want uint32
}{
{name: "normal", args: args{ip: "1.2.3.4"}, want: 67305985},
{name: "illegal", args: args{ip: "1.2"}, want: 0},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := StringToUint32(tt.args.ip); got != tt.want {
t.Errorf("StringToUint32() = %v, want %v", got, tt.want)
}
})
}
}
|
TestStringToUint32
|
0015_alter_run_pipeline_command.py
|
# Generated by Django 3.2.9 on 2021-11-25 10:37
from django.db import migrations, models
class Migration(migrations.Migration):
|
dependencies = [
('run', '0014_run_duration'),
]
operations = [
migrations.AlterField(
model_name='run',
name='pipeline_command',
field=models.CharField(blank=True, max_length=600, null=True),
),
]
|
|
builder.rs
|
use std::collections::HashMap;
use std::borrow::Borrow;
use std::ops::Deref;
use std::ffi::CString;
use llvm_sys::*;
use llvm_sys::core::*;
use llvm_sys::prelude::*;
use atom::Atom;
use compiler::types::*;
use runtime::stl::Externals;
use runtime::types::Function;
use vmf::ir::Entity;
pub type Type = LLVMTypeRef;
pub type Value = LLVMValueRef;
pub type Block = LLVMBasicBlockRef;
#[derive(Debug)]
pub struct Builder {
context: LLVMContextRef,
module: LLVMModuleRef,
func: Value,
builder: LLVMBuilderRef,
entities: HashMap<Atom, Entity>,
globals: HashMap<Global, Value>,
externals: Externals,
}
pub struct ModuleHolder {
context: LLVMContextRef,
pub ptr: LLVMModuleRef,
}
impl Drop for ModuleHolder {
fn drop(&mut self) {
unsafe {
LLVMContextDispose(self.context);
}
}
}
pub type BuilderResult = (
ModuleHolder,
HashMap<Atom, Entity>,
HashMap<Global, Value>,
Externals,
);
impl Builder {
pub fn new(name: &str, entities: HashMap<Atom, Entity>) -> Builder {
let context = unsafe {
LLVMContextCreate()
};
let module = {
let mod_name = CString::new(name).unwrap();
unsafe {
LLVMModuleCreateWithNameInContext(mod_name.as_ptr(), context)
}
};
let builder = unsafe {
LLVMCreateBuilderInContext(context)
};
let main = {
let i8_ty = unsafe { LLVMInt8TypeInContext(context) };
let mut params = vec![unsafe {
LLVMPointerType(
i8_ty,
0
)
}];
let main_type = unsafe {
LLVMFunctionType(
LLVMVoidTypeInContext(context),
params.as_mut_ptr(),
params.len() as u32,
0
)
};
let func_name = CString::new("main").unwrap();
unsafe {
LLVMAddFunction(module, func_name.as_ptr(), main_type)
}
};
let entry_name = CString::new("entry").unwrap();
let entry_block = unsafe {
LLVMAppendBasicBlockInContext(context, main, entry_name.as_ptr())
};
let start_name = CString::new("start").unwrap();
let start_block = unsafe {
LLVMAppendBasicBlockInContext(context, main, start_name.as_ptr())
};
unsafe {
LLVMPositionBuilderAtEnd(builder, entry_block);
LLVMBuildBr(builder, start_block);
LLVMPositionBuilderAtEnd(builder, start_block)
}
Builder {
context,
module,
builder,
func: main,
entities,
globals: Default::default(),
externals: Externals::new(),
}
}
pub fn finalize(self) -> BuilderResult {
unsafe {
LLVMBuildRetVoid(self.builder);
LLVMDisposeBuilder(self.builder);
}
(
ModuleHolder {
context: self.context,
ptr: self.module,
},
self.entities,
self.globals,
self.externals,
)
}
fn global_ptr<S, T>(&mut self, ty: TypeId, val: S) -> ValueRef where S: Borrow<T>, T: ToOwned + Deref<Target=str>, Global: From<<T as ToOwned>::Owned> {
let cmp_ty = self.get_type(&ty);
let &mut Builder { ref mut globals, module, .. } = self;
let val = val.borrow();
let glob = Global::from(val.to_owned());
let &mut ptr = globals.entry(glob).or_insert_with(|| {
let name = CString::new(global_name(&ty, val)).unwrap();
unsafe {
LLVMAddGlobalInAddressSpace(
module,
LLVMGetElementType(cmp_ty),
name.as_ptr(),
0
)
}
});
ValueRef { ty, ptr }
}
}
/*impl Drop for Builder {
fn drop(&mut self) {
unsafe {
LLVMDisposeBuilder(self.builder);
}
}
}*/
static EMPTY_STRING: [i8; 1] = [0];
macro_rules! builder_forward {
($name:ident ( $( $args:ident ),* ) -> $ret:tt = $op:ident ) => {
pub fn $name(&mut self, $( $args: &ValueRef ),* ) -> ValueRef {
ValueRef {
ty: TypeId::$ret,
ptr: unsafe {
$op(self.builder, $( $args.ptr, )* EMPTY_STRING.as_ptr())
},
}
}
};
}
macro_rules! builder_cmp {
($name:ident<f64, $pred:ident>( $( $args:ident ),* ) ) => {
pub fn $name(&mut self, $( $args: &ValueRef ),* ) -> ValueRef {
ValueRef {
ty: TypeId::bool,
ptr: unsafe {
LLVMBuildFCmp(self.builder, LLVMRealPredicate::$pred, $( $args.ptr, )* EMPTY_STRING.as_ptr())
},
}
}
};
($name:ident<i64, $pred:ident>( $( $args:ident ),* ) ) => {
pub fn $name(&mut self, $( $args: &ValueRef ),* ) -> ValueRef {
ValueRef {
ty: TypeId::bool,
ptr: unsafe {
LLVMBuildICmp(self.builder, LLVMIntPredicate::$pred, $( $args.ptr, )* EMPTY_STRING.as_ptr())
},
}
}
};
}
impl Builder {
pub fn get_type(&self, ty: &TypeId) -> Type {
match *ty {
TypeId::Context | TypeId::Entity |
TypeId::Atom | TypeId::String |
TypeId::Vec { .. } => unsafe {
LLVMPointerType(LLVMInt8TypeInContext(self.context), 0)
},
TypeId::Array { ref len, ref ty } => unsafe {
LLVMPointerType(
LLVMArrayType(
self.get_type(ty),
*len as u32,
),
0,
)
},
TypeId::Object { ref items } => {
let mut items: Vec<_> = {
items.iter()
.map(|&(_, ref ty)| self.get_type(ty))
.collect()
};
unsafe {
LLVMPointerType(
LLVMStructTypeInContext(
self.context,
items.as_mut_ptr(),
items.len() as _,
0,
),
0,
)
}
},
TypeId::f64 => unsafe { LLVMDoubleTypeInContext(self.context) },
TypeId::bool => unsafe { LLVMInt1TypeInContext(self.context) },
TypeId::i64 => unsafe { LLVMInt64TypeInContext(self.context) },
TypeId::Void => unsafe { LLVMVoidTypeInContext(self.context) },
TypeId::Other(ty) => ty,
}
}
pub fn get_element_type(&self, ty: &TypeId) -> TypeId {
TypeId::Other(unsafe {
LLVMGetElementType(
self.get_type(ty)
)
})
}
pub fn build_undef(&self, ty: &TypeId) -> ValueRef {
ValueRef {
ty: ty.clone(),
ptr: unsafe {
LLVMGetUndef(
self.get_type(ty)
)
},
}
}
pub fn get_function_type<'a, A: IntoIterator<Item=&'a TypeId>>(&self, ret: TypeId, args: A) -> TypeId {
let mut args: Vec<_> = {
args.into_iter()
.map(|ty| self.get_type(ty))
.collect()
};
TypeId::Other(unsafe {
LLVMFunctionType(
self.get_type(&ret),
args.as_mut_ptr(),
args.len() as u32,
0
)
})
}
pub fn add_function(&self, ty: TypeId, name: &str) -> ValueRef {
let llvm_ty = self.get_type(&ty);
let c_name = CString::new(name).unwrap();
let ptr = unsafe {
LLVMAddFunction(self.module, c_name.as_ptr(), llvm_ty)
};
ValueRef { ty, ptr }
}
pub fn add_function_attribute(&self, func: &ValueRef, attr: u32) {
unsafe {
let attr = LLVMCreateEnumAttribute(self.context, attr, 0);
LLVMAddAttributeAtIndex(func.ptr, LLVMAttributeFunctionIndex, attr);
}
}
pub fn get_external(&mut self, name: Atom) -> Function {
self.externals.get_function(self, name)
}
pub fn get_runtime_context(&self) -> ValueRef {
ValueRef {
ty: TypeId::Context,
ptr: unsafe {
LLVMGetParam(self.func, 0)
},
}
}
pub fn build_call(&mut self, func: Function, args: Vec<ValueRef>) -> ValueRef {
let mut args: Vec<_> = {
args.into_iter()
.map(|val| val.ptr)
.collect()
};
let ptr = unsafe {
LLVMBuildCall(
self.builder,
func.ptr,
args.as_mut_ptr(),
args.len() as u32,
EMPTY_STRING.as_ptr()
)
};
ValueRef { ty: func.ret, ptr }
}
pub fn add_entity(&mut self, name: Atom, ent: Entity) {
self.entities.insert(name, ent);
}
pub fn add_auto_entity(&mut self) {
self.entities
.entry(hct_atom!(""))
.or_insert(Entity {
classname: hct_atom!("logic_auto"),
.. Default::default()
});
}
pub fn get_entities(&self) -> Vec<Atom> {
self.entities.keys()
.cloned()
.collect()
}
pub fn build_const_f64(&self, val: f64) -> ValueRef {
ValueRef {
ty: TypeId::f64,
ptr: unsafe {
LLVMConstReal(self.get_type(&TypeId::f64), val)
},
}
}
pub fn build_const_i32(&self, val: i32) -> ValueRef {
let ty = unsafe { LLVMInt32TypeInContext(self.context) };
ValueRef {
ty: TypeId::Other(ty),
ptr: unsafe {
LLVMConstInt(ty, val as u64, 1)
},
}
}
pub fn build_const_i64(&self, val: i64) -> ValueRef {
ValueRef {
ty: TypeId::i64,
ptr: unsafe {
LLVMConstInt(self.get_type(&TypeId::i64), val as u64, 1)
},
}
}
pub fn build_const_entity<A: Borrow<Atom>>(&mut self, val: A) -> ValueRef {
self.global_ptr(TypeId::Entity, val)
}
pub fn build_const_atom<A: Borrow<Atom>>(&mut self, val: A) -> ValueRef {
self.global_ptr(TypeId::Atom, val)
}
pub fn build_const_string<S: Borrow<String>>(&mut self, val: S) -> ValueRef {
self.global_ptr(TypeId::String, val)
}
pub fn is_constant(&self, val: &ValueRef) -> bool {
unsafe {
LLVMIsConstant(val.ptr) == 1
}
}
pub fn get_const_f64(&self, val: &ValueRef) -> Option<f64> {
if val.ty == TypeId::f64 && self.is_constant(val) {
let mut precision_lost = 0;
let res = unsafe {
LLVMConstRealGetDouble(val.ptr, &mut precision_lost)
};
if precision_lost == 0 {
Some(res)
} else {
None
}
} else {
None
}
}
pub fn append_basic_block(&mut self) -> Block {
unsafe {
LLVMAppendBasicBlockInContext(self.context, self.func, EMPTY_STRING.as_ptr())
}
}
pub fn get_insert_block(&self) -> Block {
unsafe {
LLVMGetInsertBlock(self.builder)
}
}
pub fn position_at_end(&mut self, block: Block) {
unsafe {
LLVMPositionBuilderAtEnd(self.builder, block);
}
}
pub fn build_br(&mut self, block: Block) {
unsafe {
LLVMBuildBr(self.builder, block);
}
}
pub fn build_cond_br(&mut self, cond: &ValueRef, cons: Block, alt: Block) {
assert_eq!(cond.ty, TypeId::bool);
unsafe {
LLVMBuildCondBr(self.builder, cond.ptr, cons, alt);
}
}
pub fn build_phi(&mut self, ty: TypeId) -> ValueRef {
let llvm_ty = self.get_type(&ty);
let ptr = unsafe {
LLVMBuildPhi(self.builder, llvm_ty, EMPTY_STRING.as_ptr())
};
ValueRef { ty, ptr }
}
pub fn add_incoming(&self, phi: &ValueRef, mut val: ValueRef, mut block: Block) {
unsafe {
LLVMAddIncoming(
phi.ptr,
&mut val.ptr,
&mut block,
1,
);
}
}
pub fn build_alloca(&mut self, val: &TypeId) -> ValueRef {
let current_block = unsafe {
LLVMGetInsertBlock(self.builder)
};
unsafe {
let alloca_block = LLVMGetEntryBasicBlock(self.func);
let term = LLVMGetBasicBlockTerminator(alloca_block);
LLVMPositionBuilderBefore(self.builder, term);
}
let ty = self.get_type(val);
let ptr = unsafe {
LLVMBuildAlloca(self.builder, ty, EMPTY_STRING.as_ptr())
};
unsafe {
LLVMPositionBuilderAtEnd(self.builder, current_block);
}
ValueRef { ty: val.clone(), ptr }
}
pub fn build_load(&mut self, val: &ValueRef) -> ValueRef {
let ptr = unsafe {
LLVMBuildLoad(self.builder, val.ptr, EMPTY_STRING.as_ptr())
};
ValueRef { ty: val.ty.clone(), ptr }
}
pub fn build_store(&mut self, val: &ValueRef, ptr: &ValueRef) {
unsafe {
LLVMBuildStore(self.builder, val.ptr, ptr.ptr);
}
}
pub fn
|
<'a, I: IntoIterator<Item=&'a ValueRef>>(&mut self, obj: &ValueRef, indices: I) -> ValueRef {
let mut indices: Vec<_> = {
indices.into_iter()
.map(|i| i.ptr)
.collect()
};
let ptr = unsafe {
LLVMBuildInBoundsGEP(
self.builder,
obj.ptr,
indices.as_mut_ptr(),
indices.len() as u32,
EMPTY_STRING.as_ptr()
)
};
ValueRef { ty: obj.ty.clone(), ptr }
}
pub fn build_insert_value(&mut self, container: &ValueRef, elem: &ValueRef, index: u32) -> ValueRef {
let ptr = unsafe {
LLVMBuildInsertValue(
self.builder,
container.ptr,
elem.ptr,
index,
EMPTY_STRING.as_ptr()
)
};
ValueRef { ty: container.ty.clone(), ptr }
}
builder_forward!{ build_fadd(rhs, lhs) -> f64 = LLVMBuildFAdd }
builder_forward!{ build_fsub(rhs, lhs) -> f64 = LLVMBuildFSub }
builder_forward!{ build_fmul(rhs, lhs) -> f64 = LLVMBuildFMul }
builder_forward!{ build_fdiv(rhs, lhs) -> f64 = LLVMBuildFDiv }
builder_forward!{ build_frem(rhs, lhs) -> f64 = LLVMBuildFRem }
builder_forward!{ build_nswadd(rhs, lhs) -> i64 = LLVMBuildNSWAdd }
builder_forward!{ build_shl(rhs, lhs) -> i64 = LLVMBuildShl }
builder_forward!{ build_lshr(rhs, lhs) -> i64 = LLVMBuildLShr }
builder_cmp!{ build_float_lt<f64, LLVMRealOLT>(rhs, lhs) }
builder_cmp!{ build_float_le<f64, LLVMRealOLE>(rhs, lhs) }
builder_cmp!{ build_float_gt<f64, LLVMRealOGT>(rhs, lhs) }
builder_cmp!{ build_float_ge<f64, LLVMRealOGE>(rhs, lhs) }
builder_cmp!{ build_float_eq<f64, LLVMRealOEQ>(rhs, lhs) }
builder_cmp!{ build_float_ne<f64, LLVMRealONE>(rhs, lhs) }
builder_forward!{ build_and(rhs, lhs) -> bool = LLVMBuildAnd }
builder_forward!{ build_or(rhs, lhs) -> bool = LLVMBuildOr }
builder_forward!{ build_xor(rhs, lhs) -> bool = LLVMBuildXor }
builder_forward!{ build_not(val) -> bool = LLVMBuildNot }
builder_cmp!{ build_int_lt<i64, LLVMIntULT>(rhs, lhs) }
builder_cmp!{ build_int_eq<i64, LLVMIntEQ>(rhs, lhs) }
builder_cmp!{ build_int_ne<i64, LLVMIntNE>(rhs, lhs) }
}
|
build_in_bounds_gep
|
tendo.go
|
package tendo
import (
"fmt"
"log"
"os"
"path/filepath"
"strings"
"github.com/andrewlader/go-tendo/tendo/internal/golang"
"github.com/andrewlader/go-tendo/tendo/internal/java"
)
// Tendo is the struct which manages all of the packages in the specified Go project
type Tendo struct {
languageType LanguageType
version string
sourcePath string
currentPath string
currentPackage string
logger *Logger
listener *listener
walker ITendo
}
const asciiArtTendoTotals = `
╔╦╗┌─┐┌┐┌┌┬┐┌─┐ ╔╦╗┌─┐┌┬┐┌─┐┬ ┌─┐
║ ├┤ │││ │││ │ ║ │ │ │ ├─┤│ └─┐
╩ └─┘┘└┘─┴┘└─┘ ╩ └─┘ ┴ ┴ ┴┴─┘└─┘
Version `
const asciiArtTendo = `
╔╦╗┌─┐┌┐┌┌┬┐┌─┐
║ ├┤ │││ │││ │
╩ └─┘┘└┘─┴┘└─┘
`
// NewTendo creates a new instance of Tendo and returns a reference to it
func NewTendo(logLevel LogLevel) *Tendo {
theLogger := newLogger(logLevel)
if theLogger == nil {
log.Fatal("Failed to created the logger, so quitting...")
}
return &Tendo{
version: "0.0.2",
logger: theLogger,
}
}
// Inspect
|
hrough all of the Go files specified in the path and counts the packages, structs and methods
func (tendo *Tendo) Inspect(path string, languageType LanguageType) {
tendo.sourcePath = path
fullpath, err := filepath.Abs(path)
if err != nil {
fullpath = path
}
if tendo.listener != nil {
tendo.listener.stop()
}
root := newRoot()
tendo.listener = newListener(root, tendo.logger)
switch languageType {
case LanguageType(Golang):
tendo.walker = golang.NewGolang(
tendo.listener.libChan,
tendo.listener.classChan,
tendo.listener.methodChan,
tendo.listener.functionChan)
case LanguageType(Java):
tendo.walker = java.NewJava(
tendo.listener.libChan,
tendo.listener.classChan,
tendo.listener.methodChan,
tendo.listener.functionChan)
}
tendo.logger.println(LogAll, asciiArtTendo)
tendo.logger.printfln(LogAll, "Version: %s", tendo.version)
tendo.logger.println(LogAll, "")
tendo.logger.printf(LogAll, "### Analysis initiating for path --> %s", fullpath)
go tendo.listener.start()
log.Printf("Gonna go do: %v", fullpath)
tendo.walker.Walk(fullpath)
folders, err := getListOfFolders(fullpath)
if err != nil {
tendo.logger.fatalf(LogErrors, "An error occurred processing the subfolders: %v", err)
}
if err == nil {
for _, path := range folders {
tendo.walker.Walk(path)
}
}
tendo.Shutdown()
}
func (tendo *Tendo) Shutdown() {
// all done, so shutdown
tendo.listener.stop()
}
func getListOfFolders(path string) ([]string, error) {
folders := []string{}
err := filepath.Walk(path, func(path string, file os.FileInfo, err error) error {
if err != nil {
return err
}
if isValidFolder(file, path) {
folders = append(folders, path)
}
return nil
})
return folders, err
}
func isValidFolder(file os.FileInfo, path string) bool {
const ignoreHiddenFolders = "."
const allowCurrentFolder = "./"
const ignoreVendors = "vendor"
var ignoreHiddenSubFolders = filepath.ToSlash("/.")
isValid := false
if file.IsDir() && !strings.Contains(path, ignoreVendors) && !strings.Contains(path, ignoreHiddenSubFolders) &&
(path == allowCurrentFolder || !strings.HasPrefix(path, ignoreHiddenFolders)) {
isValid = true
}
return isValid
}
// DisplayTotals calls GetTotals() and then displays the results to the console
func (tendo *Tendo) DisplayTotals() {
tendo.logger.println(logAlways, tendo.ToString())
}
// GetTotals returns the total number of packages, structs and methods
func (tendo *Tendo) GetTotals() (int, int, int, int) {
structCount := 0
methodCount := 0
functionCount := 0
for _, lib := range tendo.listener.root.libraries {
structCount += len(lib.classes)
functionCount += len(lib.functions)
for _, class := range lib.classes {
methodCount += len(class.methods)
}
}
return len(tendo.listener.root.libraries), structCount, methodCount, functionCount
}
func (tendo *Tendo) ToString() string {
const indent = " "
outputPrefix := fmt.Sprintf("%s%s\n\nSource path: %s\n", asciiArtTendoTotals, tendo.version, tendo.sourcePath)
var tree []string
// for each of the packages
for _, pkg := range tendo.listener.root.libraries {
tree = append(tree, fmt.Sprintf("%slibrary %s", indent, pkg.name))
// display all the structs in the package
for _, class := range pkg.classes {
tree = append(tree, fmt.Sprintf("%s%sclass/struct %s{}", indent, indent, class.name))
// and display all of the methods for the structs
for _, method := range class.methods {
tree = append(tree, fmt.Sprintf("%s%s%smethod %s()", indent, indent, indent, method))
}
}
// and display the functions in the package
for _, function := range pkg.functions {
tree = append(tree, fmt.Sprintf("%s%sfunction %s()", indent, indent, function))
}
}
packages, structCount, methodCount, functions := tendo.GetTotals()
tree = append(tree, fmt.Sprintf("\nTotals:\n=======\nLibrary Count: %d\nStruct Count: %d\nMethod Count: %d\nFunction Count: %d\n",
packages, structCount, methodCount, functions))
output := fmt.Sprintf("%s\n%s", outputPrefix, strings.Join(tree[:], "\n"))
return output
}
|
walks t
|
875-domain.py
|
#!/bin/python3
# -*- coding:utf-8 -*-
# CTX Engine-874 : IP
# 1、查询ip样本 2、查看查询结�?# 2、返回正确的ioc信息
from maldium import *
import ctypes
def print_result(result, extra_res):
if result is None:
print("query failed")
return
if result.eMatchType == engine.NO_MATCH:
print("result NO_MATCH")
return
elif result.eMatchType == engine.LOCAL_PTN_MATCHED:
match_type = "LOCAL_PTN_MATCHED"
elif result.eMatchType == engine.REMOTE_CACHE_MATCHED:
match_type = "REMOTE_CACHE_MATCHED"
elif result.eMatchType == engine.REMOTE_SERVER_MATCHED:
match_type = "REMOTE_SERVER_MATCHED"
else:
match_type = "UNKNOWN_MATCH_TYPE:" + str(result.eMatchType)
basic_info = result.basicInfo
print("result %s %u/%u/%u %u/%u/%u/%u" %
(match_type, basic_info.ui8Severity, basic_info.ui8Confidence, basic_info.ui8Activity,
basic_info.aui8Categories[0], basic_info.aui8Categories[1], basic_info.aui8Categories[2],
basic_info.aui8Categories[3]))
for res in extra_res:
print(res)
def test(engine):
result = engine.lookup_domain(ioc)
extra_res = engine.get_all_detail(result)
print_result(result, extra_res)
return result
def get_decimal_num(bin_num):
decimal_num = 0
for index, num in enumerate(bin_num[::-1]):
decimal_num += int(num) * (2 ** int(index))
return decimal_num
def get_flag(category_num):
tmp_num = format(ctypes.c_uint32(categor
|
d_opts = mald_options()
mald_opts.set_opt(mald_opts.MALD_OPT_PRODUCTID, "TEST_PRODUCT")
mald_opts.set_opt(mald_opts.MALD_OPT_TOKEN, "TEST_TOKEN")
mald_opts.set_opt(mald_opts.MALD_OPT_FPTN_DIR, "./ut_ptn")
mald_opts.set_opt(mald_opts.MALD_OPT_DPTN_DIR, "./ut_ptn")
# mald_opts.set_opt(mald_opts.MALD_OPT_RATING_TYPE, mald_opts.MALD_RATING_TYPE_LOCAL_DB)
# mald_opts.set_opt(mald_opts.MALD_OPT_RATING_TYPE, mald_opts.MALD_RATING_TYPE_SERVER)
mald_opts.set_opt(mald_opts.MALD_OPT_RATING_TYPE, mald_opts.MALD_RATING_TYPE_ALL)
mald_opts.set_opt(mald_opts.MALD_OPT_WHITELIST_COMP_PATH, "./ut_ptn/whitelist")
engine = mald_engine(mald_opts)
globals = {
'null': 0
}
with open("/root/auto_test/pattern_source/ptn-mini.json") as fp:
while True:
line = fp.readline()
if line:
_line = eval(line.split("\n")[0], globals)
ioc_type = _line.get("type")
if ioc_type == "domain":
_line = _line
ioc = _line.get("item")
break
else:
break
print(ioc)
result = test(engine)
num = _line.get("category")
decimal_num = get_flag(num)
if _line['severity'] == result.basicInfo.ui8Severity and _line['confidence'] == result.basicInfo.ui8Confidence and _line['activity'] == result.basicInfo.ui8Activity and decimal_num[0] == result.basicInfo.aui8Categories[0] and decimal_num[1] == result.basicInfo.aui8Categories[1] and decimal_num[2] == result.basicInfo.aui8Categories[2] and decimal_num[3] == result.basicInfo.aui8Categories[3]:
print('Success')
else:
print("Fail")
|
y_num).value, "#034b")
first_bin_num = tmp_num[2:10]
first_decimal_num = get_decimal_num(first_bin_num)
second_bin_num = tmp_num[10:18]
second_decimal_num = get_decimal_num(second_bin_num)
third_bin_num = tmp_num[18:26]
third_decimal_num = get_decimal_num(third_bin_num)
fourth_bin_num = tmp_num[26:34]
fourth_decimal_num = get_decimal_num(fourth_bin_num)
decimal_num = [first_decimal_num, second_decimal_num, third_decimal_num, fourth_decimal_num]
# print(decimal_num)
return decimal_num
if __name__ == "__main__":
mal
|
utils.py
|
import datetime
import re
from rest_framework_jwt.settings import api_settings
from django.contrib.auth.backends import ModelBackend
from .models import User
# def get_user_by_account(account):
# """
# 根据帐号获取user对象
# :param account: 账号,可以是用户名,也可以是手机号
# :return: User对象 或者 None
# """
# try:
# if re.match('^1[3-9]\d{9}$', account):
# # 帐号为 学号
# user = User.objects.get(StudentID=account)
# else:
# # 帐号为用户名
# user = User.objects.get(username=account)
# except User.DoesNotExist:
# return None
# else:
# return user
class UsernameMobileAuthBackend(ModelBackend):
"""
自定义学号认证
"""
def authenticate(self, request, username=None, password=None, **kwargs):
user = User.objects.get(StudentID=username)
if user is not None and user.check_password(password):
return user
def jwt_response_payload_handler(token, user=None, request=None):
"""
自定义jwt认证成功返回数据
"""
return {
'token': token,
'user_id': user.StudentID,
'username': user.username
}
# 生成 token
def make_token(user):
"""
生成 token
:param user: user对象
:return: 增加了token的user对象
"""
# 补充生成记录登录状态的token
jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
payload = jwt_payload_handler(user)
token = jwt_encode_handler(payload)
user.token = token
print('user',user)
return user
def howLongDays(date):
"""
计算时间间隔
:param date: 时间格式化日期 "20160903" 2019年9月3日
:return:
"""
d1 = datetime.datetime.strptime(datetime.date.today().str
|
m-%d'),'%Y-%m-%d')
d2 = datetime.datetime.strptime(date, '%Y%m%d')
delta = d1 - d2
return delta.days
|
ftime('%Y-%
|
config_regs_apds.py
|
from adafruit_bus_device.i2c_device import I2CDevice
from adafruit_apds9960.apds9960 import APDS9960
try:
# Only used for typing
from typing import Dict
except ImportError:
pass
class ConfigRegsAPDS:
def __init__(self, *, apds: APDS9960=None, i2c_bus=None):
if not apds:
if not i2c_bus:
import board
i2c = board.I2C()
self.i2c_device = I2CDevice(i2c, 0x39)
else:
self.i2c_device = apds.i2c_device
config_regs = {
"_APDS9960_ENABLE": 0x80,
"_APDS9960_ATIME": 0x81,
"_APDS9960_WTIME": 0x83,
"_APDS9960_AILTIL": 0x84,
"_APDS9960_AILTH": 0x85,
"_APDS9960_AIHTL": 0x86,
"_APDS9960_AIHTH": 0x87,
"_APDS9960_PILT": 0x89,
"_APDS9960_PIHT": 0x8B,
"_APDS9960_PERS": 0x8C,
"_APDS9960_CONFIG1": 0x8D,
"_APDS9960_PPULSE": 0x8E,
"_APDS9960_CONTROL": 0x8F,
"_APDS9960_CONFIG2": 0x90,
"_APDS9960_STATUS": 0x93,
"_APDS9960_POFFSET_UR": 0x9D,
"_APDS9960_POFFSET_DL": 0x9E,
"_APDS9960_CONFIG3": 0x9F,
"_APDS9960_GPENTH": 0xA0,
"_APDS9960_GEXTH": 0xA1,
"_APDS9960_GCONF1": 0xA2,
"_APDS9960_GCONF2": 0xA3,
"_APDS9960_GOFFSET_U": 0xA4,
"_APDS9960_GOFFSET_D": 0xA5,
"_APDS9960_GOFFSET_L": 0xA7,
"_APDS9960_GOFFSET_R": 0xA9,
|
"_APDS9960_GPULSE": 0xA6,
"_APDS9960_GCONF3": 0xAA,
"_APDS9960_GCONF4": 0xAB,
"_APDS9960_GFLVL": 0xAE,
"_APDS9960_GSTATUS": 0xAF,
}
def sorted_reg_dict(self) -> Dict[str, int]:
return sorted(self.config_regs, key=self.config_regs.get)
def print_reg_states(self) -> None:
buf2 = bytearray(2)
for key in self.sorted_reg_dict():
reg_val = self._read8(buf2, self.config_regs[key])
print(" {0:22} 0x{1:02X} | 0x{2:02X} | b{2:08b} | {2:3d}".format(key, self.config_regs[key], reg_val))
def _read8(self, buf: bytearray, addr: int) -> int:
buf[0] = addr
with self.i2c_device as i2c:
i2c.write_then_readinto(buf, buf, out_end=1, in_end=1)
return buf[0]
| |
aws.py
|
from ..utils.formats import flatten_dict
DENYLIST_ENDPOINT = ['kms', 'sts']
DENYLIST_ENDPOINT_TAGS = {
's3': ['params.Body'],
}
def truncate_arg_value(value, max_len=1024):
|
def add_span_arg_tags(span, endpoint_name, args, args_names, args_traced):
if endpoint_name not in DENYLIST_ENDPOINT:
denylisted = DENYLIST_ENDPOINT_TAGS.get(endpoint_name, [])
tags = dict(
(name, value)
for (name, value) in zip(args_names, args)
if name in args_traced
)
tags = flatten_dict(tags)
tags = {
k: truncate_arg_value(v)
for k, v in tags.items()
if k not in denylisted
}
span.set_tags(tags)
REGION = 'aws.region'
AGENT = 'aws.agent'
OPERATION = 'aws.operation'
|
"""Truncate values which are bytes and greater than `max_len`.
Useful for parameters like 'Body' in `put_object` operations.
"""
if isinstance(value, bytes) and len(value) > max_len:
return b'...'
return value
|
helper_test.go
|
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
package app
import (
"io/ioutil"
"os"
"path/filepath"
"strings"
"time"
"testing"
"github.com/mattermost/mattermost-server/v5/config"
"github.com/mattermost/mattermost-server/v5/mlog"
"github.com/mattermost/mattermost-server/v5/model"
"github.com/mattermost/mattermost-server/v5/utils"
"github.com/stretchr/testify/require"
)
type TestHelper struct {
App *App
Server *Server
BasicTeam *model.Team
BasicUser *model.User
BasicUser2 *model.User
BasicChannel *model.Channel
BasicPost *model.Post
SystemAdminUser *model.User
tempWorkspace string
}
func setupTestHelper(enterprise bool, tb testing.TB) *TestHelper {
store := mainHelper.GetStore()
store.DropAllTables()
memoryStore, err := config.NewMemoryStoreWithOptions(&config.MemoryStoreOptions{IgnoreEnvironmentOverrides: true})
if err != nil {
panic("failed to initialize memory store: " + err.Error())
}
var options []Option
options = append(options, ConfigStore(memoryStore))
options = append(options, StoreOverride(mainHelper.Store))
options = append(options, SetLogger(mlog.NewTestingLogger(tb)))
s, err := NewServer(options...)
if err != nil {
panic(err)
}
th := &TestHelper{
App: s.FakeApp(),
Server: s,
}
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.MaxUsersPerTeam = 50 })
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.RateLimitSettings.Enable = false })
prevListenAddress := *th.App.Config().ServiceSettings.ListenAddress
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.ListenAddress = ":0" })
serverErr := th.Server.Start()
if serverErr != nil {
panic(serverErr)
}
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.ListenAddress = prevListenAddress })
th.App.Srv.Store.MarkSystemRanUnitTests()
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.EnableOpenServer = true })
// Disable strict password requirements for test
th.App.UpdateConfig(func(cfg *model.Config) {
*cfg.PasswordSettings.MinimumLength = 5
*cfg.PasswordSettings.Lowercase = false
*cfg.PasswordSettings.Uppercase = false
*cfg.PasswordSettings.Symbol = false
*cfg.PasswordSettings.Number = false
})
if enterprise {
th.App.SetLicense(model.NewTestLicense())
} else {
th.App.SetLicense(nil)
}
if th.tempWorkspace == "" {
dir, err := ioutil.TempDir("", "apptest")
if err != nil {
panic(err)
}
th.tempWorkspace = dir
}
pluginDir := filepath.Join(th.tempWorkspace, "plugins")
webappDir := filepath.Join(th.tempWorkspace, "webapp")
th.App.InitPlugins(pluginDir, webappDir)
return th
}
func SetupEnterprise(tb testing.TB) *TestHelper {
return setupTestHelper(true, tb)
}
func Setup(tb testing.TB) *TestHelper {
return setupTestHelper(false, tb)
}
func (me *TestHelper) InitBasic() *TestHelper {
me.SystemAdminUser = me.CreateUser()
me.App.UpdateUserRoles(me.SystemAdminUser.Id, model.SYSTEM_USER_ROLE_ID+" "+model.SYSTEM_ADMIN_ROLE_ID, false)
me.SystemAdminUser, _ = me.App.GetUser(me.SystemAdminUser.Id)
me.BasicTeam = me.CreateTeam()
me.BasicUser = me.CreateUser()
me.LinkUserToTeam(me.BasicUser, me.BasicTeam)
me.BasicUser2 = me.CreateUser()
me.LinkUserToTeam(me.BasicUser2, me.BasicTeam)
me.BasicChannel = me.CreateChannel(me.BasicTeam)
me.BasicPost = me.CreatePost(me.BasicChannel)
return me
}
func (me *TestHelper) MakeEmail() string {
return "success_" + model.NewId() + "@simulator.amazonses.com"
}
func (me *TestHelper) CreateTeam() *model.Team {
id := model.NewId()
team := &model.Team{
DisplayName: "dn_" + id,
Name: "name" + id,
Email: "success+" + id + "@simulator.amazonses.com",
Type: model.TEAM_OPEN,
}
utils.DisableDebugLogForTest()
var err *model.AppError
if team, err = me.App.CreateTeam(team); err != nil {
mlog.Error(err.Error())
time.Sleep(time.Second)
panic(err)
}
utils.EnableDebugLogForTest()
return team
}
func (me *TestHelper) CreateUser() *model.User {
return me.CreateUserOrGuest(false)
}
func (me *TestHelper) CreateGuest() *model.User {
return me.CreateUserOrGuest(true)
}
func (me *TestHelper) CreateUserOrGuest(guest bool) *model.User {
id := model.NewId()
user := &model.User{
Email: "success+" + id + "@simulator.amazonses.com",
Username: "un_" + id,
Nickname: "nn_" + id,
Password: "Password1",
EmailVerified: true,
}
utils.DisableDebugLogForTest()
var err *model.AppError
if guest {
if user, err = me.App.CreateGuest(user); err != nil {
mlog.Error(err.Error())
time.Sleep(time.Second)
panic(err)
}
} else {
if user, err = me.App.CreateUser(user); err != nil
|
}
utils.EnableDebugLogForTest()
return user
}
func (me *TestHelper) CreateChannel(team *model.Team) *model.Channel {
return me.createChannel(team, model.CHANNEL_OPEN)
}
func (me *TestHelper) CreatePrivateChannel(team *model.Team) *model.Channel {
return me.createChannel(team, model.CHANNEL_PRIVATE)
}
func (me *TestHelper) createChannel(team *model.Team, channelType string) *model.Channel {
id := model.NewId()
channel := &model.Channel{
DisplayName: "dn_" + id,
Name: "name_" + id,
Type: channelType,
TeamId: team.Id,
CreatorId: me.BasicUser.Id,
}
utils.DisableDebugLogForTest()
var err *model.AppError
if channel, err = me.App.CreateChannel(channel, true); err != nil {
mlog.Error(err.Error())
time.Sleep(time.Second)
panic(err)
}
utils.EnableDebugLogForTest()
return channel
}
func (me *TestHelper) createChannelWithAnotherUser(team *model.Team, channelType, userId string) *model.Channel {
id := model.NewId()
channel := &model.Channel{
DisplayName: "dn_" + id,
Name: "name_" + id,
Type: channelType,
TeamId: team.Id,
CreatorId: userId,
}
utils.DisableDebugLogForTest()
var err *model.AppError
if channel, err = me.App.CreateChannel(channel, true); err != nil {
mlog.Error(err.Error())
time.Sleep(time.Second)
panic(err)
}
utils.EnableDebugLogForTest()
return channel
}
func (me *TestHelper) CreateDmChannel(user *model.User) *model.Channel {
utils.DisableDebugLogForTest()
var err *model.AppError
var channel *model.Channel
if channel, err = me.App.GetOrCreateDirectChannel(me.BasicUser.Id, user.Id); err != nil {
mlog.Error(err.Error())
time.Sleep(time.Second)
panic(err)
}
utils.EnableDebugLogForTest()
return channel
}
func (me *TestHelper) CreateGroupChannel(user1 *model.User, user2 *model.User) *model.Channel {
utils.DisableDebugLogForTest()
var err *model.AppError
var channel *model.Channel
if channel, err = me.App.CreateGroupChannel([]string{me.BasicUser.Id, user1.Id, user2.Id}, me.BasicUser.Id); err != nil {
mlog.Error(err.Error())
time.Sleep(time.Second)
panic(err)
}
utils.EnableDebugLogForTest()
return channel
}
func (me *TestHelper) CreatePost(channel *model.Channel) *model.Post {
id := model.NewId()
post := &model.Post{
UserId: me.BasicUser.Id,
ChannelId: channel.Id,
Message: "message_" + id,
CreateAt: model.GetMillis() - 10000,
}
utils.DisableDebugLogForTest()
var err *model.AppError
if post, err = me.App.CreatePost(post, channel, false); err != nil {
mlog.Error(err.Error())
time.Sleep(time.Second)
panic(err)
}
utils.EnableDebugLogForTest()
return post
}
func (me *TestHelper) CreateMessagePost(channel *model.Channel, message string) *model.Post {
post := &model.Post{
UserId: me.BasicUser.Id,
ChannelId: channel.Id,
Message: message,
CreateAt: model.GetMillis() - 10000,
}
utils.DisableDebugLogForTest()
var err *model.AppError
if post, err = me.App.CreatePost(post, channel, false); err != nil {
mlog.Error(err.Error())
time.Sleep(time.Second)
panic(err)
}
utils.EnableDebugLogForTest()
return post
}
func (me *TestHelper) LinkUserToTeam(user *model.User, team *model.Team) {
utils.DisableDebugLogForTest()
err := me.App.JoinUserToTeam(team, user, "")
if err != nil {
mlog.Error(err.Error())
time.Sleep(time.Second)
panic(err)
}
utils.EnableDebugLogForTest()
}
func (me *TestHelper) AddUserToChannel(user *model.User, channel *model.Channel) *model.ChannelMember {
utils.DisableDebugLogForTest()
member, err := me.App.AddUserToChannel(user, channel)
if err != nil {
mlog.Error(err.Error())
time.Sleep(time.Second)
panic(err)
}
utils.EnableDebugLogForTest()
return member
}
func (me *TestHelper) CreateScheme() (*model.Scheme, []*model.Role) {
utils.DisableDebugLogForTest()
scheme, err := me.App.CreateScheme(&model.Scheme{
DisplayName: "Test Scheme Display Name",
Name: model.NewId(),
Description: "Test scheme description",
Scope: model.SCHEME_SCOPE_TEAM,
})
if err != nil {
panic(err)
}
roleNames := []string{
scheme.DefaultTeamAdminRole,
scheme.DefaultTeamUserRole,
scheme.DefaultTeamGuestRole,
scheme.DefaultChannelAdminRole,
scheme.DefaultChannelUserRole,
scheme.DefaultChannelGuestRole,
}
var roles []*model.Role
for _, roleName := range roleNames {
role, err := me.App.GetRoleByName(roleName)
if err != nil {
panic(err)
}
roles = append(roles, role)
}
utils.EnableDebugLogForTest()
return scheme, roles
}
func (me *TestHelper) CreateGroup() *model.Group {
id := model.NewId()
group := &model.Group{
DisplayName: "dn_" + id,
Name: "name" + id,
Source: model.GroupSourceLdap,
Description: "description_" + id,
RemoteId: model.NewId(),
}
utils.DisableDebugLogForTest()
var err *model.AppError
if group, err = me.App.CreateGroup(group); err != nil {
mlog.Error(err.Error())
time.Sleep(time.Second)
panic(err)
}
utils.EnableDebugLogForTest()
return group
}
func (me *TestHelper) CreateEmoji() *model.Emoji {
utils.DisableDebugLogForTest()
emoji, err := me.App.Srv.Store.Emoji().Save(&model.Emoji{
CreatorId: me.BasicUser.Id,
Name: model.NewRandomString(10),
})
if err != nil {
panic(err)
}
utils.EnableDebugLogForTest()
return emoji
}
func (me *TestHelper) AddReactionToPost(post *model.Post, user *model.User, emojiName string) *model.Reaction {
utils.DisableDebugLogForTest()
reaction, err := me.App.SaveReactionForPost(&model.Reaction{
UserId: user.Id,
PostId: post.Id,
EmojiName: emojiName,
})
if err != nil {
panic(err)
}
utils.EnableDebugLogForTest()
return reaction
}
func (me *TestHelper) ShutdownApp() {
done := make(chan bool)
go func() {
me.Server.Shutdown()
close(done)
}()
select {
case <-done:
case <-time.After(30 * time.Second):
// panic instead of t.Fatal to terminate all tests in this package, otherwise the
// still running App could spuriously fail subsequent tests.
panic("failed to shutdown App within 30 seconds")
}
}
func (me *TestHelper) TearDown() {
me.ShutdownApp()
if err := recover(); err != nil {
panic(err)
}
if me.tempWorkspace != "" {
os.RemoveAll(me.tempWorkspace)
}
}
func (me *TestHelper) ResetRoleMigration() {
sqlSupplier := mainHelper.GetSqlSupplier()
if _, err := sqlSupplier.GetMaster().Exec("DELETE from Roles"); err != nil {
panic(err)
}
mainHelper.GetClusterInterface().SendClearRoleCacheMessage()
if _, err := sqlSupplier.GetMaster().Exec("DELETE from Systems where Name = :Name", map[string]interface{}{"Name": ADVANCED_PERMISSIONS_MIGRATION_KEY}); err != nil {
panic(err)
}
}
func (me *TestHelper) ResetEmojisMigration() {
sqlSupplier := mainHelper.GetSqlSupplier()
if _, err := sqlSupplier.GetMaster().Exec("UPDATE Roles SET Permissions=REPLACE(Permissions, ' create_emojis', '') WHERE builtin=True"); err != nil {
panic(err)
}
if _, err := sqlSupplier.GetMaster().Exec("UPDATE Roles SET Permissions=REPLACE(Permissions, ' delete_emojis', '') WHERE builtin=True"); err != nil {
panic(err)
}
if _, err := sqlSupplier.GetMaster().Exec("UPDATE Roles SET Permissions=REPLACE(Permissions, ' delete_others_emojis', '') WHERE builtin=True"); err != nil {
panic(err)
}
mainHelper.GetClusterInterface().SendClearRoleCacheMessage()
if _, err := sqlSupplier.GetMaster().Exec("DELETE from Systems where Name = :Name", map[string]interface{}{"Name": EMOJIS_PERMISSIONS_MIGRATION_KEY}); err != nil {
panic(err)
}
}
func (me *TestHelper) CheckTeamCount(t *testing.T, expected int64) {
teamCount, err := me.App.Srv.Store.Team().AnalyticsTeamCount(false)
require.Nil(t, err, "Failed to get team count.")
require.Equalf(t, teamCount, expected, "Unexpected number of teams. Expected: %v, found: %v", expected, teamCount)
}
func (me *TestHelper) CheckChannelsCount(t *testing.T, expected int64) {
count, err := me.App.Srv.Store.Channel().AnalyticsTypeCount("", model.CHANNEL_OPEN)
require.Nilf(t, err, "Failed to get channel count.")
require.Equalf(t, count, expected, "Unexpected number of channels. Expected: %v, found: %v", expected, count)
}
func (me *TestHelper) SetupTeamScheme() *model.Scheme {
scheme := model.Scheme{
Name: model.NewId(),
DisplayName: model.NewId(),
Scope: model.SCHEME_SCOPE_TEAM,
}
if scheme, err := me.App.CreateScheme(&scheme); err == nil {
return scheme
} else {
panic(err)
}
}
func (me *TestHelper) SetupChannelScheme() *model.Scheme {
scheme := model.Scheme{
Name: model.NewId(),
DisplayName: model.NewId(),
Scope: model.SCHEME_SCOPE_CHANNEL,
}
if scheme, err := me.App.CreateScheme(&scheme); err == nil {
return scheme
} else {
panic(err)
}
}
func (me *TestHelper) SetupPluginAPI() *PluginAPI {
manifest := &model.Manifest{
Id: "pluginid",
}
return NewPluginAPI(me.App, manifest)
}
func (me *TestHelper) RemovePermissionFromRole(permission string, roleName string) {
utils.DisableDebugLogForTest()
role, err1 := me.App.GetRoleByName(roleName)
if err1 != nil {
utils.EnableDebugLogForTest()
panic(err1)
}
var newPermissions []string
for _, p := range role.Permissions {
if p != permission {
newPermissions = append(newPermissions, p)
}
}
if strings.Join(role.Permissions, " ") == strings.Join(newPermissions, " ") {
utils.EnableDebugLogForTest()
return
}
role.Permissions = newPermissions
_, err2 := me.App.UpdateRole(role)
if err2 != nil {
utils.EnableDebugLogForTest()
panic(err2)
}
utils.EnableDebugLogForTest()
}
func (me *TestHelper) AddPermissionToRole(permission string, roleName string) {
utils.DisableDebugLogForTest()
role, err1 := me.App.GetRoleByName(roleName)
if err1 != nil {
utils.EnableDebugLogForTest()
panic(err1)
}
for _, existingPermission := range role.Permissions {
if existingPermission == permission {
utils.EnableDebugLogForTest()
return
}
}
role.Permissions = append(role.Permissions, permission)
_, err2 := me.App.UpdateRole(role)
if err2 != nil {
utils.EnableDebugLogForTest()
panic(err2)
}
utils.EnableDebugLogForTest()
}
|
{
mlog.Error(err.Error())
time.Sleep(time.Second)
panic(err)
}
|
standards.ts
|
import { BinaryLike, createHash } from "crypto";
import { URL, URLSearchParams } from "url";
import { TextDecoder, TextEncoder } from "util";
import originalFetch, {
Headers,
Request,
RequestInfo,
RequestInit,
Response,
} from "@mrbbot/node-fetch";
import { Crypto } from "@peculiar/webcrypto";
import FormData from "formdata-node";
import {
ByteLengthQueuingStrategy,
CountQueuingStrategy,
ReadableByteStreamController,
ReadableStream,
ReadableStreamBYOBReader,
ReadableStreamBYOBRequest,
ReadableStreamDefaultController,
ReadableStreamDefaultReader,
TransformStream,
TransformStreamDefaultController,
WritableStream,
WritableStreamDefaultController,
WritableStreamDefaultWriter,
} from "web-streams-polyfill/ponyfill/es6";
import WebSocket from "ws";
import { Log } from "../log";
import { Context, Module } from "./module";
import { WebSocketPair, terminateWebSocket } from "./ws";
export {
URL,
URLSearchParams,
TextDecoder,
TextEncoder,
Headers,
FormData,
Request,
Response,
ByteLengthQueuingStrategy,
CountQueuingStrategy,
ReadableByteStreamController,
ReadableStream,
ReadableStreamBYOBReader,
ReadableStreamBYOBRequest,
ReadableStreamDefaultController,
ReadableStreamDefaultReader,
TransformStream,
TransformStreamDefaultController,
WritableStream,
WritableStreamDefaultController,
WritableStreamDefaultWriter,
};
export function atob(s: string): string {
return Buffer.from(s, "base64").toString("binary");
}
export function btoa(s: string): string {
return Buffer.from(s, "binary").toString("base64");
}
export const crypto = new Crypto();
// Override the digest function to add support for MD5 digests which aren't
// part of the WebCrypto standard, but are supported in Workers
const originalDigest = crypto.subtle.digest.bind(crypto.subtle);
crypto.subtle.digest = function (algorithm, data) {
const algorithmName =
typeof algorithm === "string" ? algorithm : algorithm?.name;
if (algorithmName?.toLowerCase() == "md5") {
if (data instanceof ArrayBuffer) data = Buffer.from(data);
return Promise.resolve(
createHash("md5")
.update(data as BinaryLike)
.digest().buffer
);
}
// If the algorithm isn't MD5, defer to the original function
return originalDigest(algorithm, data);
};
export class StandardsModule extends Module {
private webSockets: WebSocket[];
private readonly sandbox: Context;
constructor(log: Log) {
// TODO: (low priority) proxy Date.now() and add warning, maybe new Date() too?
super(log);
this.webSockets = [];
this.sandbox = {
console,
setTimeout,
setInterval,
clearTimeout,
clearInterval,
atob,
btoa,
crypto,
TextDecoder,
TextEncoder,
fetch: this.fetch.bind(this),
Headers,
Request,
Response,
FormData,
URL,
URLSearchParams,
ByteLengthQueuingStrategy,
CountQueuingStrategy,
ReadableByteStreamController,
ReadableStream,
ReadableStreamBYOBReader,
ReadableStreamBYOBRequest,
ReadableStreamDefaultController,
ReadableStreamDefaultReader,
TransformStream,
TransformStreamDefaultController,
WritableStream,
WritableStreamDefaultController,
WritableStreamDefaultWriter,
// The types below would be included automatically, but it's not possible
// to create instances of them without using their constructors and they
// may be returned from Miniflare's realm (e.g. ArrayBuffer responses,
// Durable Object listed keys) so it makes sense to share these so
// instanceof behaves correctly.
ArrayBuffer,
Atomics,
BigInt64Array,
BigUint64Array,
DataView,
Date,
Float32Array,
Float64Array,
Int8Array,
Int16Array,
Int32Array,
Map,
Set,
SharedArrayBuffer,
Uint8Array,
Uint8ClampedArray,
Uint16Array,
Uint32Array,
WeakMap,
WeakSet,
WebAssembly,
// The types below are included automatically. By not including Array,
// Object, Function and RegExp, instanceof will return true for these
// types on literals. JSON.parse will return instances of its realm's
// objects/arrays too, hence it is not included. See tests for examples.
//
// Array,
// Boolean,
// Function,
// Error,
// EvalError,
// Math,
// NaN,
// Number,
// BigInt,
// Object,
// Promise,
// Proxy,
// RangeError,
// ReferenceError,
// Reflect,
// RegExp,
// String,
// Symbol,
// SyntaxError,
// TypeError,
// URIError,
// Intl,
// JSON,
};
}
async fetch(input: RequestInfo, init?: RequestInit): Promise<Response> {
const request = new Request(input, init);
// Cloudflare ignores request Host
|
// Handle web socket upgrades
if (request.headers.get("upgrade") === "websocket") {
// Establish web socket connection
const headers: Record<string, string> = {};
for (const [key, value] of request.headers.entries()) {
headers[key] = value;
}
const ws = new WebSocket(request.url, {
followRedirects: request.redirect === "follow",
maxRedirects: request.follow,
headers,
});
this.webSockets.push(ws);
// Terminate web socket with pair and resolve
const [worker, client] = Object.values(new WebSocketPair());
await terminateWebSocket(ws, client);
return new Response(null, { webSocket: worker });
}
// TODO: (low priority) support cache using fetch:
// https://developers.cloudflare.com/workers/learning/how-the-cache-works#fetch
// https://developers.cloudflare.com/workers/examples/cache-using-fetch
return originalFetch(request);
}
resetWebSockets(): void {
// Ensure all fetched web sockets are closed
for (const ws of this.webSockets) {
ws.close(1012, "Service Restart");
}
this.webSockets = [];
}
buildSandbox(): Context {
return this.sandbox;
}
}
|
request.headers.delete("host");
|
app.component.ts
|
import {Component} from '@angular/core';
import {LoggerService} from './core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class
|
{
title = 'Bovsi Studios Timeclock';
isDarkTheme: boolean;
constructor(private _logger: LoggerService) {
this._logger.info('Starting App.Component');
// get theme setting
const isDarkTheme = localStorage.getItem('isDarkTheme');
this.isDarkTheme = JSON.parse(isDarkTheme);
}
switchTheme(isDarkTheme: boolean) {
this.isDarkTheme = !isDarkTheme;
this._logger.info(`Dark Theme? ${this.isDarkTheme}`);
}
}
|
AppComponent
|
version_test.go
|
package strings
import (
"fmt"
"testing"
)
func TestVersion(t *testing.T) {
version1 := "20.02.15"
version2 := "20.03.25"
fmt.Println(CompareVersion(version1, version2))
version1 = "1.0.13"
version2 = "1.0.1a"
fmt.Println(CompareVersion(version1, version2))
|
version1 = "1.0.131"
version2 = "1.0.1a"
fmt.Println(CompareVersion(version1, version2))
version1 = "1.1.131"
version2 = "1.10.1a"
fmt.Println(CompareVersion(version1, version2))
version1 = "1.0.4"
version2 = "1.1.1"
fmt.Println(CompareVersion(version1, version2))
}
| |
system.go
|
package daemon
import (
"context"
"fmt"
"os"
"os/signal"
"sync"
"syscall"
"time"
dc "github.com/docker/docker/client"
"github.com/fuserobotics/deviced/pkg/arch"
"github.com/fuserobotics/deviced/pkg/config"
"github.com/fuserobotics/deviced/pkg/containersync"
"github.com/fuserobotics/deviced/pkg/imagesync"
"github.com/fuserobotics/deviced/pkg/reflection"
)
type System struct {
ConfigPath string
Config config.DevicedConfig
ConfigLock sync.Mutex
WorkerLock sync.Mutex
ConfigWatcher *config.DevicedConfigWatcher
DockerClient *dc.Client
ContainerWorker *containersync.ContainerSyncWorker
ImageWorker *imagesync.ImageSyncWorker
Reflection *reflection.DevicedReflection
}
func (s *System) initConfig() int {
if !s.Config.CreateOrRead(s.ConfigPath) {
fmt.Printf("Failed to create/read config at %s", s.ConfigPath)
return 1
}
return 0
}
func (s *System) initWorkers() int {
fmt.Printf("Initializing workers...\n")
var err error
s.DockerClient, err = s.Config.DockerConfig.BuildClient()
if err != nil {
fmt.Printf("Unable to create docker client, %v\n", err)
return 1
}
_, err = s.DockerClient.Ping(context.Background())
if err != nil {
fmt.Printf("Unable to ping Docker, %v\n", err)
return 1
}
refl, err := reflection.BuildReflection(s.DockerClient)
if err != nil || refl == nil {
fmt.Printf("Unable to locate our container, continuing without reflection.\n")
fmt.Printf("Error locating container was: %v\n", err)
} else {
fmt.Printf("Located our container, continuing with reflection.\n")
s.Reflection = refl
}
s.ContainerWorker = &containersync.ContainerSyncWorker{
ConfigLock: &s.ConfigLock,
WorkerLock: &s.WorkerLock,
DockerClient: s.DockerClient,
Config: &s.Config,
Reflection: s.Reflection,
}
if err = s.ContainerWorker.Init(); err != nil {
fmt.Printf("Error initializing ContainerWorker, %v\n", err)
return 1
}
s.ImageWorker = &imagesync.ImageSyncWorker{
ConfigLock: &s.ConfigLock,
WorkerLock: &s.WorkerLock,
DockerClient: s.DockerClient,
Config: &s.Config,
WakeContainerChannel: &s.ContainerWorker.WakeChannel,
}
s.ImageWorker.Init()
return 0
}
func (s *System) initWatchers() int {
s.ConfigWatcher = new(config.DevicedConfigWatcher)
s.ConfigWatcher.ConfigPath = &s.ConfigPath
if res := s.ConfigWatcher.Init(); res != 0
|
return 0
}
// Wake the workers upon a config change
func (s *System) wakeWorkers() {
fmt.Printf("Config changed, waking workers...\n")
s.ImageWorker.WakeChannel <- true
s.ContainerWorker.WakeChannel <- true
}
func (s *System) triggerConfRecheck() {
fmt.Printf("Config changed, rechecking config...\n")
s.ImageWorker.RecheckConfig()
}
func (s *System) closeWorkers() {
s.ContainerWorker.Quit()
s.ImageWorker.Quit()
}
func (s *System) closeWatchers() {
s.ConfigWatcher.Close()
}
func (s *System) Main() int {
if res := s.initConfig(); res != 0 {
return res
}
if res := s.initWorkers(); res != 0 {
return res
}
if res := s.initWatchers(); res != 0 {
return res
}
archTag := arch.GetArchTagSuffix()
if archTag != "" {
fmt.Printf("Using arch tag suffix: %s\n", archTag)
} else {
fmt.Printf("Using no arch tag suffix, arch is %s\n", arch.GetArch())
}
fmt.Printf("Starting image worker...\n")
go s.ImageWorker.Run()
fmt.Printf("Starting container worker...\n")
go s.ContainerWorker.Run()
c := make(chan os.Signal, 2)
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
keepRunning := true
for keepRunning {
select {
case <-c:
keepRunning = false
break
case event := <-s.ConfigWatcher.ConfigWatcher.Events:
fmt.Printf("event:%s\n", event)
s.closeWatchers()
time.Sleep(1 * time.Second)
s.ConfigLock.Lock()
err := s.Config.ReadFrom(s.ConfigPath)
s.ConfigLock.Unlock()
if err == nil {
s.triggerConfRecheck()
s.wakeWorkers()
}
s.initWatchers()
continue
}
}
fmt.Println("Exiting...")
s.closeWorkers()
s.closeWatchers()
return 0
}
|
{
return res
}
|
registry_test.py
|
# -*- coding: utf-8; -*-
from __future__ import unicode_literals, absolute_import
import json
import requests
import six
from tests import unittest, mock
from freight_forwarder.registry import Registry, V1, V2
from freight_forwarder.registry.registry_base import RegistryBase, RegistryException
from ..factories.registry_factory import RegistryV1Factory, RegistryV2Factory
class RegistryTest(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
@mock.patch.object(V1, '_validate_response', autospec=True, return_value=True)
@mock.patch('freight_forwarder.registry.registry_base.requests', autospec=True)
def test_registry_v1_init(self, mock_requests, mock_v1_validate):
test_registry = Registry()
self.assertIsInstance(test_registry, RegistryBase)
self.assertEquals(test_registry.ping(), True)
@mock.patch.object(V1, '_validate_response', name="v1_validate")
@mock.patch.object(V2, '_validate_response', name="v2_validate")
@mock.patch('freight_forwarder.registry.registry_base.requests', autospec=True)
def test_registry_v2_init(self, mock_requests, mock_v2, mock_v1):
mock_v1.side_effect = RegistryException("test")
mock_v2.return_value = True
test_v1_registry = RegistryV1Factory()
test_v2_registry = RegistryV2Factory()
# This is stated to ensure the test environment is setup correctly
# validated v1.ping() returns an exception
with self.assertRaises(RegistryException):
test_v1_registry.ping()
# validated v2.ping() returns an exception
self.assertEquals(test_v2_registry.ping(), True)
# Validate the logic of the registry class to return a V2 object
test_registry = Registry(address="https://v2.dockertest.io")
self.assertIsInstance(test_registry, RegistryBase)
class RegistryV1Test(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
@mock.patch.object(V1, '_validate_response', return_value=True)
@mock.patch.object(V1, '_request_builder')
@mock.patch('freight_forwarder.registry.registry_base.requests', autospec=True)
def test_v1_search(self, mock_requests, mock_request_builder, mock_validate_response):
# Defined Search Request a
search_response_content = {
"num_results": 3,
"query": "test",
"results": [
{"description": "api test app", "name": "testproject/test-app"},
{"description": "database test app", "name": "testproject/test-db"},
{"description": "cache test app", "name": "testproject/test-cache"}
]
}
# Define Response Value for content once request has been validated
mock_request_builder.return_value = create_response_object(
url="https://search.registry.docker.com",
status_code=200,
content=json.dumps(search_response_content).encode('utf-8')
)
# Define Default value for utils _validate_reponse
mock_validate_response.return_value = True
# Build V1 Factory Registry
test_registry = RegistryV1Factory(address='https://search.registry.docker.com')
results = test_registry.search("test")
self.assertIsInstance(results, dict)
@mock.patch.object(V1, '_validate_response', return_value=True)
@mock.patch.object(V1, '_request_builder')
@mock.patch('freight_forwarder.registry.registry_base.requests', autospec=True)
def test_v1_tags(self, mock_requests, mock_request_builder, mock_validate_response):
tag_response_content = {
"0.1": "3fad19bfa2",
"latest": "xxxxxxxxxx",
"localtest": "xxxxxxxxxxxxxxae13",
"redis123123": "xxxxxxxxxxxxxxae132",
"jira1268": "xxxxxxxxxxxxxxae1324987"
}
formatted_output = [
'appexample/test-app:0.1',
'appexample/test-app:latest',
'appexample/test-app:us-east-01-dev',
'appexample/test-app:localtest',
'appexample/test-app:redis123123',
'appexample/test-app:jira1268'
]
mock_request_builder.return_value = create_response_object(
url="https://tag.registry.docker.com",
status_code=200,
content=json.dumps(tag_response_content).encode('utf-8')
)
mock_validate_response.return_value = True
test_registry = RegistryV1Factory(address='https://tag.registry.docker.com')
for tag in test_registry.tags("appexample/test-app"):
tag_output = "".join(tag)
self.assertIsInstance(tag_output, six.string_types)
self.assertIn(tag_output, formatted_output)
def test_delete_tag(self):
self.skipTest("Implemented but not used")
def test_delete(self):
self.skipTest("Implemented but not used")
def test_get_image_by_id(self):
self.skipTest("Implemented but not used")
def test_get_image_id_by_tag(self):
self.skipTest("Implemented but not used")
def set_image_tag(self):
self.skipTest("Implemented but not used")
class
|
(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
@mock.patch.object(V2, '_validate_response', name='mock_v2_validate_response', return_value=True)
@mock.patch.object(V2, '_request_builder', name='mock_v2_request_builder')
@mock.patch('freight_forwarder.registry.registry_base.requests', autospec=True)
def test_v2_search(self, mock_requests, mock_request_builder, mock_validate_response):
# Defined Search Request
search_response_content = json.dumps({"repositories": ["appexample/test-app",
"appexample/test-db",
"appexample/test-cache"]}).encode('utf-8')
response = create_response_object(url="https://v2search.registry.docker.com",
status_code=200,
content=search_response_content)
# Define Response Value for content once request has been validated
mock_request_builder.return_value = response
# Define Default value for utils _validate_response
mock_validate_response.return_value = True
# Build V1 Factory Registry
test_registry = RegistryV2Factory(address='https://v2search.registry.docker.com')
test_registry.search("test")
for search in test_registry.search("test"):
search_output = "".join(search)
self.assertIsInstance(search_output, six.string_types)
@mock.patch.object(V2, '_validate_response', name='mock_v2_validate_response', return_value=True)
@mock.patch.object(V2, '_request_builder', name='mock_v2_request_builder')
@mock.patch('freight_forwarder.registry.registry_base.requests', autospec=True)
def test_v2_tags(self, mock_requests, mock_request_builder, mock_validate_response):
tag_response_content = json.dumps({"name": "appexample/test-app",
"tags": [
"latest",
"0.0.15",
"asdfasb81"]
}
).encode('utf-8')
formatted_output = ['appexample/test-app:latest',
'appexample/test-app:0.0.15',
'appexample/test-app:asdfasb81']
response = create_response_object(url="https://v2tags.registry.docker.com",
status_code=200,
content=tag_response_content)
mock_request_builder.return_value = response
mock_validate_response.return_value = True
test_registry = RegistryV2Factory(address='https://v2tags.registry.docker.com')
for tags in test_registry.tags("appexample/test-app"):
tag_output = "".join(tags)
self.assertIsInstance(tag_output, six.string_types)
self.assertIn(tag_output, formatted_output)
def test_blobs(self):
self.skipTest("Not implemented")
def test_catalog(self, count=None, last=None):
self.skipTest("Not implemented")
def test_manifests(self):
self.skipTest("Not implemented")
class RegistryBaseTests(unittest.TestCase):
def setUp(self):
self.patch_requests = mock.patch('freight_forwarder.registry.registry_base.requests', autospec=True)
self.patch_requests.start()
self.test_registry = RegistryV1Factory(address="https://registrybasetest.docker.com")
def tearDown(self):
self.patch_requests.stop()
del self.test_registry
def test_ping(self):
self.skipTest("Defined as abc method. Override in class")
def test_tags(self):
self.skipTest("Defined as abc method. Override in class")
def test_init(self):
self.assertEquals(self.test_registry.scheme, 'https://')
self.assertEquals(self.test_registry.location, 'registrybasetest.docker.com')
self.assertEquals(self.test_registry.auth, None)
self.assertEquals(self.test_registry.__str__(), "https://registrybasetest.docker.com")
self.assertIsInstance(self.test_registry, RegistryBase)
def test_registry_base_auth_base_functionality(self):
self.assertEquals(self.test_registry.auth, None)
with self.assertRaises(TypeError):
self.test_registry.auth = ["user=test_user", "passwd=password"]
def test_registry_base_auth_with_auth(self):
pass
class RegistryExceptionTest(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def test_exception_with_status_code_and_url(self):
response = create_response_object(url="https://bad.docker.io",
status_code=503,
content={"test": "data"})
registry_exception = RegistryException(response)
self.assertIsInstance(registry_exception, RegistryException)
self.assertEquals(registry_exception.response.status_code, 503)
def test_exception_with_no_content(self):
response = create_response_object(url="https://nocontent.docker.io",
status_code=503)
registry_exception = RegistryException(response)
self.assertIsInstance(registry_exception, RegistryException)
self.assertEquals(registry_exception.message, 'There was an issue with the request to the docker registry.')
def test_exception_with_error_content(self):
# TODO - grab a properly formatted error for testing
response = create_response_object(url="https://errorcontent.docker.io",
status_code=500,
content=json.dumps({'error': 'Docker Registry Error Example'}))
registry_exception = RegistryException(response)
self.assertIsInstance(registry_exception, RegistryException)
self.assertEquals(registry_exception.message, 'Docker Registry Error Example')
# Test the class.__str__ MagicMethod
self.assertEquals("{0}".format(registry_exception), 'Docker Registry Error Example')
def create_response_object(url, status_code, content=None):
"""
The function generates a mock object that is properly formatted for the RegistryException and validates the input
:param url: url to pass through for the mock request object
:param status_code: status code to append to the response object
:param content: **required** if not provided, this attribute will be blocked
:return: Parent Mock: request.Reponse Child Mock: request - requests.PreparedRequest
"""
if not isinstance(url, six.string_types):
raise(TypeError("incorrect type provided for url"))
if not isinstance(status_code, six.integer_types):
raise(TypeError("incorrect type provided for http status code"))
mock_object_request = mock.MagicMock(spec=requests.PreparedRequest, url=url)
mock_object_response = mock.MagicMock(spec=requests.Response, request=mock_object_request)
mock_object_response.status_code = status_code
if content:
mock_object_response.content = content
else:
# this blocks the content attribute from being present
del mock_object_response.content
return mock_object_response
def format_image_results(registry_response_dict):
"""
Response attribute content is formatted correctly for the Images
:param response: response object with content attribute
:return: dict of various images
"""
if not isinstance(registry_response_dict, dict):
raise TypeError('registry_response_dict must be a dict.')
images = {}
results = registry_response_dict.get('results')
if results:
for image in results:
images[image.get('name')] = image
return images
|
RegistryV2Test
|
string2.py
|
#!/usr/bin/python2.4 -tt
# Copyright 2010 Google Inc.
# Licensed under the Apache License, Version 2.0
# http://www.apache.org/licenses/LICENSE-2.0
# Google's Python Class
# http://code.google.com/edu/languages/google-python-class/
# Additional basic string exercises
# D. verbing
# Given a string, if its length is at least 3,
# add 'ing' to its end.
# Unless it already ends in 'ing', in which case
# add 'ly' instead.
# If the string length is less than 3, leave it unchanged.
# Return the resulting string.
def verbing(word):
if len(word) >= 3:
if word[-3:] == 'ing':
return word + 'ly'
else:
return word + 'ing'
else:
return word
return word
# E. not_bad
# Given a string, find the first appearance of the
# substring 'not' and 'bad'. If the 'bad' follows
# the 'not', replace the whole 'not'...'bad' substring
# with 'good'.
# Return the resulting string.
# So 'This dinner is not that bad!' yields:
# This dinner is good!
def not_bad(s):
neg_word = s.find('not')
if s.find('not') < s.find('bad'):
s = s[:neg_word] + 'good'
return s
# F. front_back
# Consider dividing a string into two halves.
# If the length is even, the front and back halves are the same length.
# If the length is odd, we'll say that the extra char goes in the front half.
# e.g. 'abcde', the front half is 'abc', the back half 'de'.
# Given 2 strings, a and b, return a string of the form
# a-front + b-front + a-back + b-back
def front_back(a, b):
lenght_first = len(a)
lenght_second = len(b)
if len(a) % 2 == 0:
a_first_half = a[:len(a) // 2]
a_second_half = a[-len(a_first_half):]
if len(a) % 2 != 0:
a_first_half = a[:len(a) // 2 + 1]
a_second_half = a[-(len(a_first_half) - 1):]
if len(b) % 2 == 0:
|
b_first_half = b[:len(b) // 2]
b_second_half = b[-len(b_first_half):]
if len(b) % 2 != 0:
b_first_half = b[:len(b) // 2 + 1]
b_second_half = b[-(len(b_first_half) - 1):]
return a_first_half + b_first_half + a_second_half + b_second_half
# Simple provided test() function used in main() to print
# what each function returns vs. what it's supposed to return.
def test(got, expected):
if got == expected:
prefix = ' OK '
else:
prefix = ' X '
print '%s got: %s expected: %s' % (prefix, repr(got), repr(expected))
# main() calls the above functions with interesting inputs,
# using the above test() to check if the result is correct or not.
def main():
print 'verbing'
test(verbing('hail'), 'hailing')
test(verbing('swiming'), 'swimingly')
test(verbing('do'), 'do')
print
print 'not_bad'
test(not_bad('This movie is not so bad'), 'This movie is good')
test(not_bad('This dinner is not that bad!'), 'This dinner is good')
test(not_bad('This tea is not hot'), 'This tea is not hot')
test(not_bad("It's bad yet not"), "It's bad yet not")
print
print 'front_back'
test(front_back('abcd', 'xy'), 'abxcdy')
test(front_back('abcde', 'xyz'), 'abcxydez')
test(front_back('Kitten', 'Donut'), 'KitDontenut')
if __name__ == '__main__':
main()
| |
index_20190731213754.js
|
import React, { Component } from "react";
import {
Col,
Row,
Layout,
Form,
Input,
Icon,
Divider,
Button,
Spin,
notification,
Upload,
message
} from "antd";
import BreadcrumbBee from "../../../../../componentes/BreadcrumBee";
import { connect } from "react-redux";
import { bindActionCreators } from "redux";
import {
getPerfil,
updatePerfil
} from "../../../../../redux/actions/tecnicoActions";
import "./styles.css";
import { colors } from "../../../../../assets";
class Perfil extends Component {
constructor(props) {
super(props);
this.state = {
userPerfil: {},
isClicouButtonUpate: false
};
}
componentDidMount = () => {
this.props.getPerfil();
};
componentWillReceiveProps = nextProps => {
const isClicouButtonUpate = this.state.isClicouButtonUpate;
if (nextProps && nextProps.code === 200 && isClicouButtonUpate) {
console.log('====================================');
console.log('Clicou: ', isClicouButtonUpate);
console.log('====================================');
notification.open({
message: "Operação realizado com sucesso",
description: nextProps.messagePerfil,
icon: <Icon type="smile" style={{ color: colors.COR_PRYMARY }} />
});
this.setState({ isClicouButtonUpate: false });
} else if (nextProps && nextProps.code === 422 && isClicouButtonUpate) {
notification.open({
message: "Falha ao realizar essa operação",
description: nextProps.messagePerfil,
icon: (
<Icon
type="smile"
rotate={180}
style={{ color: colors.COR_RED_ERROR }}
/>
)
});
this.setState({ isClicouButtonUpate: false });
}
};
handleSubmit = () => {
this.props.form.validateFields((err, values) => {
console.log("====================================");
console.log("Values: ", values);
console.log("====================================");
if (!err) {
this.setState({ isClicouButtonUpate: true });
this.props.updatePerfil({
request: values
});
}
});
};
render() {
const mapa = [
{
key: "/",
name: "Home",
icon: "home"
},
{
key: "perfil",
name: "Perfil",
icon: "user"
}
];
const { getFieldDecorator } = this.props.form;
const { loadingPerfil, userPerfil, loadingUpdatePerfil } =
this.props || null;
const props = {
name: "file",
action: "https://www.mocky.io/v2/5cc8019d300000980a055e76",
headers: {
authorization: "authorization-text"
}
// onChange(info) {
// if (info.file.status !== "uploading") {
// console.log(info.file, info.fileList);
// }
// if (info.file.status === "done") {
// message.success(`${info.file.name} file uploaded successfully`);
// } else if (info.file.status === "error") {
// message.error(`${info.file.name} file upload failed.`);
// }
// }
};
return (
<Layout.Content style={{ margin: "0 16px" }}>
<BreadcrumbBee mapa={mapa} />
<div
style={{
padding: 24,
margin: 10,
background: "#fff",
minHeight: 360,
boxShadow: "0 0 20px rgba(0, 0, 0, 0.1)"
}}
>
<Row>
<div
style={{
justifyContent: "center",
alignItems: "center",
display: "flex"
}}
>
{loadingPerfil ? (
<div
style={{
textAlign: "center",
justifyContent: "center",
alignItems: "center",
marginTop: 150
}}
>
<Spin size="large" />
</div>
) : (
<Col span={15}>
<div style={{ boxShadow: "0 0 20px rgba(0, 0, 0, 0.1)" }}>
<div className="editarDadosPessoais">
<img
src={userPerfil.foto}
className="fotoPerfilEditar"
alt={"Perfil"}
/>
<h3 className={"pendenciaEmailTelefone"} />
</div>
<div
style={{
padding: 24,
margin: 10,
background: "#fff",
minHeight: 360,
borderColor: "#000",
borderWidth: 1
}}
>
<Form style={{ padding: "2vh" }}>
<Divider orientation="left">
Dados básicos do apicultor
</Divider>
<div className="formStyle">
<Row gutter={24}>
<Col span={12}>
<Form.Item label="Nome">
{getFieldDecorator("name", {
initialValue: userPerfil.name || "",
rules: [
{
required: true,
message: "Por favor informe um nome!"
},
{
validator: this.compareToFirstPassword
}
]
})(
<Input
prefix={
<Icon
type="user"
style={{ color: "rgba(0,0,0,.25)" }}
/>
}
onBlur={this.handleConfirmBlur}
type="text"
placeholder="Endereço"
/>
)}
</Form.Item>
</Col>
<Col span={12}>
<Form.Item label="Email">
{getFieldDecorator("email", {
initialValue: userPerfil.email || "",
rules: [
{
required: true,
message: "Por favor informe seu email!"
},
{
validator: this.compareToFirstPassword
}
]
})(
<Input
prefix={
<Icon
type="mail"
style={{ color: "rgba(0,0,0,.25)" }}
/>
}
onBlur={this.handleConfirmBlur}
type="text"
placeholder="Endereço"
/>
)}
</Form.Item>
</Col>
</Row>
</div>
<Row gutter={8}>
<Col span={12}>
<Form.Item label="Insira uma senha">
{getFieldDecorator("password", {
rules: [
{
min: 5,
message:
"A senha tem que ter no minímo 5 caracteres!"
},
{
max: 20,
message:
"A senha tem que ter no máximo 20 caracteres!"
}
]
})(
<Input
prefix={
<Icon
type="lock"
style={{ color: "rgba(0,0,0,.25)" }}
/>
}
type="password"
placeholder="Senha"
/>
)}
</Form.Item>
</Col>
<Col span={12}>
<Form.Item label="Confirme a senha">
{getFieldDecorator("password_confirmation", {
rules: [
{
min: 5,
message:
"A senha tem que ter no minímo 5 caracteres!"
},
{
max: 20,
message:
"A senha tem que ter no máximo 20 caracteres!"
},
{
validator: this.compareToFirstPassword
}
]
})(
<Input
prefix={
<Icon
type="lock"
style={{ color: "rgba(0,0,0,.25)" }}
/>
}
type="password"
placeholder="Confirmar senha"
/>
)}
</Form.Item>
</Col>
<Col span={12}>
<Form.Item label="Insira uma senha">
{getFieldDecorator("password", {})(
<Upload {...props}>
<Button>
<Icon type="upload" /> Selecione uma foto
</Button>
</Upload>
)}
</Form.Item>
</Col>
</Row>
<Row gutter={8}>
<div className="buttonsAction">
<Button
key="submit"
type="primary"
loading={loadingUpdatePerfil}
onClick={this.handleSubmit}
>
Salvar alterações
</Button>
</div>
</Row>
</Form>
</div>
</div>
</Col>
)}
</div>
</Row>
</div>
</Layout.Content>
);
}
}
const WrappedNormalLoginForm = Form.create({ name: "normal_login" })(Perfil);
function mapStateToPro
|
) {
return {
userPerfil: state.tecnicoState.userPerfil,
loadingPerfil: state.tecnicoState.loadingPerfil,
loadingUpdatePerfil: state.tecnicoState.loadingUpdatePerfil,
messagePerfil: state.tecnicoState.messagePerfil,
code: state.tecnicoState.code
};
}
function mapDispatchToProps(dispatch) {
return bindActionCreators({ getPerfil, updatePerfil }, dispatch);
}
export default connect(
mapStateToProps,
mapDispatchToProps
)(WrappedNormalLoginForm);
|
ps(state, props
|
cube_model.py
|
"""
A user-facing wrapper around the neural network models for solving the cube.
"""
import models
|
from typing import Optional
class CubeModel:
_model = None # type: Optional[models.BaseModel]
def __init__(self):
pass
def load_from_config(self, filepath: Optional[str] = None) -> ():
"""
Build a model from the config file settings.
:param filepath: Optional string to filepath of model weights.
If None (default) then it will load based on the config file.
"""
import config
if filepath is None:
assert False, "Fill in this branch"
self.load(config.model_type, filepath, **config.model_kwargs)
def load(self, model_type: str, filepath: str, **kwargs) -> ():
"""
Build a model.
:param model_type: The name of the model class in models.py
:param filepath: The path to the model weights.
:param kwargs: Key word arguements for initializing the model class (the one given by model_type).
"""
model_constructor = models.__dict__[model_type] # get model class by name
self._model = model_constructor(**kwargs)
self._model.build()
self._model.load_from_file(filepath)
def _function(self):
assert (self._model is not None), "No model loaded"
return self._model.function
| |
setup.py
|
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
from __future__ import absolute_import, print_function
import io
import os
import re
from glob import glob
from os.path import basename
from os.path import dirname
from os.path import join
from os.path import relpath
from os.path import splitext
from setuptools import find_packages
from setuptools import setup
def read(*names, **kwargs):
return io.open(
join(dirname(__file__), *names),
encoding=kwargs.get('encoding', 'utf8')
).read()
tests_require=['nose']
|
setup(
name='absorbing_centrality',
version='0.1.0',
license='ISC',
description='An implementation of the absorbing random-walk centrality measure for graphs.',
long_description='%s\n%s' % (read('README.rst'), re.sub(':[a-z]+:`~?(.*?)`', r'``\1``', read('CHANGELOG.rst'))),
author='Charalampos Mavroforakis',
author_email='[email protected]',
url='https://github.com/harrymvr/absorbing-centrality',
packages=['absorbing_centrality'],
# package_dir={'': 'absorbing_centrality'},
# py_modules=[splitext(basename(path))[0] for path in glob('absorbing_centrality/*.py')],
include_package_data=True,
zip_safe=False,
test_suite='nose.collector',
classifiers=[
# complete classifier list: http://pypi.python.org/pypi?%3Aaction=list_classifiers
'Intended Audience :: Developers',
'Intended Audience :: Science/Research',
'Operating System :: Unix',
'Operating System :: POSIX',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'License :: OSI Approved :: ISC License (ISCL)',
'Topic :: Scientific/Engineering :: Information Analysis',
'Natural Language :: English'
],
keywords=['graph mining', 'node centrality', 'random walks', 'algorithms',
'data mining'
],
install_requires=[
'networkx>=1.9.1',
'numpy==1.9.2',
'scipy==0.16'
],
extras_require={
'tests': tests_require,
},
)
| |
floats.py
|
from typing import List
from typing_extensions import Annotated
from alpyro_msgs import RosMessage, float32
class
|
(RosMessage):
__msg_typ__ = "rospy_tutorials/Floats"
__msg_def__ = "ZmxvYXQzMltdIGRhdGEKCg=="
__md5_sum__ = "420cd38b6b071cd49f2970c3e2cee511"
data: Annotated[List[float32], 0, 0]
|
Floats
|
TSMessageEvent.js
|
/**
* @module ts.events
*/
define("ts/events/TSMessageEvent",[
"jsm/events/MessageEvent",
"ts/events/TSEvent"
],function(MessageEvent,TSEvent){
"use strict";
/**
* @namespace ts.events
* @class TSMessageEvent
* @constructor
* @param {String} type
* @param {Object} [init={bubbles:false,cancelable:false,
* source:null,lastEventId:"",data:null,origin:""
* }]
*/
function
|
(type/*,init*/){
TSEvent.call(this,type);
/**
* @attribute data
* @type *
*/
this.data=null;
/**
* @attribute source
* @type Window
*/
this.source=null;
/**
* @attribute lastEventId
* @type String
*/
this.lastEventId="";
/**
* @attribute origin
* @type String
*/
this.origin="";
var init=arguments[1];
if(init instanceof Object){
if("source" in init){this.source=init.source;}
if("lastEventId" in init){this.lastEventId=String(init.lastEventId);}
if("data" in init){this.data=init.data;}
if("origin" in init){this.source=String(init.origin);}
}
}
/**
* @method initChangeEvent
* @param {String} type
* @param {Boolean} [bubbles=false]
* @param {Boolean} [cancelable=false]
* @param {Window} [source=null]
* @param {String} [lastEventId=""],
* @param {Object} [data=null],
* @param {String} [origin=""],
*/
function initMessageEvent(type,bubbles,cancelable,source,lastEventId,data,origin){
this.type=String(type);
this.bubbles=!!bubbles;
this.cancelable=!!cancelable;
this.source=source||null;
this.lastEventId=""+lastEventId;
this.origin=""+origin;
}
ExtendClass(TSMessageEvent,TSEvent);
InstallFunctions(TSMessageEvent.prototype,DONT_DELETE,[
"initMessageEvent",initMessageEvent
]);
SetNativeFlag(TSMessageEvent);
ImplementInterface(TSMessageEvent,MessageEvent);
return TSMessageEvent;
});
|
TSMessageEvent
|
__init__.py
|
"""
Copyright 2016 Deepgram
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
|
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 .engine import Engine, ScopeStack
from .passthrough_engine import PassthroughEngine
from .jinja_engine import JinjaEngine
### EOF.EOF.EOF.EOF.EOF.EOF.EOF.EOF.EOF.EOF.EOF.EOF.EOF.EOF.EOF.EOF.EOF.EOF.EOF
|
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
|
send_message.rs
|
use serenity::{
client::Context,
model::interactions::{application_command::ApplicationCommandInteraction, InteractionResponseType}
};
use mrvn_model::{GuildModel, GuildActionMessage};
use mrvn_back_ytdl::Song;
use futures::prelude::*;
use crate::message::Message;
use crate::config::Config;
use serenity::model::prelude::ChannelId;
#[derive(Clone, Copy)]
pub enum SendMessageDestination<'interaction> {
Channel(ChannelId),
Interaction {
interaction: &'interaction ApplicationCommandInteraction,
is_edit: bool,
}
}
pub async fn send_messages(
config: &Config,
ctx: &Context,
destination: SendMessageDestination<'_>,
guild_model: &mut GuildModel<Song>,
mut messages: Vec<Message>,
) -> Result<(), crate::error::Error> {
let message_channel_id = match destination {
SendMessageDestination::Channel(channel) => channel,
SendMessageDestination::Interaction { interaction, .. } => interaction.channel_id,
|
};
// Action messages are special: we only keep the latest one around. This also means out of
// this list we only want to send the last action message.
let maybe_last_action_message_index = messages.iter().rposition(|message| message.is_action());
if let Some(last_action_message_index) = maybe_last_action_message_index {
let mut index = 0;
messages.retain(|message| {
let is_valid = !message.is_action() || index == last_action_message_index;
index += 1;
is_valid
});
}
let mut messages_iter = messages.into_iter();
// Send the first message as an interaction response, if our destination is an interaction.
let maybe_first_message = match destination {
SendMessageDestination::Channel(_) => None,
SendMessageDestination::Interaction { .. } => messages_iter.next(),
};
let first_message_future = async {
if let (SendMessageDestination::Interaction { interaction, is_edit }, Some(first_message)) = (destination, maybe_first_message) {
if is_edit {
interaction.edit_original_interaction_response(&ctx.http, |response| {
response.create_embed(|embed| {
embed
.description(first_message.to_string(config))
.color(config.embed_color)
})
}).await.map_err(crate::error::Error::Serenity)?;
} else {
interaction.create_interaction_response(&ctx.http, |response| {
response
.kind(InteractionResponseType::ChannelMessageWithSource)
.interaction_response_data(|data| {
data.create_embed(|embed| {
embed
.description(first_message.to_string(config))
.color(config.embed_color)
})
})
}).await.map_err(crate::error::Error::Serenity)?;
}
}
Ok(())
};
// Send each remaining message as a regular message. If the message is the possible one
// action message, keep track of its ID so we can record it later.
let remaining_messages_future = future::try_join_all(messages_iter.map(|message| async move {
let channel_message = message_channel_id.send_message(&ctx.http, |create_message| {
create_message.embed(|embed| {
embed
.description(message.to_string(config))
.color(config.embed_color)
})
}).await.map_err(crate::error::Error::Serenity)?;
if message.is_action() {
Ok(Some(channel_message))
} else {
Ok(None)
}
}));
// Delete the guild's latest action message from before this operation, if this operation
// sent an action message.
let old_action_message = guild_model.last_action_message();
let delete_old_action_message_future = async {
if maybe_last_action_message_index.is_some() {
if let Some(old_action_message) = old_action_message {
old_action_message
.channel_id
.delete_message(&ctx.http, old_action_message.message_id)
.await
.map_err(crate::error::Error::Serenity)?;
}
}
Ok(())
};
// Execute all the message sending!
let (_, remaining_messages, _) = futures::try_join!(first_message_future, remaining_messages_future, delete_old_action_message_future)?;
// Set the guild's last action message to the message we sent, if there was one.
// If we were expecting an action message but there isn't one collected after sending,
// the action message was probably sent as the interaction response. This can't be deleted
// later so we record there being no last action message.
if maybe_last_action_message_index.is_some() {
let maybe_sent_message = remaining_messages
.iter()
.find_map(|maybe_message| maybe_message.as_ref());
guild_model.set_last_action_message(maybe_sent_message.map(|sent_message| GuildActionMessage {
channel_id: sent_message.channel_id,
message_id: sent_message.id,
}));
}
Ok(())
}
| |
slack_test.go
|
package main
import (
"fmt"
"testing"
)
func Test_humanize(t *testing.T)
|
{
cases := []struct {
n int64
e string
}{
{n: 1, e: "¥1"},
{n: 123, e: "¥123"},
{n: 1234, e: "¥1,234"},
{n: 123456, e: "¥123,456"},
{n: 1234567, e: "¥1,234,567"},
}
for _, c := range cases {
t.Run(fmt.Sprint(c.n), func(t *testing.T) {
a := humanize(c.n)
if c.e != a {
t.Errorf("expected %s, but %s", c.e, a)
}
})
}
}
|
|
pms7003.go
|
/*
Package dev ...
PMS7003 is the driver of PMS7003, an air quality sensor which can be used to detect PM2.5 and PM10.
Config Your Pi:
1. $ sudo vim /boot/config.txt
add following new line:
~~~~~~~~~~~~~~~~~
enable_uart=1
~~~~~~~~~~~~~~~~~
2. $ sudo vim /boot/cmdline.txt
remove following contexts:
~~~~~~~~~~~~~~~~~~~~~~~~~~
console=serial0,115200
~~~~~~~~~~~~~~~~~~~~~~~~~~
3. $ sudo reboot now
4. $ sudo cat /dev/ttyAMA0
should see somethings output
Connect to Pi:
- VCC: any 5v pin
- GND: any gnd pin
- TXD: must connect to pin 10(gpio 15) (RXD)
- RXT: must connect to pin 8(gpio 14) (TXD)
*/
package dev
import (
"errors"
"fmt"
"math"
"github.com/jakefau/rpi-devices/util"
"github.com/tarm/serial"
)
const (
maxDeltaPM25 = 150
)
var (
mockData = []uint16{50, 110, 150, 110, 50}
mockIdx = 0
)
// PMS7003 ...
type PMS7003 struct {
port *serial.Port
history *util.History
buf [128]byte
retry int
}
// NewPMS7003 ...
func NewPMS7003(dev string, baud int) *PMS7003
|
// Get returns pm2.5 and pm10 in ug/m3
func (p *PMS7003) Get() (uint16, uint16, error) {
for i := 0; i < p.retry; i++ {
if err := p.port.Flush(); err != nil {
return 0, 0, err
}
a := 0
for a < 32 {
n, err := p.port.Read(p.buf[a:])
if err != nil {
return 0, 0, fmt.Errorf("error on read from port, error: %v. try to open serial again", err)
}
a += n
}
if a != 32 {
continue
}
if p.buf[0] != 0x42 && p.buf[1] != 0x4d && p.buf[2] != 0 && p.buf[3] != 28 {
continue
}
checksum := uint16(0)
for i := 0; i < 29; i++ {
checksum += uint16(p.buf[i])
}
if checksum != (uint16(p.buf[30])<<8)|uint16(p.buf[31]) {
continue
}
pm25 := (uint16(p.buf[6]) << 8) | uint16(p.buf[7])
pm10 := (uint16(p.buf[8]) << 8) | uint16(p.buf[9])
if !p.checkDelta(pm25) {
continue
}
return pm25, pm10, nil
}
return 0, 0, fmt.Errorf("psm7003 is invalid currently")
}
// MockGet mocks Get()
func (p *PMS7003) MockGet() (uint16, uint16, error) {
n := len(mockData)
if n == 0 {
return 0, 0, errors.New("without data")
}
if mockIdx >= n {
mockIdx = 0
}
pm25 := mockData[mockIdx]
pm10 := mockData[mockIdx]
mockIdx++
return pm25, pm10, nil
}
// Close ...
func (p *PMS7003) Close() {
p.port.Close()
}
func (p *PMS7003) open(dev string, baud int) error {
c := &serial.Config{Name: dev, Baud: baud}
port, err := serial.OpenPort(c)
if err != nil {
return err
}
p.port = port
return nil
}
func (p *PMS7003) checkDelta(pm25 uint16) bool {
avg, err := p.history.Avg()
if err != nil {
if err == util.ErrEmpty {
p.history.Add(pm25)
return true
}
return false
}
passed := math.Abs(avg-float64(pm25)) < maxDeltaPM25
if passed {
p.history.Add(pm25)
}
return passed
}
|
{
p := &PMS7003{
history: util.NewHistory(10),
retry: 10,
}
if err := p.open(dev, baud); err != nil {
return nil
}
return p
}
|
server.go
|
package server
import (
"context"
"net"
"strconv"
"time"
"github.com/ntons/log-go"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/health"
"google.golang.org/grpc/health/grpc_health_v1"
"google.golang.org/grpc/keepalive"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
)
const (
xRequestId = "x-request-id"
xLibraAppId = "x-libra-app-id"
xLibraAppSecret = "x-libra-app-secret"
xLibraRoleId = "x-libra-role-id"
xLibraTrustedAppId = "x-libra-trusted-app-id"
xLibraTrustedUserId = "x-libra-trusted-user-id"
xLibraTrustedRoleId = "x-libra-trusted-role-id"
xLibraTrustedRoleIndex = "x-libra-trusted-role-index"
)
type callKey struct{}
func FromIncomingContext(ctx context.Context) (call *Call, ok bool) {
call, ok = ctx.Value(callKey{}).(*Call)
return
}
type Call struct {
log.Recorder
// these fields can be truested
AppId string
UserId string
RoleId string
RoleIndex int32
}
type Server struct {
// grpc server, implements ServiceRegistrar
s *grpc.Server
grpc.ServiceRegistrar
// life-time control
ctx context.Context
stop context.CancelFunc
// health status
status *health.Server
}
func NewServer(opts ...grpc.ServerOption) *Server
|
func (srv *Server) ListenAndServe(addr string) (err error) {
lis, err := net.Listen("tcp", addr)
if err != nil {
return
}
defer lis.Close()
return srv.Serve(lis)
}
func (srv *Server) Serve(lis net.Listener) (err error) {
grpc_health_v1.RegisterHealthServer(srv, srv.status)
defer srv.status.Shutdown()
go srv.s.Serve(lis)
defer srv.s.GracefulStop()
<-srv.Done()
return
}
func (srv *Server) Stop() { srv.stop() }
func (srv *Server) Done() <-chan struct{} { return srv.ctx.Done() }
func (srv *Server) intercept(
ctx context.Context, req interface{}, info *grpc.UnaryServerInfo,
handler grpc.UnaryHandler) (resp interface{}, err error) {
if info.Server == srv.status {
return handler(ctx, req)
}
md, ok := metadata.FromIncomingContext(ctx)
if !ok {
return nil, status.Errorf(codes.InvalidArgument, "metadata required")
}
log.Debugw("call-in", "method", info.FullMethod, "metadata", md)
fromMD := func(key string) string {
if values := md.Get(key); len(values) > 0 {
return values[0]
}
return ""
}
appId := fromMD(xLibraTrustedAppId)
userId := fromMD(xLibraTrustedUserId)
roleId := fromMD(xLibraTrustedRoleId)
if appId == "" || userId == "" || roleId == "" {
return nil, status.Errorf(
codes.PermissionDenied, "require trusted session")
}
roleIndex, err := strconv.ParseInt(fromMD(xLibraTrustedRoleIndex), 10, 32)
if err != nil {
return nil, status.Errorf(
codes.PermissionDenied, "require trusted session")
}
call := &Call{
Recorder: log.With(log.M{
"app": appId,
"user": userId,
"role": roleId,
"request": fromMD(xRequestId),
}),
AppId: appId,
UserId: userId,
RoleId: roleId,
RoleIndex: int32(roleIndex),
}
defer func() {
if r := recover(); r != nil {
call.Errorf("recover from %v", r)
var ok bool
if err, ok = r.(error); !ok {
err = status.Errorf(codes.Aborted, "%s", r)
}
}
}()
resp, err = handler(context.WithValue(ctx, callKey{}, call), req)
return
}
|
{
srv := &Server{status: health.NewServer()}
srv.ctx, srv.stop = context.WithCancel(context.Background())
grpcsrv := grpc.NewServer(append(
opts,
grpc.KeepaliveEnforcementPolicy(
keepalive.EnforcementPolicy{
MinTime: 30 * time.Second,
},
),
grpc.ChainUnaryInterceptor(srv.intercept),
)...)
srv.s, srv.ServiceRegistrar = grpcsrv, grpcsrv
return srv
}
|
PlayerContext.tsx
|
import {createContext, ReactNode, useContext, useState} from 'react'
type Episode = {
title: string;
members: string;
thumbnail: string;
duration: number;
url: string;
}
type PlayerContextData = {
episodeList: Array<Episode>
currentEpisodeIndex: number;
isPlaying: boolean;
isLooping: boolean;
isShuffling: boolean;
play: (episode: Episode) => void;
playList: (list: Episode[], index: number) => void;
setPlayingState: (state: boolean) => void;
clearPlayerState: () => void;
togglePlay: () => void;
toggleLoop: () => void;
toggleShuffle: () => void;
playNext: () => void;
playPrevious: () => void;
hasNext: boolean;
hasPrevious: boolean;
}
type PlayerContextProviderProps = {
children: ReactNode;
}
export const PlayerContext = createContext({} as PlayerContextData)
export function PlayerContextProvider({children}: PlayerContextProviderProps) {
const [episodeList, setEpisodeList] = useState([])
const [currentEpisodeIndex, setCurrentEpisodeIndex] = useState(0)
const [isPlaying, setIsPlaying] = useState(false)
const [isLooping, setIsLooping] = useState(false)
|
setEpisodeList([episode])
setCurrentEpisodeIndex(0)
setIsPlaying(true)
}
function playList(list: Episode[], index: number) {
setEpisodeList(list)
setCurrentEpisodeIndex(index)
setIsPlaying(true)
}
function togglePlay() {
setIsPlaying(!isPlaying)
}
function toggleLoop() {
setIsLooping(!isLooping)
}
function toggleShuffle() {
setIsShuffling(!isShuffling)
}
function setPlayingState(state: boolean){
setIsPlaying(state)
}
function clearPlayerState() {
setEpisodeList([]);
setCurrentEpisodeIndex(0);
}
const hasPrevious = currentEpisodeIndex > 0;
const hasNext = isShuffling || (currentEpisodeIndex + 1) < episodeList.length;
function playNext() {
if (isShuffling) {
const nextRandomEpisodeIndex = Math.floor(Math.random() * episodeList.length)
setCurrentEpisodeIndex(nextRandomEpisodeIndex);
} else if (hasNext){
setCurrentEpisodeIndex(currentEpisodeIndex + 1)
}
}
function playPrevious() {
if (hasPrevious) {
setCurrentEpisodeIndex(currentEpisodeIndex - 1)
}
}
return(
<PlayerContext.Provider
value={{
episodeList,
currentEpisodeIndex,
play,
isPlaying,
isLooping,
isShuffling,
togglePlay,
toggleLoop,
toggleShuffle,
setPlayingState,
clearPlayerState,
playList,
playNext,
playPrevious,
hasPrevious,
hasNext,
}}
>
{children}
</PlayerContext.Provider>
)
}
export const usePlayer = () => {
return useContext(PlayerContext)
}
|
const [isShuffling, setIsShuffling] = useState(false)
function play(episode: Episode){
|
post.rs
|
use actix_identity::Identity;
use actix_web::{get, http, post, web, HttpResponse};
use chrono::NaiveDateTime;
use diesel::prelude::*;
use nanoid::nanoid;
use serde_derive::{Deserialize, Serialize};
use tera::Context;
use crate::model::model_post::*;
use crate::schema::posts;
use crate::utils::{connections::*, time::*};
#[derive(Insertable, Deserialize, Serialize, Debug)]
#[table_name = "posts"]
pub struct NewPost<'a> {
pub id_url: &'a str,
pub title: &'a str,
pub subtitle: &'a str,
pub body: &'a str,
pub published: bool,
pub create_time: NaiveDateTime,
pub tags: Vec<String>,
}
#[derive(Serialize, Deserialize)]
pub struct CreatePostForm {
pub title: String,
pub subtitle: String,
pub body: String,
pub tags: String,
}
#[derive(Insertable, Deserialize, Serialize, Debug, AsChangeset)]
#[table_name = "posts"]
pub struct EditedPost<'a> {
pub id_url: &'a str,
pub title: &'a str,
pub subtitle: &'a str,
pub body: &'a str,
pub tags: Vec<String>,
}
#[derive(Serialize, Deserialize)]
pub struct EditPostForm {
pub title: String,
pub subtitle: String,
pub body: String,
pub tags: String,
}
#[derive(AsChangeset, Serialize, Deserialize, Debug)]
#[table_name = "posts"]
pub struct DeletePostForm {
pub id: i32,
pub published: bool,
}
#[post("/create")]
pub fn create_new_post(form: web::Form<CreatePostForm>, id: Identity, db: DB) -> HttpResponse {
match id.identity() {
Some(_) => {
let new_post = NewPost {
id_url: &nanoid!(),
title: &form.title,
subtitle: &form.subtitle,
body: &form.body,
published: true,
create_time: get_now(),
tags: if form.tags.is_empty() {
vec![]
} else {
form.tags.split('/').map(String::from).collect()
},
};
diesel::insert_into(posts::table)
.values(&new_post)
.get_result::<Post>(&*db)
.expect("Error saving new post");
HttpResponse::Found()
.header(http::header::LOCATION, "/")
.finish()
}
None => HttpResponse::Found()
.header(http::header::LOCATION, "/")
.finish(),
}
}
#[get("/{post_url}/admin/edit_post")]
pub fn get_edit_post_page(
tmpl: web::Data<tera::Tera>,
id: Identity,
post_url: web::Path<String>,
db: DB,
) -> HttpResponse {
match id.identity() {
Some(_) => {
let mut context = Context::new();
let post = Post::find_by_url(&post_url, &db).unwrap();
context.insert("post", &post);
context.insert("post_url", &post.id_url);
let s = tmpl.render("admin/edit_post.html", &context).unwrap();
HttpResponse::Ok().content_type("text/html").body(s)
}
None => HttpResponse::Found()
.header(http::header::LOCATION, "/")
.finish(),
}
}
#[post("/{post_url}/edit_post")]
pub fn edit_post(
post_url: web::Path<String>,
form: web::Form<EditPostForm>,
id: Identity,
db: DB,
) -> HttpResponse {
match id.identity() {
Some(_) => {
let edited_post = EditedPost {
id_url: &post_url,
title: &form.title,
subtitle: &form.subtitle,
body: &form.body,
tags: if form.tags.is_empty() {
vec![]
} else {
form.tags.split('/').map(String::from).collect()
},
};
let post = Post::find_by_url(&post_url, &db).unwrap();
diesel::update(&post)
.set(&edited_post)
.get_result::<Post>(&*db)
.expect("Error edit post");
let url = &post_url.to_string();
HttpResponse::Found()
.header(http::header::LOCATION, format!("/post/{}", &url))
.finish()
}
None => HttpResponse::Found()
.header(http::header::LOCATION, "/")
.finish(),
}
}
#[post("/{post_url}/delete_post")]
pub fn delete_post(post_url: web::Path<String>, id: Identity, db: DB) -> HttpResponse {
match id.identity() {
Some(_) => {
|
};
diesel::update(posts::table.find(post.id))
.set(&delete_post)
.get_result::<Post>(&*db)
.expect("Error deleting this post.");
HttpResponse::Found()
.header(http::header::LOCATION, "/")
.finish()
}
None => HttpResponse::Found()
.header(http::header::LOCATION, "/")
.finish(),
}
}
|
let post = Post::find_by_url(&post_url, &db).unwrap();
let delete_post = DeletePostForm {
id: post.id,
published: false,
|
claim_parts.py
|
from typing import List
from aiogram.types import KeyboardButton, ReplyKeyboardMarkup
from keyboards import emojis
from repository import Repository
PART_NAMES: List[str] = ["head", "story", "essence", "proofs", "claims", "additions"]
def get_claim_parts_kb(user_id: int) -> ReplyKeyboardMarkup:
parts_status: dict = get_claim_parts_status(user_id)
claim_parts_kb = ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=True)
claim_parts_kb\
.add(KeyboardButton(f"{emojis.top_hat} шапка {emojis.check_mark if parts_status['head'] is True else ''}")) \
.add(KeyboardButton(f"{emojis.speech_balloon} фабула {emojis.check_mark if parts_status['story'] is True else ''}")) \
.add(KeyboardButton(f"{emojis.key} суть нарушения {emojis.check_mark if parts_status['essence'] is True else ''}")) \
.add(KeyboardButton(f"{emojis.page_with_curl} доказательства {emojis.check_mark if parts_status['proofs'] is True else ''}")) \
.add(KeyboardButton(f"{emojis.index_pointing_up} требования {emojis.check_mark if parts_status['claims'] is True else ''}")) \
.add(KeyboardButton(f"{emojis.card_index_dividers} приложения {emojis.check_mark if parts_status['additions'] is True else ''}"))
claim_parts_kb.row(*[KeyboardButton(f"{emojis.left_arrow} к шаблонам"),
KeyboardButton(f"{emojis.inbox_tray} получить")])
return claim_parts_kb
def get_claim_parts_status(user_id: int) -> dict:
repository: Repository =
|
_data: dict = repository.get_claim_data(user_id)
if "claim_data" not in claim_data.keys():
return {pn: False for pn in PART_NAMES}
parts_status: dict = {}
for part_name in PART_NAMES:
if part_name in claim_data["claim_data"].keys():
parts_status.update(**{part_name: True})
else:
parts_status.update(**{part_name: False})
return parts_status
|
Repository()
claim
|
parse.rs
|
//! parse
//! It is a module that parses and executes commands.
/// Collection of functions related to shell commands and processes.
pub mod shell_command {
use crate::prelude::*;
use anyhow::*;
use async_trait::async_trait;
use smol::process::{Child as SmolChild, Command as SmolCommand};
use std::collections::LinkedList;
use std::convert::AsRef;
use std::ffi::OsStr;
use std::fs::{File, OpenOptions};
use std::iter::Iterator;
use std::mem;
use std::ops::{Deref, DerefMut};
use std::path::Path;
use std::process::{Child as StdChild, Command, Output, Stdio};
/// The linkedlist of ChildGuard.
pub type ChildGuardList<T> = LinkedList<ChildGuard<T>>;
macro_rules! impl_command_unify{
($($command:ty => $child:ty),+) => {
$(impl CommandUnify<$child> for $command {
fn new<S: AsRef<OsStr>>(program: S) -> Self {
Self::new(program.as_ref())
}
fn args<I, S>(&mut self, args: I) -> &mut Self
where
I: IntoIterator<Item = S>,
S: AsRef<OsStr>,
{
self.args(args);
self
}
fn stdin<T: Into<Stdio>>(&mut self, cfg: T) -> &mut Self {
self.stdin(cfg);
self
}
fn stdout<T: Into<Stdio>>(&mut self, cfg: T) -> &mut Self {
self.stdout(cfg);
self
}
fn stderr<T: Into<Stdio>>(&mut self, cfg: T) -> &mut Self {
self.stderr(cfg);
self
}
fn spawn(&mut self) -> AnyResult<$child> {
Ok(self.spawn()?)
}
})+
}
}
/// Abstraction of command methods in multiple libraries.
pub trait CommandUnify<Child: ChildUnify>: Sized {
/// Constructs a new Command for launching the program at path program.
fn new<S: AsRef<OsStr>>(program: S) -> Self {
Self::new(program.as_ref())
}
/// Adds multiple arguments to pass to the program.
fn args<I, S>(&mut self, args: I) -> &mut Self
where
I: IntoIterator<Item = S>,
S: AsRef<OsStr>;
/// Configuration for the child process's standard input (stdin) handle.
fn stdin<T: Into<Stdio>>(&mut self, cfg: T) -> &mut Self;
/// Configuration for the child process's standard output (stdout) handle.
fn stdout<T: Into<Stdio>>(&mut self, cfg: T) -> &mut Self;
/// Configuration for the child process's standard error (stderr) handle.
fn stderr<T: Into<Stdio>>(&mut self, cfg: T) -> &mut Self;
/// Executes the command as a child process, returning a handle to it.
fn spawn(&mut self) -> AnyResult<Child>;
}
impl_command_unify!(Command => StdChild,SmolCommand => SmolChild);
cfg_tokio_support!(
use tokio::process::Command as TokioCommand;
use tokio::process::Child as TokioChild;
use std::convert::TryInto;
impl_command_unify!(TokioCommand => TokioChild);
);
#[async_trait]
/// Trait abstraction of multiple library process handles.
pub trait ChildUnify: Send + Sync {
/// Executes the command as a child process, waiting for it to finish and collecting all of its output.
async fn wait_with_output(self) -> AnyResult<Output>;
/// Convert stdout to stdio.
async fn stdout_to_stdio(&mut self) -> Option<Stdio>;
/// Kill the process child.
fn kill(&mut self) -> AnyResult<()>;
}
#[async_trait]
impl ChildUnify for StdChild {
async fn wait_with_output(self) -> AnyResult<Output> {
Ok(self.wait_with_output()?)
}
async fn stdout_to_stdio(&mut self) -> Option<Stdio> {
self.stdout.take().map(Stdio::from)
}
fn kill(&mut self) -> AnyResult<()> {
Ok(self.kill()?)
}
}
#[async_trait]
impl ChildUnify for SmolChild {
async fn wait_with_output(self) -> AnyResult<Output> {
Ok(self.output().await?)
}
async fn stdout_to_stdio(&mut self) -> Option<Stdio> {
if let Some(stdout) = self.stdout.take() {
return stdout.into_stdio().await.ok();
}
None
}
fn kill(&mut self) -> AnyResult<()> {
Ok(self.kill()?)
}
}
cfg_tokio_support!(
#[async_trait]
impl ChildUnify for TokioChild {
async fn wait_with_output(self) -> AnyResult<Output> {
Ok(self.wait_with_output().await?)
}
async fn stdout_to_stdio(&mut self) -> Option<Stdio> {
self.stdout.take().map(|s| s.try_into().ok()).flatten()
}
// Attempts to force the child to exit, but does not wait for the request to take effect.
// On Unix platforms, this is the equivalent to sending a SIGKILL.
// Note that on Unix platforms it is possible for a zombie process to remain after a kill is sent;
// to avoid this, the caller should ensure that either child.wait().await or child.try_wait() is invoked successfully.
fn kill(&mut self) -> AnyResult<()> {
Ok(self.start_kill()?)
}
}
);
#[derive(Debug, Default)]
/// Guarding of process handles.
pub struct ChildGuard<Child: ChildUnify> {
pub(crate) child: Option<Child>,
}
impl<Child: ChildUnify> ChildGuard<Child> {
/// Build a `ChildGuard` with `Child`.
pub fn new(child: Child) -> Self {
let child = Some(child);
Self { child }
}
/// Take inner `Child` from `ChildGuard`.
pub fn take_inner(mut self) -> Option<Child> {
self.child.take()
}
/// Await on `ChildGuard` and get `Output`.
pub async fn wait_with_output(mut self) -> Result<Output, CommandChildError> {
if let Some(child) = self.child.take() {
return child
.wait_with_output()
.await
.map_err(|e| CommandChildError::DisCondition(e.to_string()));
}
Err(CommandChildError::DisCondition(
"Without child for waiting.".to_string(),
))
}
}
impl<Child: ChildUnify> Drop for ChildGuard<Child> {
fn drop(&mut self) {
if let Some(child) = self.child.as_mut() {
child
.kill()
.unwrap_or_else(|e| error!(" `ChildGuard` : {}", e));
}
}
}
impl<Child: ChildUnify> Deref for ChildGuard<Child> {
type Target = Option<Child>;
fn deref(&self) -> &Self::Target {
&self.child
}
}
impl<Child: ChildUnify> DerefMut for ChildGuard<Child> {
fn deref_mut(&mut self) -> &mut Self::Target
|
}
//that code base on 'build-your-own-shell-rust'. Thanks you Josh Mcguigan.
/// Generate a list of processes from a string of shell commands.
// There are a lot of system calls that happen when this method is called,
// the speed of execution depends on the parsing of the command and the speed of the process fork,
// after which it should be split into unblock().
pub async fn parse_and_run<Child: ChildUnify, Command: CommandUnify<Child>>(
input: &str,
) -> Result<ChildGuardList<Child>, CommandChildError> {
// Check to see if process_linked_list is also automatically dropped out of scope
// by ERROR's early return and an internal kill method is executed.
let mut process_linked_list: ChildGuardList<Child> = LinkedList::new();
// must be peekable so we know when we are on the last command
let commands = input.trim().split(" | ").peekable();
//if str has >> | > ,after spawn return.
let mut _stdio: Stdio;
for mut command in commands {
let check_redirect_result = _has_redirect_file(command);
if check_redirect_result.is_some() {
command = _remove_angle_bracket_command(command)
.map_err(|e| CommandChildError::DisCondition(e.to_string()))?;
}
let mut parts = command.trim().split_whitespace();
let command = parts
.next()
.ok_or_else(|| CommandChildError::DisCondition("Without next part".to_string()))?;
let args = parts;
// Standard input to the current process.
// If previous_command is present, it inherits the standard output of the previous command.
// If not, it inherits the current parent process.
let previous_command = process_linked_list.back_mut();
let mut stdin = Stdio::inherit();
if let Some(previous_command_ref) = previous_command {
let mut t = None;
if let Some(child_mut) = previous_command_ref.child.as_mut() {
mem::swap(&mut child_mut.stdout_to_stdio().await, &mut t);
}
if let Some(child_stdio) = t {
stdin = child_stdio;
}
}
let mut output = Command::new(command);
output.args(args).stdin(stdin).stderr(Stdio::piped());
let process: Child;
let end_flag = if let Some(stdout_result) = check_redirect_result {
let stdout =
stdout_result.map_err(|e| CommandChildError::DisCondition(e.to_string()))?;
process = output
.stdout(stdout)
.spawn()
.map_err(|e| CommandChildError::DisCondition(e.to_string()))?;
true
} else {
let stdout;
// if commands.peek().is_some() {
// // there is another command piped behind this one
// // prepare to send output to the next command
stdout = Stdio::piped();
// } else {
// // there are no more commands piped behind this one
// // send output to shell stdout
// // TODO:It shouldn't be the standard output of the parent process in the context,
// // there should be a default file to record it.
// stdout = Stdio::inherit();
// };
process = output
.stdout(stdout)
.spawn()
.map_err(|e| CommandChildError::DisCondition(e.to_string()))?;
false
};
process_linked_list.push_back(ChildGuard::<Child>::new(process));
if end_flag {
break;
}
}
Ok(process_linked_list)
}
// I should give Option<Result<File>>
//By Option(Some(Result<T>)), determine if there is an output stdio..
//By Result<T>(OK(t)), determine if there is success open file.
#[cfg(not(SPLIT_INCLUSIVE_COMPATIBLE))]
fn _has_redirect_file(command: &str) -> Option<Result<File>> {
let angle_bracket = if command.contains(">>") {
">>"
} else if command.contains('>') {
">"
} else {
return None;
};
if let Some(filename) = command.trim().rsplit(angle_bracket).next() {
Some(create_stdio_file(angle_bracket, filename))
} else {
None
}
}
#[cfg(SPLIT_INCLUSIVE_COMPATIBLE)]
fn _has_redirect_file(command: &str) -> Option<Result<File>> {
let angle_bracket = if command.contains(">>") {
">>"
} else if command.contains('>') {
">"
} else {
return None;
};
let mut sub_command_inner = command.trim().split_inclusive(angle_bracket).rev();
sub_command_inner
.next()
.map(|filename| create_stdio_file(angle_bracket, filename))
}
//After confirming that there is a redirect file, parse the command before the command '>'.
fn _remove_angle_bracket_command(command: &str) -> Result<&str> {
let mut sub_command_inner = command.trim().split('>');
sub_command_inner
.next()
.ok_or_else(|| anyhow!("can't parse ...."))
}
fn create_stdio_file(angle_bracket: &str, filename: &str) -> Result<File> {
let mut file_tmp = OpenOptions::new();
file_tmp.write(true).create(true);
if angle_bracket == ">>" {
file_tmp.append(true);
}
//TODO:I need record that open file error because filename has a whitespace i don't trim.
let os_filename = Path::new(filename.trim()).as_os_str();
let stdio_file = file_tmp.open(os_filename)?;
Ok(stdio_file)
}
}
|
{
&mut self.child
}
|
cifar10_train.py
|
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import norm
import pickle
from keras.layers import Input, Dense, Lambda, Flatten, Reshape, Layer
from keras.layers import Conv2D, Conv2DTranspose
from keras.models import Model
from keras import backend as K
from keras import metrics
# import parameters
from cifar10_params import *
from utils import *
# tensorflow uses channels_last
# theano uses channels_first
if K.image_data_format() == 'channels_first':
original_img_size = (img_chns, img_rows, img_cols)
else:
original_img_size = (img_rows, img_cols, img_chns)
# encoder architecture
x = Input(shape=original_img_size)
conv_1 = Conv2D(img_chns,
kernel_size=(2, 2),
padding='same', activation='relu')(x)
conv_2 = Conv2D(filters,
kernel_size=(2, 2),
padding='same', activation='relu',
strides=(2, 2))(conv_1)
conv_3 = Conv2D(filters,
kernel_size=num_conv,
padding='same', activation='relu',
strides=1)(conv_2)
conv_4 = Conv2D(filters,
kernel_size=num_conv,
padding='same', activation='relu',
strides=1)(conv_3)
flat = Flatten()(conv_4)
hidden = Dense(intermediate_dim, activation='relu')(flat)
# mean and variance for latent variables
z_mean = Dense(latent_dim)(hidden)
z_log_var = Dense(latent_dim)(hidden)
# sampling layer
def sampling(args):
z_mean, z_log_var = args
epsilon = K.random_normal(shape=(K.shape(z_mean)[0], latent_dim),
mean=0., stddev=epsilon_std)
return z_mean + K.exp(z_log_var) * epsilon
z = Lambda(sampling, output_shape=(latent_dim,))([z_mean, z_log_var])
# decoder architecture
decoder_hid = Dense(int(intermediate_dim), activation='relu')
decoder_upsample = Dense(int(filters * img_rows / 2 * img_cols / 2), activation='relu')
if K.image_data_format() == 'channels_first':
output_shape = (batch_size, filters, int(img_rows / 2), int(img_cols / 2))
else:
output_shape = (batch_size, int(img_rows / 2), int(img_cols / 2), filters)
decoder_reshape = Reshape(output_shape[1:])
decoder_deconv_1 = Conv2DTranspose(filters,
kernel_size=num_conv,
padding='same',
strides=1,
activation='relu')
decoder_deconv_2 = Conv2DTranspose(filters,
kernel_size=num_conv,
padding='same',
strides=1,
activation='relu')
decoder_deconv_3_upsamp = Conv2DTranspose(filters,
kernel_size=(3, 3),
strides=(2, 2),
padding='valid',
activation='relu')
decoder_mean_squash = Conv2D(img_chns,
kernel_size=2,
padding='valid',
activation='sigmoid')
hid_decoded = decoder_hid(z)
up_decoded = decoder_upsample(hid_decoded)
reshape_decoded = decoder_reshape(up_decoded)
deconv_1_decoded = decoder_deconv_1(reshape_decoded)
deconv_2_decoded = decoder_deconv_2(deconv_1_decoded)
x_decoded_relu = decoder_deconv_3_upsamp(deconv_2_decoded)
x_decoded_mean_squash = decoder_mean_squash(x_decoded_relu)
# Custom loss layer
class CustomVariationalLayer(Layer):
def __init__(self, **kwargs):
self.is_placeholder = True
super(CustomVariationalLayer, self).__init__(**kwargs)
def vae_loss(self, x, x_decoded_mean_squash):
x = K.flatten(x)
x_decoded_mean_squash = K.flatten(x_decoded_mean_squash)
xent_loss = img_rows * img_cols * metrics.binary_crossentropy(x, x_decoded_mean_squash)
kl_loss = - 0.5 * K.mean(1 + z_log_var - K.square(z_mean) - K.exp(z_log_var), axis=-1)
return K.mean(xent_loss + kl_loss)
def call(self, inputs):
x = inputs[0]
x_decoded_mean_squash = inputs[1]
loss = self.vae_loss(x, x_decoded_mean_squash)
self.add_loss(loss, inputs=inputs)
return x
y = CustomVariationalLayer()([x, x_decoded_mean_squash])
# entire model
vae = Model(x, y)
vae.compile(optimizer='rmsprop', loss=None)
vae.summary()
# load dataset
# (x_train, _), (x_test, y_test) = cifar10.load_data()
# x_train = x_train.astype('float32') / 255.
# x_train = x_train.reshape((x_train.shape[0],) + original_img_size)
# x_test = x_test.astype('float32') / 255.
# x_test = x_test.reshape((x_test.shape[0],) + original_img_size)
x_train, x_test = load_cifar10_with_validation(0.1, False)
# training
history = vae.fit(x_train,
shuffle=True,
epochs=epochs,
batch_size=batch_size,
validation_data=(x_test, None))
# encoder from learned model
encoder = Model(x, z_mean)
# generator / decoder from learned model
decoder_input = Input(shape=(latent_dim,))
_hid_decoded = decoder_hid(decoder_input)
_up_decoded = decoder_upsample(_hid_decoded)
_reshape_decoded = decoder_reshape(_up_decoded)
_deconv_1_decoded = decoder_deconv_1(_reshape_decoded)
_deconv_2_decoded = decoder_deconv_2(_deconv_1_decoded)
_x_decoded_relu = decoder_deconv_3_upsamp(_deconv_2_decoded)
_x_decoded_mean_squash = decoder_mean_squash(_x_decoded_relu)
generator = Model(decoder_input, _x_decoded_mean_squash)
# save all 3 models for future use - especially generator
|
# save training history
fname = './models/cifar10_ld_%d_conv_%d_id_%d_e_%d_history.pkl' % (latent_dim, num_conv, intermediate_dim, epochs)
with open(fname, 'wb') as file_pi:
pickle.dump(history.history, file_pi)
|
vae.save('./models/cifar10_ld_%d_conv_%d_id_%d_e_%d_vae.h5' % (latent_dim, num_conv, intermediate_dim, epochs))
encoder.save('./models/cifar10_ld_%d_conv_%d_id_%d_e_%d_encoder.h5' % (latent_dim, num_conv, intermediate_dim, epochs))
generator.save('./models/cifar10_ld_%d_conv_%d_id_%d_e_%d_generator.h5' % (latent_dim, num_conv, intermediate_dim, epochs))
|
NotificationHandler.js
|
import React, { Component } from 'react'
import { FlatList, View, StyleSheet, TouchableOpacity, Appearance } from 'react-native'
import { Icon, Text } from 'native-base'
import { connect } from 'react-redux'
import { withTranslation } from 'react-i18next'
import Sound from 'react-native-sound'
import moment from 'moment'
import Modal from 'react-native-modal'
import { CommonActions } from '@react-navigation/native'
import FontAwesome from 'react-native-vector-icons/FontAwesome'
import Ionicons from 'react-native-vector-icons/Ionicons'
import PushNotification from '../notifications'
import NavigationHolder from '../NavigationHolder'
import { clearNotifications, pushNotification, registerPushNotificationToken } from '../redux/App/actions'
import {loadTasks, selectTasksChangedAlertSound} from '../redux/Courier'
import { loadOrderAndNavigate, loadOrderAndPushNotification, loadOrder } from '../redux/Restaurant/actions'
import { message as wsMessage } from '../redux/middlewares/CentrifugoMiddleware/actions'
import tracker from '../analytics/Tracker'
import analyticsEvent from '../analytics/Event'
// Make sure sound will play even when device is in silent mode
Sound.setCategory('Playback')
/**
* This component is used
* 1/ To configure push notifications (see componentDidMount)
* 2/ To show notifications when the app is in foreground.
*/
class
|
extends Component {
constructor(props) {
super(props)
this.state = {
sound: null,
isSoundReady: false,
}
}
_onTasksChanged(date) {
if (this.props.currentRoute !== 'CourierTaskList') {
NavigationHolder.navigate('CourierTaskList', {})
}
this.props.loadTasks(moment(date))
}
_loadSound() {
const bell = new Sound('misstickle__indian_bell_chime.wav', Sound.MAIN_BUNDLE, (error) => {
if (error) {
return
}
bell.setNumberOfLoops(-1)
this.setState({
sound: bell,
isSoundReady: true,
})
})
}
_startSound() {
const { sound, isSoundReady } = this.state
if (isSoundReady) {
sound.play((success) => {
if (!success) {
sound.reset()
}
})
// Clear notifications after 10 seconds
setTimeout(() => this.props.clearNotifications(), 10000)
}
}
_stopSound() {
const { sound, isSoundReady } = this.state
if (isSoundReady) {
sound.stop(() => {})
}
}
includesNotification(notifications, predicate) {
return notifications.findIndex(predicate) !== -1
}
componentDidUpdate(prevProps) {
if (this.props.notifications !== prevProps.notifications) {
if (this.props.notifications.length > 0) {
if (this.includesNotification(this.props.notifications, n => n.event === 'order:created')) {
this._startSound()
} else if (this.includesNotification(this.props.notifications,n => n.event === 'tasks:changed')) {
if (this.props.tasksChangedAlertSound) {
this._startSound()
}
}
} else {
this._stopSound()
}
}
}
componentDidMount() {
this._loadSound()
PushNotification.configure({
onRegister: token => this.props.registerPushNotificationToken(token),
onNotification: message => {
const { event } = message.data
if (event && event.name === 'order:created') {
tracker.logEvent(
analyticsEvent.restaurant._category,
analyticsEvent.restaurant.orderCreatedMessage,
message.foreground ? 'in_app' : 'notification_center')
const { order } = event.data
// Here in any case, we navigate to the order that was tapped,
// it should have been loaded via WebSocket already.
this.props.loadOrderAndNavigate(order)
}
if (event && event.name === 'tasks:changed') {
tracker.logEvent(
analyticsEvent.courier._category,
analyticsEvent.courier.tasksChangedMessage,
message.foreground ? 'in_app' : 'notification_center')
if (message.foreground) {
this.props.pushNotification('tasks:changed', { date: event.data.date })
} else {
// user clicked on a notification in the notification center
this._onTasksChanged(event.data.date)
}
}
},
onBackgroundMessage: message => {
const { event } = message.data
if (event && event.name === 'order:created') {
this.props.loadOrder(event.data.order, (order) => {
if (order) {
// Simulate a WebSocket message
this.props.message({
name: 'order:created',
data: { order },
})
}
})
}
},
})
}
componentWillUnmount() {
PushNotification.removeListeners()
}
_keyExtractor(item, index) {
switch (item.event) {
case 'order:created':
return `order:created:${item.params.order.id}`
case 'tasks:changed':
return `tasks:changed:${moment()}`
}
}
renderItem(notification) {
switch (notification.event) {
case 'order:created':
return this.renderOrderCreated(notification.params.order)
case 'tasks:changed':
return this.renderTasksChanged(notification.params.date, notification.params.added, notification.params.removed)
}
}
_navigateToOrder(order) {
this._stopSound()
this.props.clearNotifications()
NavigationHolder.dispatch(CommonActions.navigate({
name: 'RestaurantNav',
params: {
screen: 'Main',
params: {
restaurant: order.restaurant,
// We don't want to load orders again when navigating
loadOrders: false,
screen: 'RestaurantOrder',
params: {
order,
},
},
},
}))
}
_navigateToTasks(date) {
this._stopSound()
this.props.clearNotifications()
NavigationHolder.dispatch(CommonActions.navigate({
name: 'CourierNav',
params: {
screen: 'CourierHome',
params: {
screen: 'CourierTaskList',
},
},
}))
this.props.loadTasks(moment(date))
}
renderOrderCreated(order) {
return (
<TouchableOpacity style={ styles.item } onPress={ () => this._navigateToOrder(order) }>
<Text>
{ this.props.t('NOTIFICATION_ORDER_CREATED_TITLE') }
</Text>
<Icon as={FontAwesome} name="chevron-right" />
</TouchableOpacity>
)
}
renderTasksChanged(date, added, removed) {
return (
<TouchableOpacity style={ styles.item } onPress={ () => this._navigateToTasks(date) }>
<View>
<Text style={{ fontSize: 14, fontWeight: '700' }}>
{ this.props.t('NOTIFICATION_TASKS_CHANGED_TITLE') }
</Text>
{ (added && Array.isArray(added) && added.length > 0) && (
<Text style={{ fontSize: 14 }}>
{ this.props.t('NOTIFICATION_TASKS_ADDED', { count: added.length }) }
</Text>
) }
{ (removed && Array.isArray(removed) && removed.length > 0) && (
<Text style={{ fontSize: 14 }}>
{ this.props.t('NOTIFICATION_TASKS_REMOVED', { count: removed.length }) }
</Text>
) }
</View>
<Icon as={FontAwesome} name="chevron-right" />
</TouchableOpacity>
)
}
renderModalContent() {
const colorScheme = Appearance.getColorScheme()
return (
<View style={ [ styles.modalContent, { backgroundColor: colorScheme === 'dark' ? 'black' : 'white' } ] }>
<View>
<View style={ styles.heading }>
<Icon as={Ionicons} name="notifications" style={{ color: 'white', marginRight: 10 }} />
<Text style={{ color: 'white' }}>{ this.props.t('NEW_NOTIFICATION') }</Text>
</View>
</View>
<FlatList
data={ this.props.notifications }
keyExtractor={ this._keyExtractor }
renderItem={ ({ item }) => this.renderItem(item) } />
<TouchableOpacity style={ styles.footer } onPress={ () => this.props.clearNotifications() }>
<Text style={{ color: '#FF4136' }}>
{ this.props.t('CLOSE') }
</Text>
</TouchableOpacity>
</View>
)
}
render() {
return (
<Modal isVisible={ this.props.isModalVisible }>
{ this.renderModalContent() }
</Modal>
)
}
}
const styles = StyleSheet.create({
heading: {
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'center',
paddingVertical: 25,
backgroundColor: '#39CCCC',
},
footer: {
alignItems: 'center',
justifyContent: 'center',
paddingVertical: 25,
},
modalContent: {
borderRadius: 4,
borderColor: 'rgba(0, 0, 0, 0.1)',
},
item: {
paddingVertical: 25,
paddingHorizontal: 20,
borderBottomColor: '#f7f7f7',
borderBottomWidth: StyleSheet.hairlineWidth,
flex: 1,
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'space-between',
},
})
function mapStateToProps(state) {
return {
currentRoute: state.app.currentRoute,
isModalVisible: state.app.notifications.length > 0,
notifications: state.app.notifications,
tasksChangedAlertSound: selectTasksChangedAlertSound(state),
}
}
function mapDispatchToProps (dispatch) {
return {
loadOrder: (order, cb) => dispatch(loadOrder(order, cb)),
loadOrderAndNavigate: order => dispatch(loadOrderAndNavigate(order)),
loadOrderAndPushNotification: order => dispatch(loadOrderAndPushNotification(order)),
loadTasks: (date) => dispatch(loadTasks(date)),
registerPushNotificationToken: token => dispatch(registerPushNotificationToken(token)),
clearNotifications: () => dispatch(clearNotifications()),
pushNotification: (event, params) => dispatch(pushNotification(event, params)),
message: payload => dispatch(wsMessage(payload)),
}
}
export default connect(mapStateToProps, mapDispatchToProps)(withTranslation()(NotificationHandler))
|
NotificationHandler
|
quickstart.rs
|
// Simple and robust error handling with error-chain!
// Use this as a template for new projects.
// `error_chain!` can recurse deeply
#![recursion_limit = "1024"]
// Import the macro. Don't forget to add `error-chain` in your
// `Cargo.toml`!
#[macro_use]
extern crate error_chain;
// We'll put our errors in an `errors` module, and other modules in
// this crate will `use errors::*;` to get access to everything
// `error_chain!` creates.
mod errors {
// Create the Error, ErrorKind, ResultExt, and Result types
error_chain!{}
}
// This only gives access within this module. Make this `pub use errors::*;`
// instead if the types must be accessible from other modules (e.g., within
// a `links` section).
use errors::*;
fn
|
() {
if let Err(ref e) = run() {
use std::io::Write;
let stderr = &mut ::std::io::stderr();
let errmsg = "Error writing to stderr";
writeln!(stderr, "error: {}", e).expect(errmsg);
for e in e.iter().skip(1) {
writeln!(stderr, "caused by: {}", e).expect(errmsg);
}
// The backtrace is not always generated. Try to run this example
// with `RUST_BACKTRACE=1`.
if let Some(backtrace) = e.backtrace() {
writeln!(stderr, "backtrace: {:?}", backtrace).expect(errmsg);
}
::std::process::exit(1);
}
}
// The above main gives you maximum control over how the error is
// formatted. If you don't care (i.e. you want to display the full
// error during an assert) you can just call the `display_chain` method
// on the error object
#[allow(dead_code)]
fn alternative_main() {
if let Err(ref e) = run() {
use std::io::Write;
let stderr = &mut ::std::io::stderr();
let errmsg = "Error writing to stderr";
writeln!(stderr, "{}", e.display_chain()).expect(errmsg);
::std::process::exit(1);
}
}
// Use this macro to auto-generate the main above. You may want to
// set the `RUST_BACKTRACE` env variable to see a backtrace.
// quick_main!(run);
// Most functions will return the `Result` type, imported from the
// `errors` module. It is a typedef of the standard `Result` type
// for which the error type is always our own `Error`.
fn run() -> Result<()> {
use std::fs::File;
// This operation will fail
File::open("tretrete")
.chain_err(|| "unable to open tretrete file")?;
Ok(())
}
|
main
|
JavaLib.py
|
"""Main library."""
from typing import Optional
# Import module
import jpype
# Enable Java imports
import jpype.imports
# Pull in types
from jpype.types import *
import importlib
class JavaLib:
ROBOT_LIBRARY_SCOPE = "GLOBAL"
"""General library documentation."""
def __init__(
self,
library: str,
classpath: Optional[str] = None):
|
def get_keyword_names(self):
keywords = []
# AnnotationLibrary return Java's ArrayList with Java's Strings, converting to Python
for keyword in self.javaLibrary.getKeywordNames():
keywords.append(str(keyword))
return keywords
def run_keyword(self, keyword: str, args, kwargs):
import java
return self.javaLibrary.runKeyword(JString(keyword), java.util.ArrayList(args), java.util.HashMap(kwargs))
def get_keyword_documentation(self, keyword: str):
try:
# AnnotationLibrary returns java.lang.String
documentation = str(self.javaLibrary.getKeywordDocumentation(keyword))
except:
documentation = ""
return documentation
|
if jpype.isJVMStarted():
print("JVM running")
else:
jpype.startJVM(classpath=classpath.split(":"))
JavaLibrary = importlib.import_module(library)
self.javaLibrary = JavaLibrary()
|
errors.rs
|
// Copyright 2015-2019 Parity Technologies (UK) Ltd.
// This file is part of Parity Ethereum.
// Parity Ethereum is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity Ethereum is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity Ethereum. If not, see <http://www.gnu.org/licenses/>.
//! RPC Error codes and error objects
use std::fmt;
use jsonrpc_core::{futures, Result as RpcResult, Error, ErrorCode, Value};
use rlp::DecoderError;
use types::transaction::Error as TransactionError;
use ethcore_private_tx::Error as PrivateTransactionError;
use vm::Error as VMError;
use light::on_demand::error::{Error as OnDemandError};
use client_traits::BlockChainClient;
use types::{
ids::BlockId,
blockchain_info::BlockChainInfo,
errors::{EthcoreError},
transaction::CallError,
};
use v1::types::BlockNumber;
use v1::impls::EthClientOptions;
mod codes {
// NOTE [ToDr] Codes from [-32099, -32000]
pub const UNSUPPORTED_REQUEST: i64 = -32000;
pub const NO_WORK: i64 = -32001;
pub const NO_AUTHOR: i64 = -32002;
pub const NO_NEW_WORK: i64 = -32003;
pub const NO_WORK_REQUIRED: i64 = -32004;
pub const CANNOT_SUBMIT_WORK: i64 = -32005;
pub const CANNOT_SUBMIT_BLOCK: i64 = -32006;
pub const UNKNOWN_ERROR: i64 = -32009;
pub const TRANSACTION_ERROR: i64 = -32010;
pub const EXECUTION_ERROR: i64 = -32015;
pub const EXCEPTION_ERROR: i64 = -32016;
pub const DATABASE_ERROR: i64 = -32017;
#[cfg(any(test, feature = "accounts"))]
pub const ACCOUNT_LOCKED: i64 = -32020;
#[cfg(any(test, feature = "accounts"))]
pub const PASSWORD_INVALID: i64 = -32021;
pub const ACCOUNT_ERROR: i64 = -32023;
pub const PRIVATE_ERROR: i64 = -32024;
pub const REQUEST_REJECTED: i64 = -32040;
pub const REQUEST_REJECTED_LIMIT: i64 = -32041;
pub const REQUEST_NOT_FOUND: i64 = -32042;
pub const ENCRYPTION_ERROR: i64 = -32055;
pub const ENCODING_ERROR: i64 = -32058;
pub const FETCH_ERROR: i64 = -32060;
pub const NO_LIGHT_PEERS: i64 = -32065;
pub const NO_PEERS: i64 = -32066;
pub const DEPRECATED: i64 = -32070;
pub const EXPERIMENTAL_RPC: i64 = -32071;
pub const CANNOT_RESTART: i64 = -32080;
}
pub fn unimplemented(details: Option<String>) -> Error {
Error {
code: ErrorCode::ServerError(codes::UNSUPPORTED_REQUEST),
message: "This request is not implemented yet. Please create an issue on Github repo.".into(),
data: details.map(Value::String),
}
}
pub fn light_unimplemented(details: Option<String>) -> Error {
Error {
code: ErrorCode::ServerError(codes::UNSUPPORTED_REQUEST),
message: "This request is unsupported for light clients.".into(),
data: details.map(Value::String),
}
}
pub fn unsupported<T: Into<String>>(msg: T, details: Option<T>) -> Error {
Error {
code: ErrorCode::ServerError(codes::UNSUPPORTED_REQUEST),
message: msg.into(),
data: details.map(Into::into).map(Value::String),
}
}
pub fn request_not_found() -> Error {
Error {
code: ErrorCode::ServerError(codes::REQUEST_NOT_FOUND),
message: "Request not found.".into(),
data: None,
}
}
pub fn request_rejected() -> Error {
Error {
code: ErrorCode::ServerError(codes::REQUEST_REJECTED),
message: "Request has been rejected.".into(),
data: None,
}
}
pub fn request_rejected_limit() -> Error {
Error {
code: ErrorCode::ServerError(codes::REQUEST_REJECTED_LIMIT),
message: "Request has been rejected because of queue limit.".into(),
data: None,
}
}
pub fn request_rejected_param_limit(limit: u64, items_desc: &str) -> Error {
Error {
code: ErrorCode::ServerError(codes::REQUEST_REJECTED_LIMIT),
message: format!("Requested data size exceeds limit of {} {}.", limit, items_desc),
data: None,
}
}
pub fn account<T: fmt::Debug>(error: &str, details: T) -> Error {
Error {
code: ErrorCode::ServerError(codes::ACCOUNT_ERROR),
message: error.into(),
data: Some(Value::String(format!("{:?}", details))),
}
}
pub fn cannot_restart() -> Error {
Error {
code: ErrorCode::ServerError(codes::CANNOT_RESTART),
message: "Parity could not be restarted. This feature is disabled in development mode and if the binary name isn't parity.".into(),
data: None,
}
}
/// Internal error signifying a logic error in code.
/// Should not be used when function can just fail
/// because of invalid parameters or incomplete node state.
pub fn internal<T: fmt::Debug>(error: &str, data: T) -> Error {
Error {
code: ErrorCode::InternalError,
message: format!("Internal error occurred: {}", error),
data: Some(Value::String(format!("{:?}", data))),
}
}
pub fn invalid_params<T: fmt::Debug>(param: &str, details: T) -> Error {
Error {
code: ErrorCode::InvalidParams,
message: format!("Couldn't parse parameters: {}", param),
data: Some(Value::String(format!("{:?}", details))),
}
}
pub fn execution<T: fmt::Debug>(data: T) -> Error {
Error {
code: ErrorCode::ServerError(codes::EXECUTION_ERROR),
message: "Transaction execution error.".into(),
data: Some(Value::String(format!("{:?}", data))),
}
}
pub fn state_pruned() -> Error {
Error {
code: ErrorCode::ServerError(codes::UNSUPPORTED_REQUEST),
message: "This request is not supported because your node is running with state pruning. Run with --pruning=archive.".into(),
data: None,
}
}
pub fn state_corrupt() -> Error {
internal("State corrupt", "")
}
pub fn exceptional<T: fmt::Display>(data: T) -> Error {
Error {
code: ErrorCode::ServerError(codes::EXCEPTION_ERROR),
message: "The execution failed due to an exception.".into(),
data: Some(Value::String(data.to_string())),
}
}
pub fn no_work() -> Error {
Error {
code: ErrorCode::ServerError(codes::NO_WORK),
message: "Still syncing.".into(),
data: None,
}
}
pub fn no_new_work() -> Error {
Error {
code: ErrorCode::ServerError(codes::NO_NEW_WORK),
message: "Work has not changed.".into(),
data: None,
}
}
pub fn no_author() -> Error {
Error {
code: ErrorCode::ServerError(codes::NO_AUTHOR),
message: "Author not configured. Run Parity with --author to configure.".into(),
data: None,
}
}
pub fn no_work_required() -> Error {
Error {
code: ErrorCode::ServerError(codes::NO_WORK_REQUIRED),
message: "External work is only required for Proof of Work engines.".into(),
data: None,
}
}
pub fn cannot_submit_work(err: EthcoreError) -> Error {
Error {
code: ErrorCode::ServerError(codes::CANNOT_SUBMIT_WORK),
message: "Cannot submit work.".into(),
data: Some(Value::String(err.to_string())),
}
}
pub fn unavailable_block(no_ancient_block: bool, by_hash: bool) -> Error {
if no_ancient_block {
Error {
code: ErrorCode::ServerError(codes::UNSUPPORTED_REQUEST),
message: "Looks like you disabled ancient block download, unfortunately the information you're \
trying to fetch doesn't exist in the db and is probably in the ancient blocks.".into(),
data: None,
}
} else if by_hash {
Error {
code: ErrorCode::ServerError(codes::UNSUPPORTED_REQUEST),
message: "Block information is incomplete while ancient block sync is still in progress, before \
it's finished we can't determine the existence of requested item.".into(),
data: None,
}
} else {
Error {
code: ErrorCode::ServerError(codes::UNSUPPORTED_REQUEST),
message: "Requested block number is in a range that is not available yet, because the ancient block sync is still in progress.".into(),
data: None,
}
}
}
pub fn cannot_submit_block(err: EthcoreError) -> Error {
Error {
code: ErrorCode::ServerError(codes::CANNOT_SUBMIT_BLOCK),
message: "Cannot submit block.".into(),
data: Some(Value::String(err.to_string())),
}
}
pub fn check_block_number_existence<'a, T, C>(
client: &'a C,
num: BlockNumber,
options: EthClientOptions,
) ->
impl Fn(Option<T>) -> RpcResult<Option<T>> + 'a
where C: BlockChainClient,
{
move |response| {
if response.is_none() {
if let BlockNumber::Num(block_number) = num {
// tried to fetch block number and got nothing even though the block number is
// less than the latest block number
if block_number < client.chain_info().best_block_number && !options.allow_missing_blocks {
return Err(unavailable_block(options.no_ancient_blocks, false));
}
}
}
Ok(response)
}
}
pub fn check_block_gap<'a, T, C>(
client: &'a C,
options: EthClientOptions,
) -> impl Fn(Option<T>) -> RpcResult<Option<T>> + 'a
where C: BlockChainClient,
{
move |response| {
if response.is_none() && !options.allow_missing_blocks {
let BlockChainInfo { ancient_block_hash, .. } = client.chain_info();
// block information was requested, but unfortunately we couldn't find it and there
// are gaps in the database ethcore/src/blockchain/blockchain.rs
if ancient_block_hash.is_some() {
return Err(unavailable_block(options.no_ancient_blocks, true))
}
}
Ok(response)
}
}
pub fn not_enough_data() -> Error {
Error {
code: ErrorCode::ServerError(codes::UNSUPPORTED_REQUEST),
message: "The node does not have enough data to compute the given statistic.".into(),
data: None,
}
}
pub fn token(e: String) -> Error {
Error {
code: ErrorCode::ServerError(codes::UNKNOWN_ERROR),
message: "There was an error when saving your authorization tokens.".into(),
data: Some(Value::String(e)),
}
}
pub fn signer_disabled() -> Error {
Error {
code: ErrorCode::ServerError(codes::UNSUPPORTED_REQUEST),
message: "Trusted Signer is disabled. This API is not available.".into(),
data: None,
}
}
pub fn ws_disabled() -> Error {
Error {
code: ErrorCode::ServerError(codes::UNSUPPORTED_REQUEST),
message: "WebSockets Server is disabled. This API is not available.".into(),
data: None,
}
}
pub fn network_disabled() -> Error {
Error {
code: ErrorCode::ServerError(codes::UNSUPPORTED_REQUEST),
message: "Network is disabled or not yet up.".into(),
data: None,
}
}
pub fn encryption<T: fmt::Debug>(error: T) -> Error {
Error {
code: ErrorCode::ServerError(codes::ENCRYPTION_ERROR),
message: "Encryption error.".into(),
data: Some(Value::String(format!("{:?}", error))),
}
}
pub fn encoding<T: fmt::Debug>(error: T) -> Error {
Error {
code: ErrorCode::ServerError(codes::ENCODING_ERROR),
message: "Encoding error.".into(),
data: Some(Value::String(format!("{:?}", error))),
}
}
pub fn database<T: fmt::Debug>(error: T) -> Error {
Error {
code: ErrorCode::ServerError(codes::DATABASE_ERROR),
message: "Database error.".into(),
data: Some(Value::String(format!("{:?}", error))),
}
}
pub fn fetch<T: fmt::Debug>(error: T) -> Error {
Error {
code: ErrorCode::ServerError(codes::FETCH_ERROR),
message: "Error while fetching content.".into(),
data: Some(Value::String(format!("{:?}", error))),
}
}
#[cfg(any(test, feature = "accounts"))]
pub fn invalid_call_data<T: fmt::Display>(error: T) -> Error {
Error {
code: ErrorCode::ServerError(codes::ENCODING_ERROR),
message: format!("{}", error),
data: None
}
}
#[cfg(any(test, feature = "accounts"))]
pub fn signing(error: ::accounts::SignError) -> Error {
Error {
code: ErrorCode::ServerError(codes::ACCOUNT_LOCKED),
message: "Your account is locked. Unlock the account via CLI, personal_unlockAccount or use Trusted Signer.".into(),
data: Some(Value::String(format!("{:?}", error))),
}
}
#[cfg(any(test, feature = "accounts"))]
pub fn password(error: ::accounts::SignError) -> Error {
Error {
code: ErrorCode::ServerError(codes::PASSWORD_INVALID),
message: "Account password is invalid or account does not exist.".into(),
data: Some(Value::String(format!("{:?}", error))),
}
}
pub fn private_message(error: PrivateTransactionError) -> Error {
Error {
code: ErrorCode::ServerError(codes::PRIVATE_ERROR),
message: "Private transactions call failed.".into(),
data: Some(Value::String(format!("{:?}", error))),
}
}
pub fn private_message_block_id_not_supported() -> Error {
Error {
code: ErrorCode::ServerError(codes::PRIVATE_ERROR),
message: "Pending block id not supported.".into(),
data: None,
}
}
pub fn transaction_message(error: &TransactionError) -> String {
use self::TransactionError::*;
match *error {
AlreadyImported => "Transaction with the same hash was already imported.".into(),
Old => "Transaction nonce is too low. Try incrementing the nonce.".into(),
TooCheapToReplace { prev, new } => {
format!("Transaction gas price {} is too low. There is another transaction with same nonce in the queue{}. Try increasing the gas price or incrementing the nonce.",
new.map(|gas| format!("{}wei", gas)).unwrap_or("supplied".into()),
prev.map(|gas| format!(" with gas price: {}wei", gas)).unwrap_or("".into())
)
}
LimitReached => {
"There are too many transactions in the queue. Your transaction was dropped due to limit. Try increasing the fee.".into()
}
InsufficientGas { minimal, got } => {
format!("Transaction gas is too low. There is not enough gas to cover minimal cost of the transaction (minimal: {}, got: {}). Try increasing supplied gas.", minimal, got)
}
InsufficientGasPrice { minimal, got } => {
format!("Transaction gas price is too low. It does not satisfy your node's minimal gas price (minimal: {}, got: {}). Try increasing the gas price.", minimal, got)
}
InsufficientBalance { balance, cost } => {
format!("Insufficient funds. The account you tried to send transaction from does not have enough funds. Required {} and got: {}.", cost, balance)
}
GasLimitExceeded { limit, got } => {
format!("Transaction cost exceeds current gas limit. Limit: {}, got: {}. Try decreasing supplied gas.", limit, got)
}
InvalidSignature(ref sig) => format!("Invalid signature: {}", sig),
InvalidChainId => "Invalid chain id.".into(),
InvalidGasLimit(_) => "Supplied gas is beyond limit.".into(),
SenderBanned => "Sender is banned in local queue.".into(),
RecipientBanned => "Recipient is banned in local queue.".into(),
CodeBanned => "Code is banned in local queue.".into(),
NotAllowed => "Transaction is not permitted.".into(),
TooBig => "Transaction is too big, see chain specification for the limit.".into(),
InvalidRlp(ref descr) => format!("Invalid RLP data: {}", descr),
}
}
pub fn transaction<T: Into<EthcoreError>>(error: T) -> Error {
let error = error.into();
if let EthcoreError::Transaction(ref e) = error {
Error {
code: ErrorCode::ServerError(codes::TRANSACTION_ERROR),
message: transaction_message(e),
data: None,
}
} else {
Error {
code: ErrorCode::ServerError(codes::UNKNOWN_ERROR),
message: "Unknown error when sending transaction.".into(),
data: Some(Value::String(format!("{:?}", error))),
}
}
}
pub fn
|
<T: Into<EthcoreError>>(error: T) -> Error {
match error.into() {
EthcoreError::Decoder(ref dec_err) => rlp(dec_err.clone()),
_ => Error {
code: ErrorCode::InternalError,
message: "decoding error".into(),
data: None,
}
}
}
pub fn rlp(error: DecoderError) -> Error {
Error {
code: ErrorCode::InvalidParams,
message: "Invalid RLP.".into(),
data: Some(Value::String(format!("{:?}", error))),
}
}
pub fn call(error: CallError) -> Error {
match error {
CallError::StatePruned => state_pruned(),
CallError::StateCorrupt => state_corrupt(),
CallError::Exceptional(e) => exceptional(e),
CallError::Execution(e) => execution(e),
CallError::TransactionNotFound => internal("{}, this should not be the case with eth_call, most likely a bug.", CallError::TransactionNotFound),
}
}
pub fn vm(error: &VMError, output: &[u8]) -> Error {
use rustc_hex::ToHex;
let data = match error {
&VMError::Reverted => format!("{} 0x{}", VMError::Reverted, output.to_hex()),
error => format!("{}", error),
};
Error {
code: ErrorCode::ServerError(codes::EXECUTION_ERROR),
message: "VM execution error.".into(),
data: Some(Value::String(data)),
}
}
pub fn unknown_block() -> Error {
Error {
code: ErrorCode::InvalidParams,
message: "Unknown block number".into(),
data: None,
}
}
pub fn no_light_peers() -> Error {
Error {
code: ErrorCode::ServerError(codes::NO_LIGHT_PEERS),
message: "No light peers who can serve data".into(),
data: None,
}
}
pub fn deprecated<S: Into<String>, T: Into<Option<S>>>(message: T) -> Error {
Error {
code: ErrorCode::ServerError(codes::DEPRECATED),
message: "Method deprecated".into(),
data: message.into().map(Into::into).map(Value::String),
}
}
pub fn filter_not_found() -> Error {
Error {
code: ErrorCode::ServerError(codes::UNSUPPORTED_REQUEST),
message: "Filter not found".into(),
data: None,
}
}
pub fn filter_block_not_found(id: BlockId) -> Error {
Error {
code: ErrorCode::ServerError(codes::UNSUPPORTED_REQUEST), // Specified in EIP-234.
message: "One of the blocks specified in filter (fromBlock, toBlock or blockHash) cannot be found".into(),
data: Some(Value::String(match id {
BlockId::Hash(hash) => format!("0x{:x}", hash),
BlockId::Number(number) => format!("0x{:x}", number),
BlockId::Earliest => "earliest".to_string(),
BlockId::Latest => "latest".to_string(),
})),
}
}
pub fn on_demand_error(err: OnDemandError) -> Error {
match err {
OnDemandError::ChannelCanceled(e) => on_demand_cancel(e),
OnDemandError::RequestLimit => timeout_new_peer(&err),
OnDemandError::BadResponse(_) => max_attempts_reached(&err),
}
}
// on-demand sender cancelled.
pub fn on_demand_cancel(_cancel: futures::sync::oneshot::Canceled) -> Error {
internal("on-demand sender cancelled", "")
}
pub fn max_attempts_reached(err: &OnDemandError) -> Error {
Error {
code: ErrorCode::ServerError(codes::REQUEST_NOT_FOUND),
message: err.to_string(),
data: None,
}
}
pub fn timeout_new_peer(err: &OnDemandError) -> Error {
Error {
code: ErrorCode::ServerError(codes::NO_LIGHT_PEERS),
message: err.to_string(),
data: None,
}
}
pub fn status_error(has_peers: bool) -> Error {
if has_peers {
no_work()
} else {
Error {
code: ErrorCode::ServerError(codes::NO_PEERS),
message: "Node is not connected to any peers.".into(),
data: None,
}
}
}
/// Returns a descriptive error in case experimental RPCs are not enabled.
pub fn require_experimental(allow_experimental_rpcs: bool, eip: &str) -> Result<(), Error> {
if allow_experimental_rpcs {
Ok(())
} else {
Err(Error {
code: ErrorCode::ServerError(codes::EXPERIMENTAL_RPC),
message: format!("This method is not part of the official RPC API yet (EIP-{}). Run with `--jsonrpc-experimental` to enable it.", eip),
data: Some(Value::String(format!("See EIP: https://eips.ethereum.org/EIPS/eip-{}", eip))),
})
}
}
/// returns an error for when require_canonical was specified and
pub fn invalid_input() -> Error {
Error {
// UNSUPPORTED_REQUEST shares the same error code for EIP-1898
code: ErrorCode::ServerError(codes::UNSUPPORTED_REQUEST),
message: "Invalid input".into(),
data: None
}
}
|
decode
|
sql.py
|
"""
SQL composition utility module
"""
# Copyright (C) 2020-2021 The Psycopg Team
import codecs
import string
from abc import ABC, abstractmethod
from typing import Any, Iterator, List, Optional, Sequence, Union
from .pq import Escaping
from .abc import AdaptContext
from .adapt import Transformer, PyFormat
from ._encodings import pgconn_encoding
def quote(obj: Any, context: Optional[AdaptContext] = None) -> str:
"""
Adapt a Python object to a quoted SQL string.
Use this function only if you absolutely want to convert a Python string to
an SQL quoted literal to use e.g. to generate batch SQL and you won't have
a connection avaliable when you will need to use it.
This function is relatively inefficient, because it doesn't cache the
adaptation rules. If you pass a *context* you can adapt the adaptation
rules used, otherwise only global rules are used.
"""
return Literal(obj).as_string(context)
class Composable(ABC):
"""
Abstract base class for objects that can be used to compose an SQL string.
`!Composable` objects can be passed directly to
`~psycopg.Cursor.execute()`, `~psycopg.Cursor.executemany()`,
`~psycopg.Cursor.copy()` in place of the query string.
`!Composable` objects can be joined using the ``+`` operator: the result
will be a `Composed` instance containing the objects joined. The operator
``*`` is also supported with an integer argument: the result is a
`!Composed` instance containing the left argument repeated as many times as
requested.
"""
def __init__(self, obj: Any):
self._obj = obj
def __repr__(self) -> str:
return f"{self.__class__.__name__}({self._obj!r})"
@abstractmethod
def as_bytes(self, context: Optional[AdaptContext]) -> bytes:
"""
Return the value of the object as bytes.
:param context: the context to evaluate the object into.
:type context: `connection` or `cursor`
The method is automatically invoked by `~psycopg.Cursor.execute()`,
`~psycopg.Cursor.executemany()`, `~psycopg.Cursor.copy()` if a
`!Composable` is passed instead of the query string.
"""
raise NotImplementedError
def as_string(self, context: Optional[AdaptContext]) -> str:
"""
Return the value of the object as string.
:param context: the context to evaluate the string into.
:type context: `connection` or `cursor`
"""
conn = context.connection if context else None
enc = pgconn_encoding(conn.pgconn) if conn else "utf-8"
b = self.as_bytes(context)
if isinstance(b, bytes):
return b.decode(enc)
else:
# buffer object
return codecs.lookup(enc).decode(b)[0]
def __add__(self, other: "Composable") -> "Composed":
if isinstance(other, Composed):
return Composed([self]) + other
if isinstance(other, Composable):
return Composed([self]) + Composed([other])
else:
return NotImplemented
def __mul__(self, n: int) -> "Composed":
return Composed([self] * n)
def __eq__(self, other: Any) -> bool:
return type(self) is type(other) and self._obj == other._obj
def __ne__(self, other: Any) -> bool:
return not self.__eq__(other)
class Composed(Composable):
"""
A `Composable` object made of a sequence of `!Composable`.
The object is usually created using `!Composable` operators and methods.
However it is possible to create a `!Composed` directly specifying a
sequence of objects as arguments: if they are not `!Composable` they will
be wrapped in a `Literal`.
Example::
>>> comp = sql.Composed(
... [sql.SQL("INSERT INTO "), sql.Identifier("table")])
>>> print(comp.as_string(conn))
INSERT INTO "table"
`!Composed` objects are iterable (so they can be used in `SQL.join` for
instance).
"""
_obj: List[Composable]
def __init__(self, seq: Sequence[Any]):
seq = [
obj if isinstance(obj, Composable) else Literal(obj) for obj in seq
]
super().__init__(seq)
def as_bytes(self, context: Optional[AdaptContext]) -> bytes:
return b"".join(obj.as_bytes(context) for obj in self._obj)
def __iter__(self) -> Iterator[Composable]:
return iter(self._obj)
def __add__(self, other: Composable) -> "Composed":
if isinstance(other, Composed):
return Composed(self._obj + other._obj)
if isinstance(other, Composable):
return Composed(self._obj + [other])
else:
return NotImplemented
def join(self, joiner: Union["SQL", str]) -> "Composed":
"""
Return a new `!Composed` interposing the *joiner* with the `!Composed` items.
The *joiner* must be a `SQL` or a string which will be interpreted as
an `SQL`.
Example::
>>> fields = sql.Identifier('foo') + sql.Identifier('bar') # a Composed
>>> print(fields.join(', ').as_string(conn))
"foo", "bar"
"""
if isinstance(joiner, str):
joiner = SQL(joiner)
elif not isinstance(joiner, SQL):
raise TypeError(
f"Composed.join() argument must be strings or SQL,"
f" got {joiner!r} instead"
)
return joiner.join(self._obj)
class SQL(Composable):
"""
A `Composable` representing a snippet of SQL statement.
`!SQL` exposes `join()` and `format()` methods useful to create a template
where to merge variable parts of a query (for instance field or table
names).
The *string* doesn't undergo any form of escaping, so it is not suitable to
represent variable identifiers or values: you should only use it to pass
constant strings representing templates or snippets of SQL statements; use
other objects such as `Identifier` or `Literal` to represent variable
parts.
Example::
>>> query = sql.SQL("SELECT {0} FROM {1}").format(
... sql.SQL(', ').join([sql.Identifier('foo'), sql.Identifier('bar')]),
... sql.Identifier('table'))
>>> print(query.as_string(conn))
SELECT "foo", "bar" FROM "table"
"""
_obj: str
_formatter = string.Formatter()
def __init__(self, obj: str):
super().__init__(obj)
if not isinstance(obj, str):
raise TypeError(f"SQL values must be strings, got {obj!r} instead")
def as_string(self, context: Optional[AdaptContext]) -> str:
return self._obj
def as_bytes(self, context: Optional[AdaptContext]) -> bytes:
enc = "utf-8"
if context:
conn = context.connection
if conn:
enc = pgconn_encoding(conn.pgconn)
return self._obj.encode(enc)
def format(self, *args: Any, **kwargs: Any) -> Composed:
"""
Merge `Composable` objects into a template.
:param args: parameters to replace to numbered (``{0}``, ``{1}``) or
auto-numbered (``{}``) placeholders
:param kwargs: parameters to replace to named (``{name}``) placeholders
:return: the union of the `!SQL` string with placeholders replaced
:rtype: `Composed`
The method is similar to the Python `str.format()` method: the string
template supports auto-numbered (``{}``), numbered (``{0}``,
``{1}``...), and named placeholders (``{name}``), with positional
arguments replacing the numbered placeholders and keywords replacing
the named ones. However placeholder modifiers (``{0!r}``, ``{0:<10}``)
are not supported.
If a `!Composable` objects is passed to the template it will be merged
according to its `as_string()` method. If any other Python object is
passed, it will be wrapped in a `Literal` object and so escaped
according to SQL rules.
Example::
>>> print(sql.SQL("SELECT * FROM {} WHERE {} = %s")
... .format(sql.Identifier('people'), sql.Identifier('id'))
... .as_string(conn))
SELECT * FROM "people" WHERE "id" = %s
>>> print(sql.SQL("SELECT * FROM {tbl} WHERE name = {name}")
... .format(tbl=sql.Identifier('people'), name="O'Rourke"))
... .as_string(conn))
SELECT * FROM "people" WHERE name = 'O''Rourke'
"""
rv: List[Composable] = []
autonum: Optional[int] = 0
for pre, name, spec, conv in self._formatter.parse(self._obj):
if spec:
raise ValueError("no format specification supported by SQL")
if conv:
raise ValueError("no format conversion supported by SQL")
if pre:
rv.append(SQL(pre))
if name is None:
continue
if name.isdigit():
if autonum:
raise ValueError(
"cannot switch from automatic field numbering to manual"
)
rv.append(args[int(name)])
autonum = None
elif not name:
if autonum is None:
raise ValueError(
"cannot switch from manual field numbering to automatic"
)
rv.append(args[autonum])
autonum += 1
else:
rv.append(kwargs[name])
return Composed(rv)
def join(self, seq: Sequence[Composable]) -> Composed:
"""
Join a sequence of `Composable`.
:param seq: the elements to join.
:type seq: iterable of `!Composable`
Use the `!SQL` object's *string* to separate the elements in *seq*.
Note that `Composed` objects are iterable too, so they can be used as
argument for this method.
Example::
>>> snip = sql.SQL(', ').join(
... sql.Identifier(n) for n in ['foo', 'bar', 'baz'])
>>> print(snip.as_string(conn))
"foo", "bar", "baz"
"""
rv = []
it = iter(seq)
try:
rv.append(next(it))
|
for i in it:
rv.append(self)
rv.append(i)
return Composed(rv)
class Identifier(Composable):
"""
A `Composable` representing an SQL identifier or a dot-separated sequence.
Identifiers usually represent names of database objects, such as tables or
fields. PostgreSQL identifiers follow `different rules`__ than SQL string
literals for escaping (e.g. they use double quotes instead of single).
.. __: https://www.postgresql.org/docs/current/sql-syntax-lexical.html# \
SQL-SYNTAX-IDENTIFIERS
Example::
>>> t1 = sql.Identifier("foo")
>>> t2 = sql.Identifier("ba'r")
>>> t3 = sql.Identifier('ba"z')
>>> print(sql.SQL(', ').join([t1, t2, t3]).as_string(conn))
"foo", "ba'r", "ba""z"
Multiple strings can be passed to the object to represent a qualified name,
i.e. a dot-separated sequence of identifiers.
Example::
>>> query = sql.SQL("SELECT {} FROM {}").format(
... sql.Identifier("table", "field"),
... sql.Identifier("schema", "table"))
>>> print(query.as_string(conn))
SELECT "table"."field" FROM "schema"."table"
"""
_obj: Sequence[str]
def __init__(self, *strings: str):
# init super() now to make the __repr__ not explode in case of error
super().__init__(strings)
if not strings:
raise TypeError("Identifier cannot be empty")
for s in strings:
if not isinstance(s, str):
raise TypeError(
f"SQL identifier parts must be strings, got {s!r} instead"
)
def __repr__(self) -> str:
return f"{self.__class__.__name__}({', '.join(map(repr, self._obj))})"
def as_bytes(self, context: Optional[AdaptContext]) -> bytes:
conn = context.connection if context else None
if not conn:
raise ValueError("a connection is necessary for Identifier")
esc = Escaping(conn.pgconn)
enc = pgconn_encoding(conn.pgconn)
escs = [esc.escape_identifier(s.encode(enc)) for s in self._obj]
return b".".join(escs)
class Literal(Composable):
"""
A `Composable` representing an SQL value to include in a query.
Usually you will want to include placeholders in the query and pass values
as `~cursor.execute()` arguments. If however you really really need to
include a literal value in the query you can use this object.
The string returned by `!as_string()` follows the normal :ref:`adaptation
rules <types-adaptation>` for Python objects.
Example::
>>> s1 = sql.Literal("foo")
>>> s2 = sql.Literal("ba'r")
>>> s3 = sql.Literal(42)
>>> print(sql.SQL(', ').join([s1, s2, s3]).as_string(conn))
'foo', 'ba''r', 42
"""
def as_bytes(self, context: Optional[AdaptContext]) -> bytes:
tx = Transformer(context)
dumper = tx.get_dumper(self._obj, PyFormat.TEXT)
return dumper.quote(self._obj)
class Placeholder(Composable):
"""A `Composable` representing a placeholder for query parameters.
If the name is specified, generate a named placeholder (e.g. ``%(name)s``,
``%(name)b``), otherwise generate a positional placeholder (e.g. ``%s``,
``%b``).
The object is useful to generate SQL queries with a variable number of
arguments.
Examples::
>>> names = ['foo', 'bar', 'baz']
>>> q1 = sql.SQL("INSERT INTO my_table ({}) VALUES ({})").format(
... sql.SQL(', ').join(map(sql.Identifier, names)),
... sql.SQL(', ').join(sql.Placeholder() * len(names)))
>>> print(q1.as_string(conn))
INSERT INTO my_table ("foo", "bar", "baz") VALUES (%s, %s, %s)
>>> q2 = sql.SQL("INSERT INTO my_table ({}) VALUES ({})").format(
... sql.SQL(', ').join(map(sql.Identifier, names)),
... sql.SQL(', ').join(map(sql.Placeholder, names)))
>>> print(q2.as_string(conn))
INSERT INTO my_table ("foo", "bar", "baz") VALUES (%(foo)s, %(bar)s, %(baz)s)
"""
def __init__(self, name: str = "", format: PyFormat = PyFormat.AUTO):
super().__init__(name)
if not isinstance(name, str):
raise TypeError(f"expected string as name, got {name!r}")
if ")" in name:
raise ValueError(f"invalid name: {name!r}")
self._format = format
def __repr__(self) -> str:
parts = []
if self._obj:
parts.append(repr(self._obj))
if self._format != PyFormat.AUTO:
parts.append(f"format={PyFormat(self._format).name}")
return f"{self.__class__.__name__}({', '.join(parts)})"
def as_string(self, context: Optional[AdaptContext]) -> str:
code = self._format
return f"%({self._obj}){code}" if self._obj else f"%{code}"
def as_bytes(self, context: Optional[AdaptContext]) -> bytes:
conn = context.connection if context else None
enc = pgconn_encoding(conn.pgconn) if conn else "utf-8"
return self.as_string(context).encode(enc)
# Literals
NULL = SQL("NULL")
DEFAULT = SQL("DEFAULT")
|
except StopIteration:
pass
else:
|
interfaces.go
|
package types
import (
"fmt"
"time"
"github.com/livekit/protocol/auth"
"github.com/livekit/protocol/livekit"
"github.com/livekit/protocol/logger"
"github.com/pion/webrtc/v3"
"github.com/livekit/livekit-server/pkg/routing"
"github.com/livekit/livekit-server/pkg/sfu"
)
//go:generate go run github.com/maxbrunsfeld/counterfeiter/v6 -generate
//counterfeiter:generate . WebsocketClient
type WebsocketClient interface {
ReadMessage() (messageType int, p []byte, err error)
WriteMessage(messageType int, data []byte) error
WriteControl(messageType int, data []byte, deadline time.Time) error
}
type AddSubscriberParams struct {
AllTracks bool
TrackIDs []livekit.TrackID
}
type MigrateState int32
const (
MigrateStateInit MigrateState = iota
MigrateStateSync
MigrateStateComplete
)
func (m MigrateState) String() string {
switch m {
case MigrateStateInit:
return "MIGRATE_STATE_INIT"
case MigrateStateSync:
return "MIGRATE_STATE_SYNC"
case MigrateStateComplete:
return "MIGRATE_STATE_COMPLETE"
default:
return fmt.Sprintf("%d", int(m))
}
}
//counterfeiter:generate . Participant
type Participant interface {
ID() livekit.ParticipantID
Identity() livekit.ParticipantIdentity
ToProto() *livekit.ParticipantInfo
SetMetadata(metadata string)
GetPublishedTrack(sid livekit.TrackID) MediaTrack
GetPublishedTracks() []MediaTrack
GetDataTrack() DataTrack
AddSubscriber(op LocalParticipant, params AddSubscriberParams) (int, error)
RemoveSubscriber(op LocalParticipant, trackID livekit.TrackID, resume bool)
// permissions
Hidden() bool
IsRecorder() bool
Start()
Close(sendLeave bool) error
SubscriptionPermission() *livekit.SubscriptionPermission
// updates from remotes
UpdateSubscriptionPermission(subscriptionPermission *livekit.SubscriptionPermission, resolver func(participantID livekit.ParticipantID) LocalParticipant) error
UpdateVideoLayers(updateVideoLayers *livekit.UpdateVideoLayers) error
UpdateSubscribedQuality(nodeID livekit.NodeID, trackID livekit.TrackID, maxQuality livekit.VideoQuality) error
UpdateMediaLoss(nodeID livekit.NodeID, trackID livekit.TrackID, fractionalLoss uint32) error
DebugInfo() map[string]interface{}
}
//counterfeiter:generate . LocalParticipant
type LocalParticipant interface {
Participant
GetLogger() logger.Logger
ProtocolVersion() ProtocolVersion
ConnectedAt() time.Time
State() livekit.ParticipantInfo_State
IsReady() bool
SubscriberAsPrimary() bool
GetResponseSink() routing.MessageSink
SetResponseSink(sink routing.MessageSink)
// permissions
ClaimGrants() *auth.ClaimGrants
SetPermission(permission *livekit.ParticipantPermission)
CanPublish() bool
CanSubscribe() bool
CanPublishData() bool
AddICECandidate(candidate webrtc.ICECandidateInit, target livekit.SignalTarget) error
HandleOffer(sdp webrtc.SessionDescription) (answer webrtc.SessionDescription, err error)
AddTrack(req *livekit.AddTrackRequest)
SetTrackMuted(trackID livekit.TrackID, muted bool, fromAdmin bool)
SubscriberMediaEngine() *webrtc.MediaEngine
SubscriberPC() *webrtc.PeerConnection
HandleAnswer(sdp webrtc.SessionDescription) error
Negotiate()
ICERestart() error
AddSubscribedTrack(st SubscribedTrack)
RemoveSubscribedTrack(st SubscribedTrack)
UpdateSubscribedTrackSettings(trackID livekit.TrackID, settings *livekit.UpdateTrackSettings) error
// returns list of participant identities that the current participant is subscribed to
GetSubscribedParticipants() []livekit.ParticipantID
GetAudioLevel() (level uint8, active bool)
GetConnectionQuality() *livekit.ConnectionQualityInfo
// server sent messages
SendJoinResponse(info *livekit.Room, otherParticipants []*livekit.ParticipantInfo, iceServers []*livekit.ICEServer, region string) error
SendParticipantUpdate(participants []*livekit.ParticipantInfo) error
SendSpeakerUpdate(speakers []*livekit.SpeakerInfo) error
SendDataPacket(packet *livekit.DataPacket) error
SendRoomUpdate(room *livekit.Room) error
SendConnectionQualityUpdate(update *livekit.ConnectionQualityUpdate) error
SubscriptionPermissionUpdate(publisherID livekit.ParticipantID, trackID livekit.TrackID, allowed bool)
SendRefreshToken(token string) error
// callbacks
OnStateChange(func(p LocalParticipant, oldState livekit.ParticipantInfo_State))
// OnTrackPublished - remote added a track
OnTrackPublished(func(LocalParticipant, MediaTrack))
// OnTrackUpdated - one of its publishedTracks changed in status
OnTrackUpdated(callback func(LocalParticipant, MediaTrack))
OnMetadataUpdate(callback func(LocalParticipant))
OnClose(_callback func(LocalParticipant, map[livekit.TrackID]livekit.ParticipantID))
OnClaimsChanged(_callback func(LocalParticipant))
OnDataTrackPublished(callback func(LocalParticipant, DataTrack))
// session migration
SetMigrateState(s MigrateState)
MigrateState() MigrateState
SetMigrateInfo(mediaTracks []*livekit.TrackPublishedResponse, dataChannels []*livekit.DataChannelInfo)
SetPreviousAnswer(previous *webrtc.SessionDescription)
UpdateRTT(rtt uint32)
}
// Room is a container of participants, and can provide room-level actions
//counterfeiter:generate . Room
type Room interface {
Name() livekit.RoomName
ID() livekit.RoomID
UpdateSubscriptions(participant LocalParticipant, trackIDs []livekit.TrackID, participantTracks []*livekit.ParticipantTracks, subscribe bool) error
UpdateSubscriptionPermission(participant LocalParticipant, permissions *livekit.SubscriptionPermission) error
SyncState(participant LocalParticipant, state *livekit.SyncState) error
|
SimulateScenario(participant LocalParticipant, scenario *livekit.SimulateScenario) error
SetParticipantPermission(participant LocalParticipant, permission *livekit.ParticipantPermission) error
UpdateVideoLayers(participant Participant, updateVideoLayers *livekit.UpdateVideoLayers) error
}
// MediaTrack represents a media track
//counterfeiter:generate . MediaTrack
type MediaTrack interface {
ID() livekit.TrackID
Kind() livekit.TrackType
Name() string
Source() livekit.TrackSource
ToProto() *livekit.TrackInfo
PublisherID() livekit.ParticipantID
PublisherIdentity() livekit.ParticipantIdentity
IsMuted() bool
SetMuted(muted bool)
UpdateVideoLayers(layers []*livekit.VideoLayer)
IsSimulcast() bool
Receiver() sfu.TrackReceiver
// callbacks
AddOnClose(func())
// subscribers
AddSubscriber(participant LocalParticipant) error
RemoveSubscriber(participantID livekit.ParticipantID, resume bool)
IsSubscriber(subID livekit.ParticipantID) bool
RemoveAllSubscribers()
RevokeDisallowedSubscribers(allowedSubscriberIDs []livekit.ParticipantID) []livekit.ParticipantID
// returns quality information that's appropriate for width & height
GetQualityForDimension(width, height uint32) livekit.VideoQuality
NotifySubscriberNodeMaxQuality(nodeID livekit.NodeID, quality livekit.VideoQuality)
NotifySubscriberNodeMediaLoss(nodeID livekit.NodeID, fractionalLoss uint8)
}
//counterfeiter:generate . LocalMediaTrack
type LocalMediaTrack interface {
MediaTrack
SignalCid() string
SdpCid() string
GetAudioLevel() (level uint8, active bool)
GetConnectionScore() float32
SetRTT(rtt uint32)
}
// MediaTrack is the main interface representing a track published to the room
//counterfeiter:generate . SubscribedTrack
type SubscribedTrack interface {
OnBind(f func())
ID() livekit.TrackID
PublisherID() livekit.ParticipantID
PublisherIdentity() livekit.ParticipantIdentity
SubscriberID() livekit.ParticipantID
DownTrack() *sfu.DownTrack
MediaTrack() MediaTrack
IsMuted() bool
SetPublisherMuted(muted bool)
UpdateSubscriberSettings(settings *livekit.UpdateTrackSettings)
// selects appropriate video layer according to subscriber preferences
UpdateVideoLayer()
}
// DataTrack is the interface representing a data track published to the room
//counterfeiter:generate . DataTrack
type DataTrack interface {
TrackID() livekit.TrackID
Receiver() sfu.TrackReceiver
AddOnClose(func())
OnDataPacket(callback func(*livekit.DataPacket))
Kind() livekit.TrackType
}
| |
modify_db_instance_spec.go
|
package dds
//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.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
)
// ModifyDBInstanceSpec invokes the dds.ModifyDBInstanceSpec API synchronously
// api document: https://help.aliyun.com/api/dds/modifydbinstancespec.html
func (client *Client) ModifyDBInstanceSpec(request *ModifyDBInstanceSpecRequest) (response *ModifyDBInstanceSpecResponse, err error) {
response = CreateModifyDBInstanceSpecResponse()
err = client.DoAction(request, response)
return
}
// ModifyDBInstanceSpecWithChan invokes the dds.ModifyDBInstanceSpec API asynchronously
// api document: https://help.aliyun.com/api/dds/modifydbinstancespec.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) ModifyDBInstanceSpecWithChan(request *ModifyDBInstanceSpecRequest) (<-chan *ModifyDBInstanceSpecResponse, <-chan error) {
responseChan := make(chan *ModifyDBInstanceSpecResponse, 1)
errChan := make(chan error, 1)
err := client.AddAsyncTask(func() {
defer close(responseChan)
defer close(errChan)
response, err := client.ModifyDBInstanceSpec(request)
if err != nil {
errChan <- err
} else {
responseChan <- response
}
})
if err != nil {
errChan <- err
close(responseChan)
close(errChan)
}
return responseChan, errChan
}
// ModifyDBInstanceSpecWithCallback invokes the dds.ModifyDBInstanceSpec API asynchronously
// api document: https://help.aliyun.com/api/dds/modifydbinstancespec.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) ModifyDBInstanceSpecWithCallback(request *ModifyDBInstanceSpecRequest, callback func(response *ModifyDBInstanceSpecResponse, err error)) <-chan int {
result := make(chan int, 1)
err := client.AddAsyncTask(func() {
var response *ModifyDBInstanceSpecResponse
var err error
defer close(result)
response, err = client.ModifyDBInstanceSpec(request)
callback(response, err)
result <- 1
})
if err != nil {
defer close(result)
callback(nil, err)
result <- 0
}
return result
}
// ModifyDBInstanceSpecRequest is the request struct for api ModifyDBInstanceSpec
type ModifyDBInstanceSpecRequest struct {
*requests.RpcRequest
ResourceOwnerId requests.Integer `position:"Query" name:"ResourceOwnerId"`
DBInstanceStorage string `position:"Query" name:"DBInstanceStorage"`
ReadonlyReplicas string `position:"Query" name:"ReadonlyReplicas"`
CouponNo string `position:"Query" name:"CouponNo"`
ReplicationFactor string `position:"Query" name:"ReplicationFactor"`
SecurityToken string `position:"Query" name:"SecurityToken"`
EffectiveTime string `position:"Query" name:"EffectiveTime"`
DBInstanceId string `position:"Query" name:"DBInstanceId"`
BusinessInfo string `position:"Query" name:"BusinessInfo"`
AutoPay requests.Boolean `position:"Query" name:"AutoPay"`
FromApp string `position:"Query" name:"FromApp"`
ResourceOwnerAccount string `position:"Query" name:"ResourceOwnerAccount"`
OwnerAccount string `position:"Query" name:"OwnerAccount"`
OwnerId requests.Integer `position:"Query" name:"OwnerId"`
DBInstanceClass string `position:"Query" name:"DBInstanceClass"`
OrderType string `position:"Query" name:"OrderType"`
}
// ModifyDBInstanceSpecResponse is the response struct for api ModifyDBInstanceSpec
type ModifyDBInstanceSpecResponse struct {
*responses.BaseResponse
RequestId string `json:"RequestId" xml:"RequestId"`
OrderId string `json:"OrderId" xml:"OrderId"`
}
// CreateModifyDBInstanceSpecRequest creates a request to invoke ModifyDBInstanceSpec API
func CreateModifyDBInstanceSpecRequest() (request *ModifyDBInstanceSpecRequest) {
request = &ModifyDBInstanceSpecRequest{
RpcRequest: &requests.RpcRequest{},
}
request.InitWithApiInfo("Dds", "2015-12-01", "ModifyDBInstanceSpec", "Dds", "openAPI")
request.Method = requests.POST
return
}
// CreateModifyDBInstanceSpecResponse creates a response to parse from ModifyDBInstanceSpec response
func CreateModifyDBInstanceSpecResponse() (response *ModifyDBInstanceSpecResponse)
|
{
response = &ModifyDBInstanceSpecResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}
|
|
base_input_feed.py
|
import abc
import typing
class BaseInputFeed(abc.ABC):
"""
"""
def __init__(self, model, batch_size):
self.model = model
self.batch_size = batch_size
@abc.abstractmethod
def get_train_batch(self):
"""Defien a batch feed dictionary the model needs for training, each sub class should
implement this method."""
@abc.abstractmethod
|
"""Defien a batch feed dictionary the model needs for testing, each sub class should
implement this method."""
|
def get_test_batch(self):
|
pyunit_https_import.py
|
import sys
sys.path.insert(1, "../../")
import h2o
def
|
(ip,port):
url = "https://s3.amazonaws.com/h2o-public-test-data/smalldata/prostate/prostate.csv.zip"
aa = h2o.import_file(path=url)
aa.show()
if __name__ == "__main__":
h2o.run_test(sys.argv, https_import)
|
https_import
|
packaging_test.py
|
# Copyright 2019 The Bazel 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
|
# 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.
"""Test that the rules_pkg distribution is usable."""
import os
import subprocess
import unittest
from bazel_tools.tools.python.runfiles import runfiles
from releasing import release_tools
from distro import release_version
_VERBOSE = True
class PackagingTest(unittest.TestCase):
"""Test the distribution packaging."""
def setUp(self):
self.data_files = runfiles.Create()
self.repo = 'rules_pkg'
self.version = release_version.RELEASE_VERSION
def testBuild(self):
# Set up a fresh Bazel workspace using the currently build repo.
tempdir = os.path.join(os.environ['TEST_TMPDIR'], 'build')
if not os.path.exists(tempdir):
os.makedirs(tempdir)
with open(os.path.join(tempdir, 'WORKSPACE'), 'w') as workspace:
file_name = release_tools.package_basename(self.repo, self.version)
local_path = runfiles.Create().Rlocation(
os.path.join('rules_pkg', 'distro', file_name))
sha256 = release_tools.get_package_sha256(local_path)
workspace_content = '\n'.join((
'workspace(name = "test_rules_pkg_packaging")',
release_tools.workspace_content(
'file://%s' % local_path, self.repo, sha256,
deps_method='rules_pkg_dependencies'
)
))
workspace.write(workspace_content)
if _VERBOSE:
print('=== WORKSPACE ===')
print(workspace_content)
# We do a little dance of renaming *.tmpl to *, mostly so that we do not
# have a BUILD file in testdata, which would create a package boundary.
def CopyTestFile(source_name, dest_name):
source_path = self.data_files.Rlocation(
os.path.join('rules_pkg', 'distro', 'testdata', source_name))
with open(source_path) as inp:
with open(os.path.join(tempdir, dest_name), 'w') as out:
content = inp.read()
out.write(content)
CopyTestFile('BUILD.tmpl', 'BUILD')
os.chdir(tempdir)
build_result = subprocess.check_output(['bazel', 'build', ':dummy_tar'])
if _VERBOSE:
print('=== Build Result ===')
print(build_result)
# TODO(aiuto): Find tar in a disciplined way
content = subprocess.check_output(
['tar', 'tzf', 'bazel-bin/dummy_tar.tar.gz'])
self.assertEqual(b'./\n./BUILD\n', content)
if __name__ == '__main__':
unittest.main()
|
#
# Unless required by applicable law or agreed to in writing, software
|
rest.ts
|
import { RestClient } from "../src/rest-client";
/*
|
(async () => {
// Optional, but required for private endpoints
const key = 'apiKeyHere';
const secret = 'apiSecretHere';
const client = new RestClient(key, secret);
// Try some public API calls
try {
console.log('getBalances: ', await client.getBalances());
console.log('getSubaccountBalances: ', await client.getSubaccountBalances('sub1'));
console.log('getMarkets: ', await client.getMarket('ABNB-0326'));
} catch (e) {
console.error('public get method failed: ', e);
}
// Try some authenticated API calls
const market = 'BTC/USD';
try {
console.log('buysome: ', await client.placeOrder({
market,
side: 'buy',
type: 'market',
size: 0.001,
price: null
}));
} catch (e) {
console.error('buy failed: ', e);
}
try {
console.log('sellsome: ', await client.placeOrder({
market,
side: 'sell',
type: 'market',
size: 0.001,
price: null
}));
} catch (e) {
console.error('sell failed: ', e);
}
// Nothing left - close the process
process.exit();
})();
|
Demonstrations on basic REST API calls
*/
|
App.js
|
import Navbar from './components/Navbar';
import './App.css';
import { BrowserRouter as Router, Switch, Route, Redirect } from 'react-router-dom';
import axios from 'axios';
import useAuth from './hooks/auth';
import Home from './pages/Home';
import Signup from './pages/Signup';
import Login from './pages/Login';
function
|
() {
// Pull auth token from storage, in case you refresh the page
const { getToken, logout } = useAuth();
axios.defaults.headers.common.Authorization = `Bearer ${getToken()}`;
// A nice trick that if we EVER get back a 401, will pop the token off
axios.interceptors.response.use(response => {
// Any status code that lie within the range of 2xx cause this function to trigger
// Do something with response data
return response;
}, error => {
const { message } = error.toJSON();
// If we had time, we could write our own custom method to the auth middleware
// However, we are just gonna use their message.
if(message === 'Request failed with status code 401'){
logout();
}
// Any status codes that falls outside the range of 2xx cause this function to trigger
// Do something with response error
return Promise.reject(error);
});
return (
<Router>
<Navbar />
<Switch>
<Route exact path='/'>
<Home />
</Route>
<Route path='/signup'>
<Signup />
</Route>
<Route path='/login'>
<Login />
</Route>
</Switch>
</Router>
);
}
// Yanked straight from the react-router docs for redirects
function PrivateRoute({ children, ...rest }) {
const { isLoggedIn } = useAuth();
return (
<Route
{...rest}
render={({ location }) =>
isLoggedIn() ? (
children
) :
(
<Redirect
to={{
pathname: '/login',
state: { from: location }
}}
/>
)
}
/>
);
}
export default App;
|
App
|
optimize.go
|
// Copyright The ezgliding 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.
//
package igc
// Score functions calculate a score for the given Task.
//
// The main use of these functions is in passing them to the Optimizers, so
// they can evaluate each Task towards different goals.
//
// Example functions include the total distance between all turn points or an
// online competition (netcoupe, online contest) score which takes additional
// metrics of each leg into account.
type Score func(task Task) float64
// Distance returns the sum of distances between each of the points in the Task.
//
// The sum is made calculating the distances between each two consecutive Points.
func Distance(task Task) float64
|
// Optimizer returns an optimal Task for the given turnpoints and Score function.
//
// Available score functions include MaxDistance and MaxPoints, but it is
// possible to pass the Optimizer a custom function.
//
// Optimizers might not support a high number of turnpoints. As an example, the
// BruteForceOptimizer does not perform well with nPoints > 2, and might decide
// to return an error instead of attempting to finalize the optimization
// indefinitely.
type Optimizer interface {
Optimize(track Track, nPoints int, score Score) (Task, error)
}
|
{
return task.Distance()
}
|
manager.py
|
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# 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.
"""
Volume manager manages creating, attaching, detaching, and persistent storage.
Persistent storage volumes keep their state independent of instances. You can
attach to an instance, terminate the instance, spawn a new instance (even
one from a different image) and re-attach the volume with the same data
intact.
**Related Flags**
:volume_manager: The module name of a class derived from
:class:`manager.Manager` (default:
:class:`cinder.volume.manager.Manager`).
:volume_driver: Used by :class:`Manager`. Defaults to
:class:`cinder.volume.drivers.lvm.LVMVolumeDriver`.
:volume_group: Name of the group that will contain exported volumes (default:
`cinder-volumes`)
:num_shell_tries: Number of times to attempt to run commands (default: 3)
"""
import requests
import time
from castellan import key_manager
from oslo_config import cfg
from oslo_log import log as logging
import oslo_messaging as messaging
from oslo_serialization import jsonutils
from oslo_service import periodic_task
from oslo_utils import excutils
from oslo_utils import importutils
from oslo_utils import timeutils
from oslo_utils import units
from oslo_utils import uuidutils
profiler = importutils.try_import('osprofiler.profiler')
import six
from taskflow import exceptions as tfe
from cinder.backup import rpcapi as backup_rpcapi
from cinder.common import constants
from cinder import compute
from cinder import context
from cinder import coordination
from cinder import db
from cinder import exception
from cinder import flow_utils
from cinder.i18n import _
from cinder.image import cache as image_cache
from cinder.image import glance
from cinder.image import image_utils
from cinder.keymgr import migration as key_migration
from cinder import manager
from cinder.message import api as message_api
from cinder.message import message_field
from cinder import objects
from cinder.objects import cgsnapshot
from cinder.objects import consistencygroup
from cinder.objects import fields
from cinder import quota
from cinder import utils
from cinder import volume as cinder_volume
from cinder.volume import configuration as config
from cinder.volume.flows.manager import create_volume
from cinder.volume.flows.manager import manage_existing
from cinder.volume.flows.manager import manage_existing_snapshot
from cinder.volume import group_types
from cinder.volume import rpcapi as volume_rpcapi
from cinder.volume import volume_migration
from cinder.volume import volume_types
from cinder.volume import volume_utils
LOG = logging.getLogger(__name__)
QUOTAS = quota.QUOTAS
GROUP_QUOTAS = quota.GROUP_QUOTAS
VALID_REMOVE_VOL_FROM_GROUP_STATUS = (
'available',
'in-use',
'error',
'error_deleting')
VALID_ADD_VOL_TO_GROUP_STATUS = (
'available',
'in-use')
VALID_CREATE_GROUP_SRC_SNAP_STATUS = (fields.SnapshotStatus.AVAILABLE,)
VALID_CREATE_GROUP_SRC_GROUP_STATUS = ('available',)
VA_LIST = objects.VolumeAttachmentList
volume_manager_opts = [
cfg.IntOpt('migration_create_volume_timeout_secs',
default=300,
help='Timeout for creating the volume to migrate to '
'when performing volume migration (seconds)'),
cfg.BoolOpt('volume_service_inithost_offload',
default=False,
help='Offload pending volume delete during '
'volume service startup'),
cfg.StrOpt('zoning_mode',
help="FC Zoning mode configured, only 'fabric' is "
"supported now."),
cfg.IntOpt('reinit_driver_count',
default=3,
help='Maximum times to reintialize the driver '
'if volume initialization fails. The interval of retry is '
'exponentially backoff, and will be 1s, 2s, 4s etc.'),
cfg.IntOpt('init_host_max_objects_retrieval',
default=0,
help='Max number of volumes and snapshots to be retrieved '
'per batch during volume manager host initialization. '
'Query results will be obtained in batches from the '
'database and not in one shot to avoid extreme memory '
'usage. Set 0 to turn off this functionality.'),
cfg.IntOpt('backend_stats_polling_interval',
default=60,
min=3,
help='Time in seconds between requests for usage statistics '
'from the backend. Be aware that generating usage '
'statistics is expensive for some backends, so setting '
'this value too low may adversely affect performance.'),
]
volume_backend_opts = [
cfg.StrOpt('volume_driver',
default='cinder.volume.drivers.lvm.LVMVolumeDriver',
help='Driver to use for volume creation'),
cfg.StrOpt('extra_capabilities',
default='{}',
help='User defined capabilities, a JSON formatted string '
'specifying key/value pairs. The key/value pairs can '
'be used by the CapabilitiesFilter to select between '
'backends when requests specify volume types. For '
'example, specifying a service level or the geographical '
'location of a backend, then creating a volume type to '
'allow the user to select by these different '
'properties.'),
cfg.BoolOpt('suppress_requests_ssl_warnings',
default=False,
help='Suppress requests library SSL certificate warnings.'),
cfg.IntOpt('backend_native_threads_pool_size',
default=20,
min=20,
help='Size of the native threads pool for the backend. '
'Increase for backends that heavily rely on this, like '
'the RBD driver.'),
]
CONF = cfg.CONF
CONF.register_opts(volume_manager_opts)
CONF.register_opts(volume_backend_opts, group=config.SHARED_CONF_GROUP)
# MAPPING is used for driver renames to keep backwards compatibilty. When a
# driver is renamed, add a mapping here from the old name (the dict key) to the
# new name (the dict value) for at least a cycle to allow time for deployments
# to transition.
MAPPING = {
'cinder.volume.drivers.dell_emc.vmax.iscsi.VMAXISCSIDriver':
'cinder.volume.drivers.dell_emc.powermax.iscsi.PowerMaxISCSIDriver',
'cinder.volume.drivers.dell_emc.vmax.fc.VMAXFCDriver':
'cinder.volume.drivers.dell_emc.powermax.fc.PowerMaxFCDriver',
'cinder.volume.drivers.fujitsu.eternus_dx_fc.FJDXFCDriver':
'cinder.volume.drivers.fujitsu.eternus_dx.eternus_dx_fc.FJDXFCDriver',
'cinder.volume.drivers.fujitsu.eternus_dx_iscsi.FJDXISCSIDriver':
'cinder.volume.drivers.fujitsu.eternus_dx.eternus_dx_iscsi.'
'FJDXISCSIDriver',
'cinder.volume.drivers.dell_emc.scaleio.driver.ScaleIODriver':
'cinder.volume.drivers.dell_emc.vxflexos.driver.VxFlexOSDriver',
}
class VolumeManager(manager.CleanableManager,
manager.SchedulerDependentManager):
"""Manages attachable block storage devices."""
RPC_API_VERSION = volume_rpcapi.VolumeAPI.RPC_API_VERSION
FAILBACK_SENTINEL = 'default'
target = messaging.Target(version=RPC_API_VERSION)
# On cloning a volume, we shouldn't copy volume_type, consistencygroup
# and volume_attachment, because the db sets that according to [field]_id,
# which we do copy. We also skip some other values that are set during
# creation of Volume object.
_VOLUME_CLONE_SKIP_PROPERTIES = {
'id', '_name_id', 'name_id', 'name', 'status',
'attach_status', 'migration_status', 'volume_type',
'consistencygroup', 'volume_attachment', 'group'}
def _get_service(self, host=None, binary=constants.VOLUME_BINARY):
host = host or self.host
ctxt = context.get_admin_context()
svc_host = volume_utils.extract_host(host, 'backend')
return objects.Service.get_by_args(ctxt, svc_host, binary)
def __init__(self, volume_driver=None, service_name=None,
*args, **kwargs):
"""Load the driver from the one specified in args, or from flags."""
# update_service_capabilities needs service_name to be volume
super(VolumeManager, self).__init__(service_name='volume',
*args, **kwargs)
# NOTE(dulek): service_name=None means we're running in unit tests.
service_name = service_name or 'backend_defaults'
self.configuration = config.Configuration(volume_backend_opts,
config_group=service_name)
self._set_tpool_size(
self.configuration.backend_native_threads_pool_size)
self.stats = {}
self.service_uuid = None
if not volume_driver:
# Get from configuration, which will get the default
# if its not using the multi backend
volume_driver = self.configuration.volume_driver
if volume_driver in MAPPING:
LOG.warning("Driver path %s is deprecated, update your "
"configuration to the new path.", volume_driver)
volume_driver = MAPPING[volume_driver]
vol_db_empty = self._set_voldb_empty_at_startup_indicator(
context.get_admin_context())
LOG.debug("Cinder Volume DB check: vol_db_empty=%s", vol_db_empty)
# We pass the current setting for service.active_backend_id to
# the driver on init, in case there was a restart or something
curr_active_backend_id = None
try:
service = self._get_service()
except exception.ServiceNotFound:
# NOTE(jdg): This is to solve problems with unit tests
LOG.info("Service not found for updating "
"active_backend_id, assuming default "
"for driver init.")
else:
curr_active_backend_id = service.active_backend_id
self.service_uuid = service.uuid
if self.configuration.suppress_requests_ssl_warnings:
LOG.warning("Suppressing requests library SSL Warnings")
requests.packages.urllib3.disable_warnings(
requests.packages.urllib3.exceptions.InsecureRequestWarning)
requests.packages.urllib3.disable_warnings(
requests.packages.urllib3.exceptions.InsecurePlatformWarning)
self.key_manager = key_manager.API(CONF)
# A driver can feed additional RPC endpoints into this list
driver_additional_endpoints = []
self.driver = importutils.import_object(
volume_driver,
configuration=self.configuration,
db=self.db,
host=self.host,
cluster_name=self.cluster,
is_vol_db_empty=vol_db_empty,
active_backend_id=curr_active_backend_id,
additional_endpoints=driver_additional_endpoints)
self.additional_endpoints.extend(driver_additional_endpoints)
if self.cluster and not self.driver.SUPPORTS_ACTIVE_ACTIVE:
msg = _('Active-Active configuration is not currently supported '
'by driver %s.') % volume_driver
LOG.error(msg)
raise exception.VolumeDriverException(message=msg)
self.message_api = message_api.API()
if CONF.profiler.enabled and profiler is not None:
self.driver = profiler.trace_cls("driver")(self.driver)
try:
self.extra_capabilities = jsonutils.loads(
self.driver.configuration.extra_capabilities)
except AttributeError:
self.extra_capabilities = {}
except Exception:
with excutils.save_and_reraise_exception():
LOG.error("Invalid JSON: %s",
self.driver.configuration.extra_capabilities)
# Check if a per-backend AZ has been specified
backend_zone = self.driver.configuration.safe_get(
'backend_availability_zone')
if backend_zone:
self.availability_zone = backend_zone
if self.driver.configuration.safe_get(
'image_volume_cache_enabled'):
max_cache_size = self.driver.configuration.safe_get(
'image_volume_cache_max_size_gb')
max_cache_entries = self.driver.configuration.safe_get(
'image_volume_cache_max_count')
self.image_volume_cache = image_cache.ImageVolumeCache(
self.db,
cinder_volume.API(),
max_cache_size,
max_cache_entries
)
LOG.info('Image-volume cache enabled for host %(host)s.',
{'host': self.host})
else:
LOG.info('Image-volume cache disabled for host %(host)s.',
{'host': self.host})
self.image_volume_cache = None
def _count_allocated_capacity(self, ctxt, volume):
pool = volume_utils.extract_host(volume['host'], 'pool')
if pool is None:
# No pool name encoded in host, so this is a legacy
# volume created before pool is introduced, ask
# driver to provide pool info if it has such
# knowledge and update the DB.
try:
pool = self.driver.get_pool(volume)
except Exception:
LOG.exception('Fetch volume pool name failed.',
resource=volume)
return
if pool:
new_host = volume_utils.append_host(volume['host'],
pool)
self.db.volume_update(ctxt, volume['id'],
{'host': new_host})
else:
# Otherwise, put them into a special fixed pool with
# volume_backend_name being the pool name, if
# volume_backend_name is None, use default pool name.
# This is only for counting purpose, doesn't update DB.
pool = (self.driver.configuration.safe_get(
'volume_backend_name') or volume_utils.extract_host(
volume['host'], 'pool', True))
try:
pool_stat = self.stats['pools'][pool]
except KeyError:
# First volume in the pool
self.stats['pools'][pool] = dict(
allocated_capacity_gb=0)
pool_stat = self.stats['pools'][pool]
pool_sum = pool_stat['allocated_capacity_gb']
pool_sum += volume['size']
self.stats['pools'][pool]['allocated_capacity_gb'] = pool_sum
self.stats['allocated_capacity_gb'] += volume['size']
def _set_voldb_empty_at_startup_indicator(self, ctxt):
"""Determine if the Cinder volume DB is empty.
A check of the volume DB is done to determine whether it is empty or
not at this point.
:param ctxt: our working context
"""
vol_entries = self.db.volume_get_all(ctxt, None, 1, filters=None)
if len(vol_entries) == 0:
LOG.info("Determined volume DB was empty at startup.")
return True
else:
LOG.info("Determined volume DB was not empty at startup.")
return False
def _sync_provider_info(self, ctxt, volumes, snapshots):
# NOTE(jdg): For now this just updates provider_id, we can add more
# items to the update if they're relevant but we need to be safe in
# what we allow and add a list of allowed keys. Things that make sense
# are provider_*, replication_status etc
updates, snapshot_updates = self.driver.update_provider_info(
volumes, snapshots)
if updates:
for volume in volumes:
# NOTE(JDG): Make sure returned item is in this hosts volumes
update = (
[updt for updt in updates if updt['id'] ==
volume['id']])
if update:
update = update[0]
self.db.volume_update(
ctxt,
update['id'],
{'provider_id': update['provider_id']})
if snapshot_updates:
for snap in snapshots:
# NOTE(jdg): For now we only update those that have no entry
if not snap.get('provider_id', None):
update = (
[updt for updt in snapshot_updates if updt['id'] ==
snap['id']][0])
if update:
self.db.snapshot_update(
ctxt,
update['id'],
{'provider_id': update['provider_id']})
def _include_resources_in_cluster(self, ctxt):
LOG.info('Including all resources from host %(host)s in cluster '
'%(cluster)s.',
{'host': self.host, 'cluster': self.cluster})
num_vols = objects.VolumeList.include_in_cluster(
ctxt, self.cluster, host=self.host)
num_cgs = objects.ConsistencyGroupList.include_in_cluster(
ctxt, self.cluster, host=self.host)
num_gs = objects.GroupList.include_in_cluster(
ctxt, self.cluster, host=self.host)
num_cache = db.image_volume_cache_include_in_cluster(
ctxt, self.cluster, host=self.host)
LOG.info('%(num_vols)s volumes, %(num_cgs)s consistency groups, '
'%(num_gs)s generic groups and %(num_cache)s image '
'volume caches from host %(host)s have been included in '
'cluster %(cluster)s.',
{'num_vols': num_vols, 'num_cgs': num_cgs, 'num_gs': num_gs,
'host': self.host, 'cluster': self.cluster,
'num_cache': num_cache})
def init_host(self, added_to_cluster=None, **kwargs):
"""Perform any required initialization."""
if not self.driver.supported:
utils.log_unsupported_driver_warning(self.driver)
if not self.configuration.enable_unsupported_driver:
LOG.error("Unsupported drivers are disabled."
" You can re-enable by adding "
"enable_unsupported_driver=True to the "
"driver section in cinder.conf",
resource={'type': 'driver',
'id': self.__class__.__name__})
return
self._init_host(added_to_cluster, **kwargs)
if not self.driver.initialized:
reinit_count = 0
while reinit_count < CONF.reinit_driver_count:
time.sleep(2 ** reinit_count)
self._init_host(added_to_cluster, **kwargs)
if self.driver.initialized:
return
reinit_count += 1
def _init_host(self, added_to_cluster=None, **kwargs):
ctxt = context.get_admin_context()
# If we have just added this host to a cluster we have to include all
# our resources in that cluster.
if added_to_cluster:
self._include_resources_in_cluster(ctxt)
LOG.info("Starting volume driver %(driver_name)s (%(version)s)",
{'driver_name': self.driver.__class__.__name__,
'version': self.driver.get_version()})
try:
self.driver.do_setup(ctxt)
self.driver.check_for_setup_error()
except Exception:
LOG.exception("Failed to initialize driver.",
resource={'type': 'driver',
'id': self.__class__.__name__})
# we don't want to continue since we failed
# to initialize the driver correctly.
return
# Initialize backend capabilities list
self.driver.init_capabilities()
# Zero stats
self.stats['pools'] = {}
self.stats.update({'allocated_capacity_gb': 0})
# Batch retrieval volumes and snapshots
num_vols, num_snaps, max_objs_num, req_range = None, None, None, [0]
req_limit = CONF.init_host_max_objects_retrieval
use_batch_objects_retrieval = req_limit > 0
if use_batch_objects_retrieval:
# Get total number of volumes
num_vols, __, __ = self._get_my_volumes_summary(ctxt)
# Get total number of snapshots
num_snaps, __ = self._get_my_snapshots_summary(ctxt)
# Calculate highest number of the objects (volumes or snapshots)
max_objs_num = max(num_vols, num_snaps)
# Make batch request loop counter
req_range = range(0, max_objs_num, req_limit)
volumes_to_migrate = volume_migration.VolumeMigrationList()
for req_offset in req_range:
# Retrieve 'req_limit' number of objects starting from
# 'req_offset' position
volumes, snapshots = None, None
if use_batch_objects_retrieval:
if req_offset < num_vols:
volumes = self._get_my_volumes(ctxt,
limit=req_limit,
offset=req_offset)
else:
volumes = objects.VolumeList()
if req_offset < num_snaps:
snapshots = self._get_my_snapshots(ctxt,
limit=req_limit,
offset=req_offset)
else:
snapshots = objects.SnapshotList()
# or retrieve all volumes and snapshots per single request
else:
volumes = self._get_my_volumes(ctxt)
snapshots = self._get_my_snapshots(ctxt)
self._sync_provider_info(ctxt, volumes, snapshots)
# FIXME volume count for exporting is wrong
try:
for volume in volumes:
# available volume should also be counted into allocated
if volume['status'] in ['in-use', 'available']:
# calculate allocated capacity for driver
self._count_allocated_capacity(ctxt, volume)
try:
if volume['status'] in ['in-use']:
self.driver.ensure_export(ctxt, volume)
except Exception:
LOG.exception("Failed to re-export volume, "
"setting to ERROR.",
resource=volume)
volume.conditional_update({'status': 'error'},
{'status': 'in-use'})
# All other cleanups are processed by parent class -
# CleanableManager
except Exception:
LOG.exception("Error during re-export on driver init.",
resource=volume)
return
if len(volumes):
volumes_to_migrate.append(volumes, ctxt)
del volumes
del snapshots
self.driver.set_throttle()
# at this point the driver is considered initialized.
# NOTE(jdg): Careful though because that doesn't mean
# that an entry exists in the service table
self.driver.set_initialized()
# Keep the image tmp file clean when init host.
backend_name = volume_utils.extract_host(self.service_topic_queue)
image_utils.cleanup_temporary_file(backend_name)
# Migrate any ConfKeyManager keys based on fixed_key to the currently
# configured key manager.
self._add_to_threadpool(key_migration.migrate_fixed_key,
volumes=volumes_to_migrate)
# collect and publish service capabilities
self.publish_service_capabilities(ctxt)
LOG.info("Driver initialization completed successfully.",
resource={'type': 'driver',
'id': self.driver.__class__.__name__})
# Make sure to call CleanableManager to do the cleanup
super(VolumeManager, self).init_host(added_to_cluster=added_to_cluster,
**kwargs)
def init_host_with_rpc(self):
LOG.info("Initializing RPC dependent components of volume "
"driver %(driver_name)s (%(version)s)",
{'driver_name': self.driver.__class__.__name__,
'version': self.driver.get_version()})
try:
# Make sure the driver is initialized first
utils.log_unsupported_driver_warning(self.driver)
utils.require_driver_initialized(self.driver)
except exception.DriverNotInitialized:
LOG.error("Cannot complete RPC initialization because "
"driver isn't initialized properly.",
resource={'type': 'driver',
'id': self.driver.__class__.__name__})
return
stats = self.driver.get_volume_stats(refresh=True)
try:
service = self._get_service()
except exception.ServiceNotFound:
with excutils.save_and_reraise_exception():
LOG.error("Service not found for updating replication_status.")
if service.replication_status != fields.ReplicationStatus.FAILED_OVER:
if stats and stats.get('replication_enabled', False):
replication_status = fields.ReplicationStatus.ENABLED
else:
replication_status = fields.ReplicationStatus.DISABLED
if replication_status != service.replication_status:
service.replication_status = replication_status
service.save()
# Update the cluster replication status if necessary
cluster = service.cluster
if (cluster and
cluster.replication_status != service.replication_status):
cluster.replication_status = service.replication_status
cluster.save()
LOG.info("Driver post RPC initialization completed successfully.",
resource={'type': 'driver',
'id': self.driver.__class__.__name__})
def
|
(self, ctxt, vo_resource):
if isinstance(vo_resource, objects.Volume):
if vo_resource.status == 'downloading':
self.driver.clear_download(ctxt, vo_resource)
elif vo_resource.status == 'uploading':
# Set volume status to available or in-use.
self.db.volume_update_status_based_on_attachment(
ctxt, vo_resource.id)
elif vo_resource.status == 'deleting':
if CONF.volume_service_inithost_offload:
# Offload all the pending volume delete operations to the
# threadpool to prevent the main volume service thread
# from being blocked.
self._add_to_threadpool(self.delete_volume, ctxt,
vo_resource, cascade=True)
else:
# By default, delete volumes sequentially
self.delete_volume(ctxt, vo_resource, cascade=True)
# We signal that we take care of cleaning the worker ourselves
# (with set_workers decorator in delete_volume method) so
# do_cleanup method doesn't need to remove it.
return True
# For Volume creating and downloading and for Snapshot downloading
# statuses we have to set status to error
if vo_resource.status in ('creating', 'downloading'):
vo_resource.status = 'error'
vo_resource.save()
def is_working(self):
"""Return if Manager is ready to accept requests.
This is to inform Service class that in case of volume driver
initialization failure the manager is actually down and not ready to
accept any requests.
"""
return self.driver.initialized
def _set_resource_host(self, resource):
"""Set the host field on the DB to our own when we are clustered."""
if (resource.is_clustered and
not volume_utils.hosts_are_equivalent(resource.host,
self.host)):
pool = volume_utils.extract_host(resource.host, 'pool')
resource.host = volume_utils.append_host(self.host, pool)
resource.save()
@objects.Volume.set_workers
def create_volume(self, context, volume, request_spec=None,
filter_properties=None, allow_reschedule=True):
"""Creates the volume."""
# Log about unsupported drivers
utils.log_unsupported_driver_warning(self.driver)
# Make sure the host in the DB matches our own when clustered
self._set_resource_host(volume)
# Update our allocated capacity counter early to minimize race
# conditions with the scheduler.
self._update_allocated_capacity(volume)
# We lose the host value if we reschedule, so keep it here
original_host = volume.host
context_elevated = context.elevated()
if filter_properties is None:
filter_properties = {}
if request_spec is None:
request_spec = objects.RequestSpec()
try:
# NOTE(flaper87): Driver initialization is
# verified by the task itself.
flow_engine = create_volume.get_flow(
context_elevated,
self,
self.db,
self.driver,
self.scheduler_rpcapi,
self.host,
volume,
allow_reschedule,
context,
request_spec,
filter_properties,
image_volume_cache=self.image_volume_cache,
)
except Exception:
msg = _("Create manager volume flow failed.")
LOG.exception(msg, resource={'type': 'volume', 'id': volume.id})
raise exception.CinderException(msg)
snapshot_id = request_spec.get('snapshot_id')
source_volid = request_spec.get('source_volid')
if snapshot_id is not None:
# Make sure the snapshot is not deleted until we are done with it.
locked_action = "%s-%s" % (snapshot_id, 'delete_snapshot')
elif source_volid is not None:
# Make sure the volume is not deleted until we are done with it.
locked_action = "%s-%s" % (source_volid, 'delete_volume')
else:
locked_action = None
def _run_flow():
# This code executes create volume flow. If something goes wrong,
# flow reverts all job that was done and reraises an exception.
# Otherwise, all data that was generated by flow becomes available
# in flow engine's storage.
with flow_utils.DynamicLogListener(flow_engine, logger=LOG):
flow_engine.run()
# NOTE(dulek): Flag to indicate if volume was rescheduled. Used to
# decide if allocated_capacity should be incremented.
rescheduled = False
try:
if locked_action is None:
_run_flow()
else:
with coordination.COORDINATOR.get_lock(locked_action):
_run_flow()
finally:
try:
flow_engine.storage.fetch('refreshed')
except tfe.NotFound:
# If there's no vol_ref, then flow is reverted. Lets check out
# if rescheduling occurred.
try:
rescheduled = flow_engine.storage.get_revert_result(
create_volume.OnFailureRescheduleTask.make_name(
[create_volume.ACTION]))
except tfe.NotFound:
pass
if rescheduled:
# NOTE(geguileo): Volume was rescheduled so we need to update
# volume stats because the volume wasn't created here.
# Volume.host is None now, so we pass the original host value.
self._update_allocated_capacity(volume, decrement=True,
host=original_host)
# Shared targets is only relevant for iSCSI connections.
# We default to True to be on the safe side.
volume.shared_targets = (
self.driver.capabilities.get('storage_protocol') == 'iSCSI' and
self.driver.capabilities.get('shared_targets', True))
# TODO(geguileo): service_uuid won't be enough on Active/Active
# deployments. There can be 2 services handling volumes from the same
# backend.
volume.service_uuid = self.service_uuid
volume.save()
LOG.info("Created volume successfully.", resource=volume)
return volume.id
def _check_is_our_resource(self, resource):
if resource.host:
res_backend = volume_utils.extract_host(
resource.service_topic_queue)
backend = volume_utils.extract_host(self.service_topic_queue)
if res_backend != backend:
msg = (_('Invalid %(resource)s: %(resource)s %(id)s is not '
'local to %(backend)s.') %
{'resource': resource.obj_name, 'id': resource.id,
'backend': backend})
raise exception.Invalid(msg)
@coordination.synchronized('{volume.id}-{f_name}')
@objects.Volume.set_workers
def delete_volume(self, context, volume, unmanage_only=False,
cascade=False):
"""Deletes and unexports volume.
1. Delete a volume(normal case)
Delete a volume and update quotas.
2. Delete a migration volume
If deleting the volume in a migration, we want to skip
quotas but we need database updates for the volume.
3. Delete a temp volume for backup
If deleting the temp volume for backup, we want to skip
quotas but we need database updates for the volume.
"""
context = context.elevated()
try:
volume.refresh()
except exception.VolumeNotFound:
# NOTE(thingee): It could be possible for a volume to
# be deleted when resuming deletes from init_host().
LOG.debug("Attempted delete of non-existent volume: %s", volume.id)
return
if context.project_id != volume.project_id:
project_id = volume.project_id
else:
project_id = context.project_id
if volume['attach_status'] == fields.VolumeAttachStatus.ATTACHED:
# Volume is still attached, need to detach first
raise exception.VolumeAttached(volume_id=volume.id)
self._check_is_our_resource(volume)
if unmanage_only and volume.encryption_key_id is not None:
raise exception.Invalid(
reason=_("Unmanaging encrypted volumes is not "
"supported."))
if unmanage_only and cascade:
# This could be done, but is ruled out for now just
# for simplicity.
raise exception.Invalid(
reason=_("Unmanage and cascade delete options "
"are mutually exclusive."))
# To backup a snapshot or a 'in-use' volume, create a temp volume
# from the snapshot or in-use volume, and back it up.
# Get admin_metadata (needs admin context) to detect temporary volume.
is_temp_vol = False
with volume.obj_as_admin():
if volume.admin_metadata.get('temporary', 'False') == 'True':
is_temp_vol = True
LOG.info("Trying to delete temp volume: %s", volume.id)
# The status 'deleting' is not included, because it only applies to
# the source volume to be deleted after a migration. No quota
# needs to be handled for it.
is_migrating = volume.migration_status not in (None, 'error',
'success')
is_migrating_dest = (is_migrating and
volume.migration_status.startswith(
'target:'))
notification = "delete.start"
if unmanage_only:
notification = "unmanage.start"
if not is_temp_vol:
self._notify_about_volume_usage(context, volume, notification)
try:
# NOTE(flaper87): Verify the driver is enabled
# before going forward. The exception will be caught
# and the volume status updated.
utils.require_driver_initialized(self.driver)
self.driver.remove_export(context, volume)
if unmanage_only:
self.driver.unmanage(volume)
elif cascade:
LOG.debug('Performing cascade delete.')
snapshots = objects.SnapshotList.get_all_for_volume(context,
volume.id)
for s in snapshots:
if s.status != fields.SnapshotStatus.DELETING:
self._clear_db(context, is_migrating_dest, volume,
'error_deleting')
msg = (_("Snapshot %(id)s was found in state "
"%(state)s rather than 'deleting' during "
"cascade delete.") % {'id': s.id,
'state': s.status})
raise exception.InvalidSnapshot(reason=msg)
self.delete_snapshot(context, s)
LOG.debug('Snapshots deleted, issuing volume delete')
self.driver.delete_volume(volume)
else:
self.driver.delete_volume(volume)
except exception.VolumeIsBusy:
LOG.error("Unable to delete busy volume.",
resource=volume)
# If this is a destination volume, we have to clear the database
# record to avoid user confusion.
self._clear_db(context, is_migrating_dest, volume,
'available')
return
except Exception:
with excutils.save_and_reraise_exception():
# If this is a destination volume, we have to clear the
# database record to avoid user confusion.
new_status = 'error_deleting'
if unmanage_only is True:
new_status = 'error_unmanaging'
self._clear_db(context, is_migrating_dest, volume,
new_status)
# If deleting source/destination volume in a migration or a temp
# volume for backup, we should skip quotas.
skip_quota = is_migrating or is_temp_vol
if not skip_quota:
# Get reservations
try:
reservations = None
if volume.status != 'error_managing_deleting':
reserve_opts = {'volumes': -1,
'gigabytes': -volume.size}
QUOTAS.add_volume_type_opts(context,
reserve_opts,
volume.volume_type_id)
reservations = QUOTAS.reserve(context,
project_id=project_id,
**reserve_opts)
except Exception:
LOG.exception("Failed to update usages deleting volume.",
resource=volume)
volume.destroy()
# If deleting source/destination volume in a migration or a temp
# volume for backup, we should skip quotas.
if not skip_quota:
notification = "delete.end"
if unmanage_only:
notification = "unmanage.end"
self._notify_about_volume_usage(context, volume, notification)
# Commit the reservations
if reservations:
QUOTAS.commit(context, reservations, project_id=project_id)
self._update_allocated_capacity(volume, decrement=True)
self.publish_service_capabilities(context)
msg = "Deleted volume successfully."
if unmanage_only:
msg = "Unmanaged volume successfully."
LOG.info(msg, resource=volume)
def _clear_db(self, context, is_migrating_dest, volume_ref, status):
# This method is called when driver.unmanage() or
# driver.delete_volume() fails in delete_volume(), so it is already
# in the exception handling part.
if is_migrating_dest:
volume_ref.destroy()
LOG.error("Unable to delete the destination volume "
"during volume migration, (NOTE: database "
"record needs to be deleted).", resource=volume_ref)
else:
volume_ref.status = status
volume_ref.save()
def _revert_to_snapshot_generic(self, ctxt, volume, snapshot):
"""Generic way to revert volume to a snapshot.
the framework will use the generic way to implement the revert
to snapshot feature:
1. create a temporary volume from snapshot
2. mount two volumes to host
3. copy data from temporary volume to original volume
4. detach and destroy temporary volume
"""
temp_vol = None
try:
v_options = {'display_name': '[revert] temporary volume created '
'from snapshot %s' % snapshot.id}
ctxt = context.get_internal_tenant_context() or ctxt
temp_vol = self.driver._create_temp_volume_from_snapshot(
ctxt, volume, snapshot, volume_options=v_options)
self._copy_volume_data(ctxt, temp_vol, volume)
self.driver.delete_volume(temp_vol)
temp_vol.destroy()
except Exception:
with excutils.save_and_reraise_exception():
LOG.exception(
"Failed to use snapshot %(snapshot)s to create "
"a temporary volume and copy data to volume "
" %(volume)s.",
{'snapshot': snapshot.id,
'volume': volume.id})
if temp_vol and temp_vol.status == 'available':
self.driver.delete_volume(temp_vol)
temp_vol.destroy()
def _revert_to_snapshot(self, context, volume, snapshot):
"""Use driver or generic method to rollback volume."""
try:
self.driver.revert_to_snapshot(context, volume, snapshot)
except (NotImplementedError, AttributeError):
LOG.info("Driver's 'revert_to_snapshot' is not found. "
"Try to use copy-snapshot-to-volume method.")
self._revert_to_snapshot_generic(context, volume, snapshot)
def _create_backup_snapshot(self, context, volume):
kwargs = {
'volume_id': volume.id,
'user_id': context.user_id,
'project_id': context.project_id,
'status': fields.SnapshotStatus.CREATING,
'progress': '0%',
'volume_size': volume.size,
'display_name': '[revert] volume %s backup snapshot' % volume.id,
'display_description': 'This is only used for backup when '
'reverting. If the reverting process '
'failed, you can restore you data by '
'creating new volume with this snapshot.',
'volume_type_id': volume.volume_type_id,
'encryption_key_id': volume.encryption_key_id,
'metadata': {}
}
snapshot = objects.Snapshot(context=context, **kwargs)
snapshot.create()
self.create_snapshot(context, snapshot)
return snapshot
def revert_to_snapshot(self, context, volume, snapshot):
"""Revert a volume to a snapshot.
The process of reverting to snapshot consists of several steps:
1. create a snapshot for backup (in case of data loss)
2.1. use driver's specific logic to revert volume
2.2. try the generic way to revert volume if driver's method is missing
3. delete the backup snapshot
"""
backup_snapshot = None
try:
LOG.info("Start to perform revert to snapshot process.")
self._notify_about_volume_usage(context, volume,
"revert.start")
self._notify_about_snapshot_usage(context, snapshot,
"revert.start")
# Create a snapshot which can be used to restore the volume
# data by hand if revert process failed.
if self.driver.snapshot_revert_use_temp_snapshot():
backup_snapshot = self._create_backup_snapshot(context,
volume)
self._revert_to_snapshot(context, volume, snapshot)
except Exception as error:
with excutils.save_and_reraise_exception():
self._notify_about_volume_usage(context, volume,
"revert.end")
self._notify_about_snapshot_usage(context, snapshot,
"revert.end")
msg = ('Volume %(v_id)s revert to '
'snapshot %(s_id)s failed with %(error)s.')
msg_args = {'v_id': volume.id,
's_id': snapshot.id,
'error': six.text_type(error)}
v_res = volume.update_single_status_where(
'error',
'reverting')
if not v_res:
msg_args = {"id": volume.id,
"status": 'error'}
msg += ("Failed to reset volume %(id)s "
"status to %(status)s.") % msg_args
s_res = snapshot.update_single_status_where(
fields.SnapshotStatus.AVAILABLE,
fields.SnapshotStatus.RESTORING)
if not s_res:
msg_args = {"id": snapshot.id,
"status":
fields.SnapshotStatus.AVAILABLE}
msg += ("Failed to reset snapshot %(id)s "
"status to %(status)s." % msg_args)
LOG.exception(msg, msg_args)
v_res = volume.update_single_status_where(
'available', 'reverting')
if not v_res:
msg_args = {"id": volume.id,
"status": 'available'}
msg = _("Revert finished, but failed to reset "
"volume %(id)s status to %(status)s, "
"please manually reset it.") % msg_args
raise exception.BadResetResourceStatus(reason=msg)
s_res = snapshot.update_single_status_where(
fields.SnapshotStatus.AVAILABLE,
fields.SnapshotStatus.RESTORING)
if not s_res:
msg_args = {"id": snapshot.id,
"status":
fields.SnapshotStatus.AVAILABLE}
msg = _("Revert finished, but failed to reset "
"snapshot %(id)s status to %(status)s, "
"please manually reset it.") % msg_args
raise exception.BadResetResourceStatus(reason=msg)
if backup_snapshot:
self.delete_snapshot(context,
backup_snapshot, handle_quota=False)
msg = ('Volume %(v_id)s reverted to snapshot %(snap_id)s '
'successfully.')
msg_args = {'v_id': volume.id, 'snap_id': snapshot.id}
LOG.info(msg, msg_args)
self._notify_about_volume_usage(context, volume, "revert.end")
self._notify_about_snapshot_usage(context, snapshot, "revert.end")
@objects.Snapshot.set_workers
def create_snapshot(self, context, snapshot):
"""Creates and exports the snapshot."""
context = context.elevated()
self._notify_about_snapshot_usage(
context, snapshot, "create.start")
try:
# NOTE(flaper87): Verify the driver is enabled
# before going forward. The exception will be caught
# and the snapshot status updated.
utils.require_driver_initialized(self.driver)
# Pass context so that drivers that want to use it, can,
# but it is not a requirement for all drivers.
snapshot.context = context
model_update = self.driver.create_snapshot(snapshot)
if model_update:
snapshot.update(model_update)
snapshot.save()
except Exception as create_error:
with excutils.save_and_reraise_exception():
snapshot.status = fields.SnapshotStatus.ERROR
snapshot.save()
self.message_api.create(
context,
action=message_field.Action.SNAPSHOT_CREATE,
resource_type=message_field.Resource.VOLUME_SNAPSHOT,
resource_uuid=snapshot['id'],
exception=create_error,
detail=message_field.Detail.SNAPSHOT_CREATE_ERROR)
vol_ref = self.db.volume_get(context, snapshot.volume_id)
if vol_ref.bootable:
try:
self.db.volume_glance_metadata_copy_to_snapshot(
context, snapshot.id, snapshot.volume_id)
except exception.GlanceMetadataNotFound:
# If volume is not created from image, No glance metadata
# would be available for that volume in
# volume glance metadata table
pass
except exception.CinderException as ex:
LOG.exception("Failed updating snapshot"
" metadata using the provided volumes"
" %(volume_id)s metadata",
{'volume_id': snapshot.volume_id},
resource=snapshot)
snapshot.status = fields.SnapshotStatus.ERROR
snapshot.save()
self.message_api.create(
context,
action=message_field.Action.SNAPSHOT_CREATE,
resource_type=message_field.Resource.VOLUME_SNAPSHOT,
resource_uuid=snapshot['id'],
exception=ex,
detail=message_field.Detail.SNAPSHOT_UPDATE_METADATA_FAILED
)
raise exception.MetadataCopyFailure(reason=six.text_type(ex))
snapshot.status = fields.SnapshotStatus.AVAILABLE
snapshot.progress = '100%'
# Resync with the volume's DB value. This addresses the case where
# the snapshot creation was in flight just prior to when the volume's
# fixed_key encryption key ID was migrated to Barbican.
snapshot.encryption_key_id = vol_ref.encryption_key_id
snapshot.save()
self._notify_about_snapshot_usage(context, snapshot, "create.end")
LOG.info("Create snapshot completed successfully",
resource=snapshot)
return snapshot.id
@coordination.synchronized('{snapshot.id}-{f_name}')
def delete_snapshot(self, context, snapshot,
unmanage_only=False, handle_quota=True):
"""Deletes and unexports snapshot."""
context = context.elevated()
snapshot._context = context
project_id = snapshot.project_id
self._notify_about_snapshot_usage(
context, snapshot, "delete.start")
try:
# NOTE(flaper87): Verify the driver is enabled
# before going forward. The exception will be caught
# and the snapshot status updated.
utils.require_driver_initialized(self.driver)
# Pass context so that drivers that want to use it, can,
# but it is not a requirement for all drivers.
snapshot.context = context
snapshot.save()
if unmanage_only:
self.driver.unmanage_snapshot(snapshot)
else:
self.driver.delete_snapshot(snapshot)
except exception.SnapshotIsBusy as busy_error:
LOG.error("Delete snapshot failed, due to snapshot busy.",
resource=snapshot)
snapshot.status = fields.SnapshotStatus.AVAILABLE
snapshot.save()
self.message_api.create(
context,
action=message_field.Action.SNAPSHOT_DELETE,
resource_type=message_field.Resource.VOLUME_SNAPSHOT,
resource_uuid=snapshot['id'],
exception=busy_error)
return
except Exception as delete_error:
with excutils.save_and_reraise_exception():
snapshot.status = fields.SnapshotStatus.ERROR_DELETING
snapshot.save()
self.message_api.create(
context,
action=message_field.Action.SNAPSHOT_DELETE,
resource_type=message_field.Resource.VOLUME_SNAPSHOT,
resource_uuid=snapshot['id'],
exception=delete_error,
detail=message_field.Detail.SNAPSHOT_DELETE_ERROR)
# Get reservations
reservations = None
try:
if handle_quota:
if CONF.no_snapshot_gb_quota:
reserve_opts = {'snapshots': -1}
else:
reserve_opts = {
'snapshots': -1,
'gigabytes': -snapshot.volume_size,
}
volume_ref = self.db.volume_get(context, snapshot.volume_id)
QUOTAS.add_volume_type_opts(context,
reserve_opts,
volume_ref.get('volume_type_id'))
reservations = QUOTAS.reserve(context,
project_id=project_id,
**reserve_opts)
except Exception:
reservations = None
LOG.exception("Update snapshot usages failed.",
resource=snapshot)
self.db.volume_glance_metadata_delete_by_snapshot(context, snapshot.id)
snapshot.destroy()
self._notify_about_snapshot_usage(context, snapshot, "delete.end")
# Commit the reservations
if reservations:
QUOTAS.commit(context, reservations, project_id=project_id)
msg = "Delete snapshot completed successfully."
if unmanage_only:
msg = "Unmanage snapshot completed successfully."
LOG.info(msg, resource=snapshot)
@coordination.synchronized('{volume_id}')
def attach_volume(self, context, volume_id, instance_uuid, host_name,
mountpoint, mode, volume=None):
"""Updates db to show volume is attached."""
# FIXME(lixiaoy1): Remove this in v4.0 of RPC API.
if volume is None:
# For older clients, mimic the old behavior and look
# up the volume by its volume_id.
volume = objects.Volume.get_by_id(context, volume_id)
# Get admin_metadata. This needs admin context.
with volume.obj_as_admin():
volume_metadata = volume.admin_metadata
# check the volume status before attaching
if volume.status == 'attaching':
if (volume_metadata.get('attached_mode') and
volume_metadata.get('attached_mode') != mode):
raise exception.InvalidVolume(
reason=_("being attached by different mode"))
host_name_sanitized = volume_utils.sanitize_hostname(
host_name) if host_name else None
if instance_uuid:
attachments = (
VA_LIST.get_all_by_instance_uuid(
context, instance_uuid))
else:
attachments = (
VA_LIST.get_all_by_host(
context, host_name_sanitized))
if attachments:
# check if volume<->instance mapping is already tracked in DB
for attachment in attachments:
if attachment['volume_id'] == volume_id:
volume.status = 'in-use'
volume.save()
return attachment
if (volume.status == 'in-use' and not volume.multiattach
and not volume.migration_status):
raise exception.InvalidVolume(
reason=_("volume is already attached and multiple attachments "
"are not enabled"))
self._notify_about_volume_usage(context, volume,
"attach.start")
attachment = volume.begin_attach(mode)
if instance_uuid and not uuidutils.is_uuid_like(instance_uuid):
attachment.attach_status = (
fields.VolumeAttachStatus.ERROR_ATTACHING)
attachment.save()
raise exception.InvalidUUID(uuid=instance_uuid)
try:
if volume_metadata.get('readonly') == 'True' and mode != 'ro':
raise exception.InvalidVolumeAttachMode(mode=mode,
volume_id=volume.id)
# NOTE(flaper87): Verify the driver is enabled
# before going forward. The exception will be caught
# and the volume status updated.
utils.require_driver_initialized(self.driver)
LOG.info('Attaching volume %(volume_id)s to instance '
'%(instance)s at mountpoint %(mount)s on host '
'%(host)s.',
{'volume_id': volume_id, 'instance': instance_uuid,
'mount': mountpoint, 'host': host_name_sanitized},
resource=volume)
self.driver.attach_volume(context,
volume,
instance_uuid,
host_name_sanitized,
mountpoint)
except Exception as excep:
with excutils.save_and_reraise_exception():
self.message_api.create(
context,
message_field.Action.ATTACH_VOLUME,
resource_uuid=volume_id,
exception=excep)
attachment.attach_status = (
fields.VolumeAttachStatus.ERROR_ATTACHING)
attachment.save()
volume = attachment.finish_attach(
instance_uuid,
host_name_sanitized,
mountpoint,
mode)
self._notify_about_volume_usage(context, volume, "attach.end")
LOG.info("Attach volume completed successfully.",
resource=volume)
return attachment
@coordination.synchronized('{volume_id}-{f_name}')
def detach_volume(self, context, volume_id, attachment_id=None,
volume=None):
"""Updates db to show volume is detached."""
# TODO(vish): refactor this into a more general "unreserve"
# FIXME(lixiaoy1): Remove this in v4.0 of RPC API.
if volume is None:
# For older clients, mimic the old behavior and look up the volume
# by its volume_id.
volume = objects.Volume.get_by_id(context, volume_id)
if attachment_id:
try:
attachment = objects.VolumeAttachment.get_by_id(context,
attachment_id)
except exception.VolumeAttachmentNotFound:
LOG.info("Volume detach called, but volume not attached.",
resource=volume)
# We need to make sure the volume status is set to the correct
# status. It could be in detaching status now, and we don't
# want to leave it there.
volume.finish_detach(attachment_id)
return
else:
# We can try and degrade gracefully here by trying to detach
# a volume without the attachment_id here if the volume only has
# one attachment. This is for backwards compatibility.
attachments = volume.volume_attachment
if len(attachments) > 1:
# There are more than 1 attachments for this volume
# we have to have an attachment id.
msg = _("Detach volume failed: More than one attachment, "
"but no attachment_id provided.")
LOG.error(msg, resource=volume)
raise exception.InvalidVolume(reason=msg)
elif len(attachments) == 1:
attachment = attachments[0]
else:
# there aren't any attachments for this volume.
# so set the status to available and move on.
LOG.info("Volume detach called, but volume not attached.",
resource=volume)
volume.status = 'available'
volume.attach_status = fields.VolumeAttachStatus.DETACHED
volume.save()
return
self._notify_about_volume_usage(context, volume, "detach.start")
try:
# NOTE(flaper87): Verify the driver is enabled
# before going forward. The exception will be caught
# and the volume status updated.
utils.require_driver_initialized(self.driver)
LOG.info('Detaching volume %(volume_id)s from instance '
'%(instance)s.',
{'volume_id': volume_id,
'instance': attachment.get('instance_uuid')},
resource=volume)
self.driver.detach_volume(context, volume, attachment)
except Exception:
with excutils.save_and_reraise_exception():
self.db.volume_attachment_update(
context, attachment.get('id'), {
'attach_status':
fields.VolumeAttachStatus.ERROR_DETACHING})
# NOTE(jdg): We used to do an ensure export here to
# catch upgrades while volumes were attached (E->F)
# this was necessary to convert in-use volumes from
# int ID's to UUID's. Don't need this any longer
# We're going to remove the export here
# (delete the iscsi target)
try:
utils.require_driver_initialized(self.driver)
self.driver.remove_export(context.elevated(), volume)
except exception.DriverNotInitialized:
with excutils.save_and_reraise_exception():
LOG.exception("Detach volume failed, due to "
"uninitialized driver.",
resource=volume)
except Exception as ex:
LOG.exception("Detach volume failed, due to "
"remove-export failure.",
resource=volume)
raise exception.RemoveExportException(volume=volume_id,
reason=six.text_type(ex))
volume.finish_detach(attachment.id)
self._notify_about_volume_usage(context, volume, "detach.end")
LOG.info("Detach volume completed successfully.", resource=volume)
def _create_image_cache_volume_entry(self, ctx, volume_ref,
image_id, image_meta):
"""Create a new image-volume and cache entry for it.
This assumes that the image has already been downloaded and stored
in the volume described by the volume_ref.
"""
cache_entry = self.image_volume_cache.get_entry(ctx,
volume_ref,
image_id,
image_meta)
if cache_entry:
LOG.debug('Cache entry already exists with image ID %'
'(image_id)s',
{'image_id': image_id})
return
image_volume = None
try:
if not self.image_volume_cache.ensure_space(ctx, volume_ref):
LOG.warning('Unable to ensure space for image-volume in'
' cache. Will skip creating entry for image'
' %(image)s on %(service)s.',
{'image': image_id,
'service': volume_ref.service_topic_queue})
return
image_volume = self._clone_image_volume(ctx,
volume_ref,
image_meta)
if not image_volume:
LOG.warning('Unable to clone image_volume for image '
'%(image_id)s will not create cache entry.',
{'image_id': image_id})
return
self.image_volume_cache.create_cache_entry(
ctx,
image_volume,
image_id,
image_meta
)
except exception.CinderException as e:
LOG.warning('Failed to create new image-volume cache entry.'
' Error: %(exception)s', {'exception': e})
if image_volume:
self.delete_volume(ctx, image_volume)
def _clone_image_volume(self, ctx, volume, image_meta):
volume_type_id = volume.get('volume_type_id')
reserve_opts = {'volumes': 1, 'gigabytes': volume.size}
QUOTAS.add_volume_type_opts(ctx, reserve_opts, volume_type_id)
reservations = QUOTAS.reserve(ctx, **reserve_opts)
# NOTE(yikun): Skip 'snapshot_id', 'source_volid' keys to avoid
# creating tmp img vol from wrong snapshot or wrong source vol.
skip = {'snapshot_id', 'source_volid'}
skip.update(self._VOLUME_CLONE_SKIP_PROPERTIES)
try:
new_vol_values = {k: volume[k] for k in set(volume.keys()) - skip}
new_vol_values['volume_type_id'] = volume_type_id
new_vol_values['attach_status'] = (
fields.VolumeAttachStatus.DETACHED)
new_vol_values['status'] = 'creating'
new_vol_values['project_id'] = ctx.project_id
new_vol_values['display_name'] = 'image-%s' % image_meta['id']
new_vol_values['source_volid'] = volume.id
LOG.debug('Creating image volume entry: %s.', new_vol_values)
image_volume = objects.Volume(context=ctx, **new_vol_values)
image_volume.create()
except Exception as ex:
LOG.exception('Create clone_image_volume: %(volume_id)s '
'for image %(image_id)s, '
'failed (Exception: %(except)s)',
{'volume_id': volume.id,
'image_id': image_meta['id'],
'except': ex})
QUOTAS.rollback(ctx, reservations)
return
QUOTAS.commit(ctx, reservations,
project_id=new_vol_values['project_id'])
try:
self.create_volume(ctx, image_volume, allow_reschedule=False)
image_volume.refresh()
if image_volume.status != 'available':
raise exception.InvalidVolume(_('Volume is not available.'))
self.db.volume_admin_metadata_update(ctx.elevated(),
image_volume.id,
{'readonly': 'True'},
False)
return image_volume
except exception.CinderException:
LOG.exception('Failed to clone volume %(volume_id)s for '
'image %(image_id)s.',
{'volume_id': volume.id,
'image_id': image_meta['id']})
try:
self.delete_volume(ctx, image_volume)
except exception.CinderException:
LOG.exception('Could not delete the image volume %(id)s.',
{'id': volume.id})
return
def _clone_image_volume_and_add_location(self, ctx, volume, image_service,
image_meta):
"""Create a cloned volume and register its location to the image."""
if (image_meta['disk_format'] != 'raw' or
image_meta['container_format'] != 'bare'):
return False
image_volume_context = ctx
if self.driver.configuration.image_upload_use_internal_tenant:
internal_ctx = context.get_internal_tenant_context()
if internal_ctx:
image_volume_context = internal_ctx
image_volume = self._clone_image_volume(image_volume_context,
volume,
image_meta)
if not image_volume:
return False
# The image_owner metadata should be set before uri is added to
# the image so glance cinder store can check its owner.
image_volume_meta = {'image_owner': ctx.project_id}
self.db.volume_metadata_update(image_volume_context,
image_volume.id,
image_volume_meta,
False)
uri = 'cinder://%s' % image_volume.id
image_registered = None
try:
image_registered = image_service.add_location(
ctx, image_meta['id'], uri, {})
except (exception.NotAuthorized, exception.Invalid,
exception.NotFound):
LOG.exception('Failed to register image volume location '
'%(uri)s.', {'uri': uri})
if not image_registered:
LOG.warning('Registration of image volume URI %(uri)s '
'to image %(image_id)s failed.',
{'uri': uri, 'image_id': image_meta['id']})
try:
self.delete_volume(image_volume_context, image_volume)
except exception.CinderException:
LOG.exception('Could not delete failed image volume '
'%(id)s.', {'id': image_volume.id})
return False
image_volume_meta['glance_image_id'] = image_meta['id']
self.db.volume_metadata_update(image_volume_context,
image_volume.id,
image_volume_meta,
False)
return True
def copy_volume_to_image(self, context, volume_id, image_meta):
"""Uploads the specified volume to Glance.
image_meta is a dictionary containing the following keys:
'id', 'container_format', 'disk_format'
"""
payload = {'volume_id': volume_id, 'image_id': image_meta['id']}
image_service = None
try:
volume = objects.Volume.get_by_id(context, volume_id)
# NOTE(flaper87): Verify the driver is enabled
# before going forward. The exception will be caught
# and the volume status updated.
utils.require_driver_initialized(self.driver)
image_service, image_id = \
glance.get_remote_image_service(context, image_meta['id'])
if (self.driver.configuration.image_upload_use_cinder_backend
and self._clone_image_volume_and_add_location(
context, volume, image_service, image_meta)):
LOG.debug("Registered image volume location to glance "
"image-id: %(image_id)s.",
{'image_id': image_meta['id']},
resource=volume)
else:
self.driver.copy_volume_to_image(context, volume,
image_service, image_meta)
LOG.debug("Uploaded volume to glance image-id: %(image_id)s.",
{'image_id': image_meta['id']},
resource=volume)
except Exception as error:
LOG.error("Upload volume to image encountered an error "
"(image-id: %(image_id)s).",
{'image_id': image_meta['id']},
resource=volume)
self.message_api.create(
context,
message_field.Action.COPY_VOLUME_TO_IMAGE,
resource_uuid=volume_id,
exception=error,
detail=message_field.Detail.FAILED_TO_UPLOAD_VOLUME)
if image_service is not None:
# Deletes the image if it is in queued or saving state
self._delete_image(context, image_meta['id'], image_service)
with excutils.save_and_reraise_exception():
payload['message'] = six.text_type(error)
finally:
self.db.volume_update_status_based_on_attachment(context,
volume_id)
LOG.info("Copy volume to image completed successfully.",
resource=volume)
def _delete_image(self, context, image_id, image_service):
"""Deletes an image stuck in queued or saving state."""
try:
image_meta = image_service.show(context, image_id)
image_status = image_meta.get('status')
if image_status == 'queued' or image_status == 'saving':
LOG.warning("Deleting image in unexpected status: "
"%(image_status)s.",
{'image_status': image_status},
resource={'type': 'image', 'id': image_id})
image_service.delete(context, image_id)
except Exception:
LOG.warning("Image delete encountered an error.",
exc_info=True, resource={'type': 'image',
'id': image_id})
def _parse_connection_options(self, context, volume, conn_info):
# Add qos_specs to connection info
typeid = volume.volume_type_id
specs = None
if typeid:
res = volume_types.get_volume_type_qos_specs(typeid)
qos = res['qos_specs']
# only pass qos_specs that is designated to be consumed by
# front-end, or both front-end and back-end.
if qos and qos.get('consumer') in ['front-end', 'both']:
specs = qos.get('specs')
# NOTE(mnaser): The following configures for per-GB QoS
if specs is not None:
volume_size = int(volume.size)
tune_opts = ('read_iops_sec', 'read_bytes_sec',
'write_iops_sec', 'write_bytes_sec',
'total_iops_sec', 'total_bytes_sec')
for option in tune_opts:
option_per_gb = '%s_per_gb' % option
option_per_gb_min = '%s_per_gb_min' % option
option_max = '%s_max' % option
if option_per_gb in specs:
minimum_value = int(specs.pop(option_per_gb_min, 0))
value = int(specs[option_per_gb]) * volume_size
per_gb_value = max(minimum_value, value)
max_value = int(specs.pop(option_max, per_gb_value))
specs[option] = min(per_gb_value, max_value)
specs.pop(option_per_gb)
qos_spec = dict(qos_specs=specs)
conn_info['data'].update(qos_spec)
# Add access_mode to connection info
volume_metadata = volume.admin_metadata
access_mode = volume_metadata.get('attached_mode')
if access_mode is None:
# NOTE(zhiyan): client didn't call 'os-attach' before
access_mode = ('ro'
if volume_metadata.get('readonly') == 'True'
else 'rw')
conn_info['data']['access_mode'] = access_mode
# Add encrypted flag to connection_info if not set in the driver.
if conn_info['data'].get('encrypted') is None:
encrypted = bool(volume.encryption_key_id)
conn_info['data']['encrypted'] = encrypted
# Add discard flag to connection_info if not set in the driver and
# configured to be reported.
if conn_info['data'].get('discard') is None:
discard_supported = (self.driver.configuration
.safe_get('report_discard_supported'))
if discard_supported:
conn_info['data']['discard'] = True
return conn_info
def initialize_connection(self, context, volume, connector):
"""Prepare volume for connection from host represented by connector.
This method calls the driver initialize_connection and returns
it to the caller. The connector parameter is a dictionary with
information about the host that will connect to the volume in the
following format:
.. code:: json
{
"ip": "<ip>",
"initiator": "<initiator>"
}
ip:
the ip address of the connecting machine
initiator:
the iscsi initiator name of the connecting machine. This can be
None if the connecting machine does not support iscsi connections.
driver is responsible for doing any necessary security setup and
returning a connection_info dictionary in the following format:
.. code:: json
{
"driver_volume_type": "<driver_volume_type>",
"data": "<data>"
}
driver_volume_type:
a string to identify the type of volume. This can be used by the
calling code to determine the strategy for connecting to the
volume. This could be 'iscsi', 'rbd', 'sheepdog', etc.
data:
this is the data that the calling code will use to connect to the
volume. Keep in mind that this will be serialized to json in
various places, so it should not contain any non-json data types.
"""
# NOTE(flaper87): Verify the driver is enabled
# before going forward. The exception will be caught
# and the volume status updated.
# TODO(jdg): Add deprecation warning
utils.require_driver_initialized(self.driver)
try:
self.driver.validate_connector(connector)
except exception.InvalidConnectorException as err:
raise exception.InvalidInput(reason=six.text_type(err))
except Exception as err:
err_msg = (_("Validate volume connection failed "
"(error: %(err)s).") % {'err': six.text_type(err)})
LOG.exception(err_msg, resource=volume)
raise exception.VolumeBackendAPIException(data=err_msg)
try:
model_update = self.driver.create_export(context.elevated(),
volume, connector)
except exception.CinderException as ex:
msg = _("Create export of volume failed (%s)") % ex.msg
LOG.exception(msg, resource=volume)
raise exception.VolumeBackendAPIException(data=msg)
try:
if model_update:
volume.update(model_update)
volume.save()
except Exception as ex:
LOG.exception("Model update failed.", resource=volume)
try:
self.driver.remove_export(context.elevated(), volume)
except Exception:
LOG.exception('Could not remove export after DB model failed.')
raise exception.ExportFailure(reason=six.text_type(ex))
try:
conn_info = self.driver.initialize_connection(volume, connector)
except exception.ConnectorRejected:
with excutils.save_and_reraise_exception():
LOG.info("The connector was rejected by the volume driver.")
except Exception as err:
err_msg = (_("Driver initialize connection failed "
"(error: %(err)s).") % {'err': six.text_type(err)})
LOG.exception(err_msg, resource=volume)
self.driver.remove_export(context.elevated(), volume)
raise exception.VolumeBackendAPIException(data=err_msg)
conn_info = self._parse_connection_options(context, volume, conn_info)
LOG.info("Initialize volume connection completed successfully.",
resource=volume)
return conn_info
def initialize_connection_snapshot(self, ctxt, snapshot_id, connector):
utils.require_driver_initialized(self.driver)
snapshot = objects.Snapshot.get_by_id(ctxt, snapshot_id)
try:
self.driver.validate_connector(connector)
except exception.InvalidConnectorException as err:
raise exception.InvalidInput(reason=six.text_type(err))
except Exception as err:
err_msg = (_("Validate snapshot connection failed "
"(error: %(err)s).") % {'err': six.text_type(err)})
LOG.exception(err_msg, resource=snapshot)
raise exception.VolumeBackendAPIException(data=err_msg)
model_update = None
try:
LOG.debug("Snapshot %s: creating export.", snapshot.id)
model_update = self.driver.create_export_snapshot(
ctxt.elevated(), snapshot, connector)
if model_update:
snapshot.provider_location = model_update.get(
'provider_location', None)
snapshot.provider_auth = model_update.get(
'provider_auth', None)
snapshot.save()
except exception.CinderException as ex:
msg = _("Create export of snapshot failed (%s)") % ex.msg
LOG.exception(msg, resource=snapshot)
raise exception.VolumeBackendAPIException(data=msg)
try:
if model_update:
snapshot.update(model_update)
snapshot.save()
except exception.CinderException as ex:
LOG.exception("Model update failed.", resource=snapshot)
raise exception.ExportFailure(reason=six.text_type(ex))
try:
conn = self.driver.initialize_connection_snapshot(snapshot,
connector)
except Exception as err:
try:
err_msg = (_('Unable to fetch connection information from '
'backend: %(err)s') %
{'err': six.text_type(err)})
LOG.error(err_msg)
LOG.debug("Cleaning up failed connect initialization.")
self.driver.remove_export_snapshot(ctxt.elevated(), snapshot)
except Exception as ex:
ex_msg = (_('Error encountered during cleanup '
'of a failed attach: %(ex)s') %
{'ex': six.text_type(ex)})
LOG.error(ex_msg)
raise exception.VolumeBackendAPIException(data=ex_msg)
raise exception.VolumeBackendAPIException(data=err_msg)
LOG.info("Initialize snapshot connection completed successfully.",
resource=snapshot)
return conn
def terminate_connection(self, context, volume_id, connector, force=False):
"""Cleanup connection from host represented by connector.
The format of connector is the same as for initialize_connection.
"""
# NOTE(flaper87): Verify the driver is enabled
# before going forward. The exception will be caught
# and the volume status updated.
utils.require_driver_initialized(self.driver)
volume_ref = self.db.volume_get(context, volume_id)
try:
self.driver.terminate_connection(volume_ref, connector,
force=force)
except Exception as err:
err_msg = (_('Terminate volume connection failed: %(err)s')
% {'err': six.text_type(err)})
LOG.exception(err_msg, resource=volume_ref)
raise exception.VolumeBackendAPIException(data=err_msg)
LOG.info("Terminate volume connection completed successfully.",
resource=volume_ref)
def terminate_connection_snapshot(self, ctxt, snapshot_id,
connector, force=False):
utils.require_driver_initialized(self.driver)
snapshot = objects.Snapshot.get_by_id(ctxt, snapshot_id)
try:
self.driver.terminate_connection_snapshot(snapshot, connector,
force=force)
except Exception as err:
err_msg = (_('Terminate snapshot connection failed: %(err)s')
% {'err': six.text_type(err)})
LOG.exception(err_msg, resource=snapshot)
raise exception.VolumeBackendAPIException(data=err_msg)
LOG.info("Terminate snapshot connection completed successfully.",
resource=snapshot)
def remove_export(self, context, volume_id):
"""Removes an export for a volume."""
utils.require_driver_initialized(self.driver)
volume_ref = self.db.volume_get(context, volume_id)
try:
self.driver.remove_export(context, volume_ref)
except Exception:
msg = _("Remove volume export failed.")
LOG.exception(msg, resource=volume_ref)
raise exception.VolumeBackendAPIException(data=msg)
LOG.info("Remove volume export completed successfully.",
resource=volume_ref)
def remove_export_snapshot(self, ctxt, snapshot_id):
"""Removes an export for a snapshot."""
utils.require_driver_initialized(self.driver)
snapshot = objects.Snapshot.get_by_id(ctxt, snapshot_id)
try:
self.driver.remove_export_snapshot(ctxt, snapshot)
except Exception:
msg = _("Remove snapshot export failed.")
LOG.exception(msg, resource=snapshot)
raise exception.VolumeBackendAPIException(data=msg)
LOG.info("Remove snapshot export completed successfully.",
resource=snapshot)
def accept_transfer(self, context, volume_id, new_user, new_project,
no_snapshots=False):
# NOTE(flaper87): Verify the driver is enabled
# before going forward. The exception will be caught
# and the volume status updated.
utils.require_driver_initialized(self.driver)
# NOTE(jdg): need elevated context as we haven't "given" the vol
# yet
volume_ref = self.db.volume_get(context.elevated(), volume_id)
# NOTE(jdg): Some drivers tie provider info (CHAP) to tenant
# for those that do allow them to return updated model info
model_update = self.driver.accept_transfer(context,
volume_ref,
new_user,
new_project)
if model_update:
try:
self.db.volume_update(context.elevated(),
volume_id,
model_update)
except exception.CinderException:
with excutils.save_and_reraise_exception():
LOG.exception("Update volume model for "
"transfer operation failed.",
resource=volume_ref)
self.db.volume_update(context.elevated(),
volume_id,
{'status': 'error'})
LOG.info("Transfer volume completed successfully.",
resource=volume_ref)
return model_update
def _connect_device(self, conn):
use_multipath = self.configuration.use_multipath_for_image_xfer
device_scan_attempts = self.configuration.num_volume_device_scan_tries
protocol = conn['driver_volume_type']
connector = utils.brick_get_connector(
protocol,
use_multipath=use_multipath,
device_scan_attempts=device_scan_attempts,
conn=conn)
vol_handle = connector.connect_volume(conn['data'])
root_access = True
if not connector.check_valid_device(vol_handle['path'], root_access):
if isinstance(vol_handle['path'], six.string_types):
raise exception.DeviceUnavailable(
path=vol_handle['path'],
reason=(_("Unable to access the backend storage via the "
"path %(path)s.") %
{'path': vol_handle['path']}))
else:
raise exception.DeviceUnavailable(
path=None,
reason=(_("Unable to access the backend storage via file "
"handle.")))
return {'conn': conn, 'device': vol_handle, 'connector': connector}
def _attach_volume(self, ctxt, volume, properties, remote=False,
attach_encryptor=False):
status = volume['status']
if remote:
rpcapi = volume_rpcapi.VolumeAPI()
try:
conn = rpcapi.initialize_connection(ctxt, volume, properties)
except Exception:
with excutils.save_and_reraise_exception():
LOG.error("Failed to attach volume %(vol)s.",
{'vol': volume['id']})
self.db.volume_update(ctxt, volume['id'],
{'status': status})
else:
conn = self.initialize_connection(ctxt, volume, properties)
attach_info = self._connect_device(conn)
try:
if attach_encryptor and (
volume_types.is_encrypted(ctxt,
volume.volume_type_id)):
encryption = self.db.volume_encryption_metadata_get(
ctxt.elevated(), volume.id)
if encryption:
utils.brick_attach_volume_encryptor(ctxt,
attach_info,
encryption)
except Exception:
with excutils.save_and_reraise_exception():
LOG.error("Failed to attach volume encryptor"
" %(vol)s.", {'vol': volume['id']})
self._detach_volume(ctxt, attach_info, volume, properties,
force=True)
return attach_info
def _detach_volume(self, ctxt, attach_info, volume, properties,
force=False, remote=False,
attach_encryptor=False):
connector = attach_info['connector']
if attach_encryptor and (
volume_types.is_encrypted(ctxt,
volume.volume_type_id)):
encryption = self.db.volume_encryption_metadata_get(
ctxt.elevated(), volume.id)
if encryption:
utils.brick_detach_volume_encryptor(attach_info, encryption)
connector.disconnect_volume(attach_info['conn']['data'],
attach_info['device'], force=force)
if remote:
rpcapi = volume_rpcapi.VolumeAPI()
rpcapi.terminate_connection(ctxt, volume, properties, force=force)
rpcapi.remove_export(ctxt, volume)
else:
try:
self.terminate_connection(ctxt, volume['id'], properties,
force=force)
self.remove_export(ctxt, volume['id'])
except Exception as err:
with excutils.save_and_reraise_exception():
LOG.error('Unable to terminate volume connection: '
'%(err)s.', {'err': err})
def _copy_volume_data(self, ctxt, src_vol, dest_vol, remote=None):
"""Copy data from src_vol to dest_vol."""
LOG.debug('_copy_volume_data %(src)s -> %(dest)s.',
{'src': src_vol['name'], 'dest': dest_vol['name']})
attach_encryptor = False
# If the encryption method or key is changed, we have to
# copy data through dm-crypt.
if volume_types.volume_types_encryption_changed(
ctxt,
src_vol.volume_type_id,
dest_vol.volume_type_id):
attach_encryptor = True
use_multipath = self.configuration.use_multipath_for_image_xfer
enforce_multipath = self.configuration.enforce_multipath_for_image_xfer
properties = utils.brick_get_connector_properties(use_multipath,
enforce_multipath)
dest_remote = remote in ['dest', 'both']
dest_attach_info = self._attach_volume(
ctxt, dest_vol, properties,
remote=dest_remote,
attach_encryptor=attach_encryptor)
try:
src_remote = remote in ['src', 'both']
src_attach_info = self._attach_volume(
ctxt, src_vol, properties,
remote=src_remote,
attach_encryptor=attach_encryptor)
except Exception:
with excutils.save_and_reraise_exception():
LOG.error("Failed to attach source volume for copy.")
self._detach_volume(ctxt, dest_attach_info, dest_vol,
properties, remote=dest_remote,
attach_encryptor=attach_encryptor,
force=True)
# Check the backend capabilities of migration destination host.
rpcapi = volume_rpcapi.VolumeAPI()
capabilities = rpcapi.get_capabilities(ctxt,
dest_vol.service_topic_queue,
False)
sparse_copy_volume = bool(capabilities and
capabilities.get('sparse_copy_volume',
False))
try:
size_in_mb = int(src_vol['size']) * units.Ki # vol size is in GB
volume_utils.copy_volume(src_attach_info['device']['path'],
dest_attach_info['device']['path'],
size_in_mb,
self.configuration.volume_dd_blocksize,
sparse=sparse_copy_volume)
except Exception:
with excutils.save_and_reraise_exception():
LOG.error("Failed to copy volume %(src)s to %(dest)s.",
{'src': src_vol['id'], 'dest': dest_vol['id']})
finally:
try:
self._detach_volume(ctxt, dest_attach_info, dest_vol,
properties, force=True,
remote=dest_remote,
attach_encryptor=attach_encryptor)
finally:
self._detach_volume(ctxt, src_attach_info, src_vol,
properties, force=True,
remote=src_remote,
attach_encryptor=attach_encryptor)
def _migrate_volume_generic(self, ctxt, volume, backend, new_type_id):
rpcapi = volume_rpcapi.VolumeAPI()
# Create new volume on remote host
tmp_skip = {'snapshot_id', 'source_volid'}
skip = {'host', 'cluster_name', 'availability_zone'}
skip.update(tmp_skip)
skip.update(self._VOLUME_CLONE_SKIP_PROPERTIES)
new_vol_values = {k: volume[k] for k in set(volume.keys()) - skip}
if new_type_id:
new_vol_values['volume_type_id'] = new_type_id
if volume_types.volume_types_encryption_changed(
ctxt, volume.volume_type_id, new_type_id):
encryption_key_id = volume_utils.create_encryption_key(
ctxt, self.key_manager, new_type_id)
new_vol_values['encryption_key_id'] = encryption_key_id
dst_service = self._get_service(backend['host'])
new_volume = objects.Volume(
context=ctxt,
host=backend['host'],
availability_zone=dst_service.availability_zone,
cluster_name=backend.get('cluster_name'),
status='creating',
attach_status=fields.VolumeAttachStatus.DETACHED,
migration_status='target:%s' % volume['id'],
**new_vol_values
)
new_volume.create()
rpcapi.create_volume(ctxt, new_volume, None, None,
allow_reschedule=False)
# Wait for new_volume to become ready
starttime = time.time()
deadline = starttime + CONF.migration_create_volume_timeout_secs
new_volume.refresh()
tries = 0
while new_volume.status != 'available':
tries += 1
now = time.time()
if new_volume.status == 'error':
msg = _("failed to create new_volume on destination")
self._clean_temporary_volume(ctxt, volume,
new_volume,
clean_db_only=True)
raise exception.VolumeMigrationFailed(reason=msg)
elif now > deadline:
msg = _("timeout creating new_volume on destination")
self._clean_temporary_volume(ctxt, volume,
new_volume,
clean_db_only=True)
raise exception.VolumeMigrationFailed(reason=msg)
else:
time.sleep(tries ** 2)
new_volume.refresh()
# Set skipped value to avoid calling
# function except for _create_raw_volume
tmp_skipped_values = {k: volume[k] for k in tmp_skip if volume.get(k)}
if tmp_skipped_values:
new_volume.update(tmp_skipped_values)
new_volume.save()
# Copy the source volume to the destination volume
try:
attachments = volume.volume_attachment
# A volume might have attachments created, but if it is reserved
# it means it's being migrated prior to the attachment completion.
if not attachments or volume.status == 'reserved':
# Pre- and post-copy driver-specific actions
self.driver.before_volume_copy(ctxt, volume, new_volume,
remote='dest')
self._copy_volume_data(ctxt, volume, new_volume, remote='dest')
self.driver.after_volume_copy(ctxt, volume, new_volume,
remote='dest')
# The above call is synchronous so we complete the migration
self.migrate_volume_completion(ctxt, volume, new_volume,
error=False)
else:
nova_api = compute.API()
# This is an async call to Nova, which will call the completion
# when it's done
for attachment in attachments:
instance_uuid = attachment['instance_uuid']
nova_api.update_server_volume(ctxt, instance_uuid,
volume.id,
new_volume.id)
except Exception:
with excutils.save_and_reraise_exception():
LOG.exception(
"Failed to copy volume %(vol1)s to %(vol2)s", {
'vol1': volume.id, 'vol2': new_volume.id})
self._clean_temporary_volume(ctxt, volume,
new_volume)
def _clean_temporary_volume(self, ctxt, volume, new_volume,
clean_db_only=False):
# If we're in the migrating phase, we need to cleanup
# destination volume because source volume is remaining
if volume.migration_status == 'migrating':
try:
if clean_db_only:
# The temporary volume is not created, only DB data
# is created
new_volume.destroy()
else:
# The temporary volume is already created
rpcapi = volume_rpcapi.VolumeAPI()
rpcapi.delete_volume(ctxt, new_volume)
except exception.VolumeNotFound:
LOG.info("Couldn't find the temporary volume "
"%(vol)s in the database. There is no need "
"to clean up this volume.",
{'vol': new_volume.id})
else:
# If we're in the completing phase don't delete the
# destination because we may have already deleted the
# source! But the migration_status in database should
# be cleared to handle volume after migration failure
try:
new_volume.migration_status = None
new_volume.save()
except exception.VolumeNotFound:
LOG.info("Couldn't find destination volume "
"%(vol)s in the database. The entry might be "
"successfully deleted during migration "
"completion phase.",
{'vol': new_volume.id})
LOG.warning("Failed to migrate volume. The destination "
"volume %(vol)s is not deleted since the "
"source volume may have been deleted.",
{'vol': new_volume.id})
def migrate_volume_completion(self, ctxt, volume, new_volume, error=False):
try:
# NOTE(flaper87): Verify the driver is enabled
# before going forward. The exception will be caught
# and the migration status updated.
utils.require_driver_initialized(self.driver)
except exception.DriverNotInitialized:
with excutils.save_and_reraise_exception():
volume.migration_status = 'error'
volume.save()
# NOTE(jdg): Things get a little hairy in here and we do a lot of
# things based on volume previous-status and current-status. At some
# point this should all be reworked but for now we need to maintain
# backward compatibility and NOT change the API so we're going to try
# and make this work best we can
LOG.debug("migrate_volume_completion: completing migration for "
"volume %(vol1)s (temporary volume %(vol2)s",
{'vol1': volume.id, 'vol2': new_volume.id})
rpcapi = volume_rpcapi.VolumeAPI()
orig_volume_status = volume.previous_status
if error:
LOG.info("migrate_volume_completion is cleaning up an error "
"for volume %(vol1)s (temporary volume %(vol2)s",
{'vol1': volume['id'], 'vol2': new_volume.id})
rpcapi.delete_volume(ctxt, new_volume)
updates = {'migration_status': 'error',
'status': orig_volume_status}
volume.update(updates)
volume.save()
return volume.id
volume.migration_status = 'completing'
volume.save()
volume_attachments = []
# NOTE(jdg): With new attach flow, we deleted the attachment, so the
# original volume should now be listed as available, we still need to
# do the magic swappy thing of name.id etc but we're done with the
# original attachment record
# In the "old flow" at this point the orig_volume_status will be in-use
# and the current status will be retyping. This is sort of a
# misleading deal, because Nova has already called terminate
# connection
# New Attach Flow, Nova has gone ahead and deleted the attachemnt, this
# is the source/original volume, we've already migrated the data, we're
# basically done with it at this point. We don't need to issue the
# detach to toggle the status
if orig_volume_status == 'in-use' and volume.status != 'available':
for attachment in volume.volume_attachment:
# Save the attachments the volume currently have
volume_attachments.append(attachment)
try:
self.detach_volume(ctxt, volume.id, attachment.id)
except Exception as ex:
LOG.error("Detach migration source volume "
"%(volume.id)s from attachment "
"%(attachment.id)s failed: %(err)s",
{'err': ex,
'volume.id': volume.id,
'attachment.id': attachment.id},
resource=volume)
# Give driver (new_volume) a chance to update things as needed
# after a successful migration.
# Note this needs to go through rpc to the host of the new volume
# the current host and driver object is for the "existing" volume.
rpcapi.update_migrated_volume(ctxt, volume, new_volume,
orig_volume_status)
volume.refresh()
new_volume.refresh()
# Swap src and dest DB records so we can continue using the src id and
# asynchronously delete the destination id
updated_new = volume.finish_volume_migration(new_volume)
updates = {'status': orig_volume_status,
'previous_status': volume.status,
'migration_status': 'success'}
# NOTE(jdg): With new attachment API's nova will delete the
# attachment for the source volume for us before calling the
# migration-completion, now we just need to do the swapping on the
# volume record, but don't jack with the attachments other than
# updating volume_id
# In the old flow at this point the volumes are in attaching and
# deleting status (dest/new is deleting, but we've done our magic
# swappy thing so it's a bit confusing, but it does unwind properly
# when you step through it)
# In the new flow we simlified this and we don't need it, instead of
# doing a bunch of swapping we just do attachment-create/delete on the
# nova side, and then here we just do the ID swaps that are necessary
# to maintain the old beahvior
# Restore the attachments for old flow use-case
if orig_volume_status == 'in-use' and volume.status in ['available',
'reserved',
'attaching']:
for attachment in volume_attachments:
LOG.debug('Re-attaching: %s', attachment)
# This is just a db state toggle, the volume is actually
# already attach and in-use, new attachment flow won't allow
# this
rpcapi.attach_volume(ctxt, volume,
attachment.instance_uuid,
attachment.attached_host,
attachment.mountpoint,
attachment.attach_mode or 'rw')
# At this point we now have done almost all of our swapping and
# state-changes. The target volume is now marked back to
# "in-use" the destination/worker volume is now in deleting
# state and the next steps will finish the deletion steps
volume.update(updates)
volume.save()
# Asynchronous deletion of the source volume in the back-end (now
# pointed by the target volume id)
try:
rpcapi.delete_volume(ctxt, updated_new)
except Exception as ex:
LOG.error('Failed to request async delete of migration source '
'vol %(vol)s: %(err)s',
{'vol': volume.id, 'err': ex})
# For the new flow this is really the key part. We just use the
# attachments to the worker/destination volumes that we created and
# used for the libvirt migration and we'll just swap their volume_id
# entries to coorespond with the volume.id swap we did
for attachment in VA_LIST.get_all_by_volume_id(ctxt, updated_new.id):
attachment.volume_id = volume.id
attachment.save()
# Phewww.. that was easy! Once we get to a point where the old attach
# flow can go away we really should rewrite all of this.
LOG.info("Complete-Migrate volume completed successfully.",
resource=volume)
return volume.id
def migrate_volume(self, ctxt, volume, host, force_host_copy=False,
new_type_id=None):
"""Migrate the volume to the specified host (called on source host)."""
try:
# NOTE(flaper87): Verify the driver is enabled
# before going forward. The exception will be caught
# and the migration status updated.
utils.require_driver_initialized(self.driver)
except exception.DriverNotInitialized:
with excutils.save_and_reraise_exception():
volume.migration_status = 'error'
volume.save()
model_update = None
moved = False
status_update = None
if volume.status in ('retyping', 'maintenance'):
status_update = {'status': volume.previous_status}
volume.migration_status = 'migrating'
volume.save()
if not force_host_copy and new_type_id is None:
try:
LOG.debug("Issue driver.migrate_volume.", resource=volume)
moved, model_update = self.driver.migrate_volume(ctxt,
volume,
host)
if moved:
dst_service = self._get_service(host['host'])
updates = {
'host': host['host'],
'cluster_name': host.get('cluster_name'),
'migration_status': 'success',
'availability_zone': dst_service.availability_zone,
'previous_status': volume.status,
}
if status_update:
updates.update(status_update)
if model_update:
updates.update(model_update)
volume.update(updates)
volume.save()
except Exception:
with excutils.save_and_reraise_exception():
updates = {'migration_status': 'error'}
if status_update:
updates.update(status_update)
volume.update(updates)
volume.save()
if not moved:
try:
self._migrate_volume_generic(ctxt, volume, host, new_type_id)
except Exception:
with excutils.save_and_reraise_exception():
updates = {'migration_status': 'error'}
if status_update:
updates.update(status_update)
volume.update(updates)
volume.save()
LOG.info("Migrate volume completed successfully.",
resource=volume)
def _report_driver_status(self, context):
# It's possible during live db migration that the self.service_uuid
# value isn't set (we didn't restart services), so we'll go ahead
# and make this a part of the service periodic
if not self.service_uuid:
# We hack this with a try/except for unit tests temporarily
try:
service = self._get_service()
self.service_uuid = service.uuid
except exception.ServiceNotFound:
LOG.warning("Attempt to update service_uuid "
"resulted in a Service NotFound "
"exception, service_uuid field on "
"volumes will be NULL.")
if not self.driver.initialized:
if self.driver.configuration.config_group is None:
config_group = ''
else:
config_group = ('(config name %s)' %
self.driver.configuration.config_group)
LOG.warning("Update driver status failed: %(config_group)s "
"is uninitialized.",
{'config_group': config_group},
resource={'type': 'driver',
'id': self.driver.__class__.__name__})
else:
volume_stats = self.driver.get_volume_stats(refresh=True)
if self.extra_capabilities:
volume_stats.update(self.extra_capabilities)
if "pools" in volume_stats:
for pool in volume_stats["pools"]:
pool.update(self.extra_capabilities)
else:
volume_stats.update(self.extra_capabilities)
if volume_stats:
# NOTE(xyang): If driver reports replication_status to be
# 'error' in volume_stats, get model updates from driver
# and update db
if volume_stats.get('replication_status') == (
fields.ReplicationStatus.ERROR):
filters = self._get_cluster_or_host_filters()
groups = objects.GroupList.get_all_replicated(
context, filters=filters)
group_model_updates, volume_model_updates = (
self.driver.get_replication_error_status(context,
groups))
for grp_update in group_model_updates:
try:
grp_obj = objects.Group.get_by_id(
context, grp_update['group_id'])
grp_obj.update(grp_update)
grp_obj.save()
except exception.GroupNotFound:
# Group may be deleted already. Log a warning
# and continue.
LOG.warning("Group %(grp)s not found while "
"updating driver status.",
{'grp': grp_update['group_id']},
resource={
'type': 'group',
'id': grp_update['group_id']})
for vol_update in volume_model_updates:
try:
vol_obj = objects.Volume.get_by_id(
context, vol_update['volume_id'])
vol_obj.update(vol_update)
vol_obj.save()
except exception.VolumeNotFound:
# Volume may be deleted already. Log a warning
# and continue.
LOG.warning("Volume %(vol)s not found while "
"updating driver status.",
{'vol': vol_update['volume_id']},
resource={
'type': 'volume',
'id': vol_update['volume_id']})
# Append volume stats with 'allocated_capacity_gb'
self._append_volume_stats(volume_stats)
# Append filter and goodness function if needed
volume_stats = (
self._append_filter_goodness_functions(volume_stats))
# queue it to be sent to the Schedulers.
self.update_service_capabilities(volume_stats)
def _append_volume_stats(self, vol_stats):
pools = vol_stats.get('pools', None)
if pools:
if isinstance(pools, list):
for pool in pools:
pool_name = pool['pool_name']
try:
pool_stats = self.stats['pools'][pool_name]
except KeyError:
# Pool not found in volume manager
pool_stats = dict(allocated_capacity_gb=0)
pool.update(pool_stats)
else:
raise exception.ProgrammingError(
reason='Pools stats reported by the driver are not '
'reported in a list')
# For drivers that are not reporting their stats by pool we will use
# the data from the special fixed pool created by
# _count_allocated_capacity.
elif self.stats.get('pools'):
vol_stats.update(next(iter(self.stats['pools'].values())))
# This is a special subcase of the above no pool case that happens when
# we don't have any volumes yet.
else:
vol_stats.update(self.stats)
vol_stats.pop('pools', None)
def _append_filter_goodness_functions(self, volume_stats):
"""Returns volume_stats updated as needed."""
# Append filter_function if needed
if 'filter_function' not in volume_stats:
volume_stats['filter_function'] = (
self.driver.get_filter_function())
# Append goodness_function if needed
if 'goodness_function' not in volume_stats:
volume_stats['goodness_function'] = (
self.driver.get_goodness_function())
return volume_stats
@periodic_task.periodic_task(spacing=CONF.backend_stats_polling_interval)
def publish_service_capabilities(self, context):
"""Collect driver status and then publish."""
self._report_driver_status(context)
self._publish_service_capabilities(context)
def _notify_about_volume_usage(self,
context,
volume,
event_suffix,
extra_usage_info=None):
volume_utils.notify_about_volume_usage(
context, volume, event_suffix,
extra_usage_info=extra_usage_info, host=self.host)
def _notify_about_snapshot_usage(self,
context,
snapshot,
event_suffix,
extra_usage_info=None):
volume_utils.notify_about_snapshot_usage(
context, snapshot, event_suffix,
extra_usage_info=extra_usage_info, host=self.host)
def _notify_about_group_usage(self,
context,
group,
event_suffix,
volumes=None,
extra_usage_info=None):
volume_utils.notify_about_group_usage(
context, group, event_suffix,
extra_usage_info=extra_usage_info, host=self.host)
if not volumes:
volumes = objects.VolumeList.get_all_by_generic_group(
context, group.id)
if volumes:
for volume in volumes:
volume_utils.notify_about_volume_usage(
context, volume, event_suffix,
extra_usage_info=extra_usage_info, host=self.host)
def _notify_about_group_snapshot_usage(self,
context,
group_snapshot,
event_suffix,
snapshots=None,
extra_usage_info=None):
volume_utils.notify_about_group_snapshot_usage(
context, group_snapshot, event_suffix,
extra_usage_info=extra_usage_info, host=self.host)
if not snapshots:
snapshots = objects.SnapshotList.get_all_for_group_snapshot(
context, group_snapshot.id)
if snapshots:
for snapshot in snapshots:
volume_utils.notify_about_snapshot_usage(
context, snapshot, event_suffix,
extra_usage_info=extra_usage_info, host=self.host)
def extend_volume(self, context, volume, new_size, reservations):
try:
# NOTE(flaper87): Verify the driver is enabled
# before going forward. The exception will be caught
# and the volume status updated.
utils.require_driver_initialized(self.driver)
except exception.DriverNotInitialized:
with excutils.save_and_reraise_exception():
volume.status = 'error_extending'
volume.save()
project_id = volume.project_id
size_increase = (int(new_size)) - volume.size
self._notify_about_volume_usage(context, volume, "resize.start")
try:
self.driver.extend_volume(volume, new_size)
except exception.TargetUpdateFailed:
# We just want to log this but continue on with quota commit
LOG.warning('Volume extended but failed to update target.')
except Exception:
LOG.exception("Extend volume failed.",
resource=volume)
self.message_api.create(
context,
message_field.Action.EXTEND_VOLUME,
resource_uuid=volume.id,
detail=message_field.Detail.DRIVER_FAILED_EXTEND)
try:
self.db.volume_update(context, volume.id,
{'status': 'error_extending'})
raise exception.CinderException(_("Volume %s: Error trying "
"to extend volume") %
volume.id)
finally:
QUOTAS.rollback(context, reservations, project_id=project_id)
return
QUOTAS.commit(context, reservations, project_id=project_id)
attachments = volume.volume_attachment
if not attachments:
orig_volume_status = 'available'
else:
orig_volume_status = 'in-use'
volume.update({'size': int(new_size), 'status': orig_volume_status})
volume.save()
if orig_volume_status == 'in-use':
nova_api = compute.API()
instance_uuids = [attachment.instance_uuid
for attachment in attachments]
nova_api.extend_volume(context, instance_uuids, volume.id)
pool = volume_utils.extract_host(volume.host, 'pool')
if pool is None:
# Legacy volume, put them into default pool
pool = self.driver.configuration.safe_get(
'volume_backend_name') or volume_utils.extract_host(
volume.host, 'pool', True)
try:
self.stats['pools'][pool]['allocated_capacity_gb'] += size_increase
except KeyError:
self.stats['pools'][pool] = dict(
allocated_capacity_gb=size_increase)
self._notify_about_volume_usage(
context, volume, "resize.end",
extra_usage_info={'size': int(new_size)})
LOG.info("Extend volume completed successfully.",
resource=volume)
def _is_our_backend(self, host, cluster_name):
return ((not cluster_name and
volume_utils.hosts_are_equivalent(self.driver.host, host)) or
(cluster_name and
volume_utils.hosts_are_equivalent(self.driver.cluster_name,
cluster_name)))
def retype(self, context, volume, new_type_id, host,
migration_policy='never', reservations=None,
old_reservations=None):
def _retype_error(context, volume, old_reservations,
new_reservations, status_update):
try:
volume.update(status_update)
volume.save()
finally:
if old_reservations:
QUOTAS.rollback(context, old_reservations)
if new_reservations:
QUOTAS.rollback(context, new_reservations)
previous_status = (
volume.previous_status or volume.status)
status_update = {'status': previous_status}
if context.project_id != volume.project_id:
project_id = volume.project_id
else:
project_id = context.project_id
try:
# NOTE(flaper87): Verify the driver is enabled
# before going forward. The exception will be caught
# and the volume status updated.
utils.require_driver_initialized(self.driver)
except exception.DriverNotInitialized:
with excutils.save_and_reraise_exception():
# NOTE(flaper87): Other exceptions in this method don't
# set the volume status to error. Should that be done
# here? Setting the volume back to it's original status
# for now.
volume.update(status_update)
volume.save()
# We already got the new reservations
new_reservations = reservations
# If volume types have the same contents, no need to do anything.
# Use the admin contex to be able to access volume extra_specs
retyped = False
diff, all_equal = volume_types.volume_types_diff(
context.elevated(), volume.volume_type_id, new_type_id)
if all_equal:
retyped = True
# Call driver to try and change the type
retype_model_update = None
# NOTE(jdg): Check to see if the destination host or cluster (depending
# if it's the volume is in a clustered backend or not) is the same as
# the current. If it's not don't call the driver.retype method,
# otherwise drivers that implement retype may report success, but it's
# invalid in the case of a migrate.
# We assume that those that support pools do this internally
# so we strip off the pools designation
if (not retyped and
not diff.get('encryption') and
self._is_our_backend(host['host'], host.get('cluster_name'))):
try:
new_type = volume_types.get_volume_type(context.elevated(),
new_type_id)
with volume.obj_as_admin():
ret = self.driver.retype(context,
volume,
new_type,
diff,
host)
# Check if the driver retype provided a model update or
# just a retype indication
if type(ret) == tuple:
retyped, retype_model_update = ret
else:
retyped = ret
if retyped:
LOG.info("Volume %s: retyped successfully.", volume.id)
except Exception:
retyped = False
LOG.exception("Volume %s: driver error when trying to "
"retype, falling back to generic "
"mechanism.", volume.id)
# We could not change the type, so we need to migrate the volume, where
# the destination volume will be of the new type
if not retyped:
if migration_policy == 'never':
_retype_error(context, volume, old_reservations,
new_reservations, status_update)
msg = _("Retype requires migration but is not allowed.")
raise exception.VolumeMigrationFailed(reason=msg)
snaps = objects.SnapshotList.get_all_for_volume(context,
volume.id)
if snaps:
_retype_error(context, volume, old_reservations,
new_reservations, status_update)
msg = _("Volume must not have snapshots.")
LOG.error(msg)
raise exception.InvalidVolume(reason=msg)
# Don't allow volume with replicas to be migrated
rep_status = volume.replication_status
if(rep_status is not None and rep_status not in
[fields.ReplicationStatus.DISABLED,
fields.ReplicationStatus.NOT_CAPABLE]):
_retype_error(context, volume, old_reservations,
new_reservations, status_update)
msg = _("Volume must not be replicated.")
LOG.error(msg)
raise exception.InvalidVolume(reason=msg)
volume.migration_status = 'starting'
volume.save()
try:
self.migrate_volume(context, volume, host,
new_type_id=new_type_id)
except Exception:
with excutils.save_and_reraise_exception():
_retype_error(context, volume, old_reservations,
new_reservations, status_update)
else:
model_update = {'volume_type_id': new_type_id,
'host': host['host'],
'cluster_name': host.get('cluster_name'),
'status': status_update['status']}
if retype_model_update:
model_update.update(retype_model_update)
self._set_replication_status(diff, model_update)
volume.update(model_update)
volume.save()
if old_reservations:
QUOTAS.commit(context, old_reservations, project_id=project_id)
if new_reservations:
QUOTAS.commit(context, new_reservations, project_id=project_id)
self._notify_about_volume_usage(
context, volume, "retype",
extra_usage_info={'volume_type': new_type_id})
self.publish_service_capabilities(context)
LOG.info("Retype volume completed successfully.",
resource=volume)
@staticmethod
def _set_replication_status(diff, model_update):
"""Update replication_status in model_update if it has changed."""
if not diff or model_update.get('replication_status'):
return
diff_specs = diff.get('extra_specs', {})
replication_diff = diff_specs.get('replication_enabled')
if replication_diff:
is_replicated = volume_utils.is_boolean_str(replication_diff[1])
if is_replicated:
replication_status = fields.ReplicationStatus.ENABLED
else:
replication_status = fields.ReplicationStatus.DISABLED
model_update['replication_status'] = replication_status
def manage_existing(self, ctxt, volume, ref=None):
vol_ref = self._run_manage_existing_flow_engine(
ctxt, volume, ref)
self._update_stats_for_managed(vol_ref)
LOG.info("Manage existing volume completed successfully.",
resource=vol_ref)
return vol_ref.id
def _update_stats_for_managed(self, volume_reference):
# Update volume stats
pool = volume_utils.extract_host(volume_reference.host, 'pool')
if pool is None:
# Legacy volume, put them into default pool
pool = self.driver.configuration.safe_get(
'volume_backend_name') or volume_utils.extract_host(
volume_reference.host, 'pool', True)
try:
self.stats['pools'][pool]['allocated_capacity_gb'] \
+= volume_reference.size
except KeyError:
self.stats['pools'][pool] = dict(
allocated_capacity_gb=volume_reference.size)
def _run_manage_existing_flow_engine(self, ctxt, volume, ref):
try:
flow_engine = manage_existing.get_flow(
ctxt,
self.db,
self.driver,
self.host,
volume,
ref,
)
except Exception:
msg = _("Failed to create manage_existing flow.")
LOG.exception(msg, resource={'type': 'volume', 'id': volume.id})
raise exception.CinderException(msg)
with flow_utils.DynamicLogListener(flow_engine, logger=LOG):
flow_engine.run()
# Fetch created volume from storage
vol_ref = flow_engine.storage.fetch('volume')
return vol_ref
def _get_cluster_or_host_filters(self):
if self.cluster:
filters = {'cluster_name': self.cluster}
else:
filters = {'host': self.host}
return filters
def _get_my_volumes_summary(self, ctxt):
filters = self._get_cluster_or_host_filters()
return objects.VolumeList.get_volume_summary(ctxt, False, filters)
def _get_my_snapshots_summary(self, ctxt):
filters = self._get_cluster_or_host_filters()
return objects.SnapshotList.get_snapshot_summary(ctxt, False, filters)
def _get_my_resources(self, ctxt, ovo_class_list, limit=None, offset=None):
filters = self._get_cluster_or_host_filters()
return getattr(ovo_class_list, 'get_all')(ctxt, filters=filters,
limit=limit,
offset=offset)
def _get_my_volumes(self, ctxt, limit=None, offset=None):
return self._get_my_resources(ctxt, objects.VolumeList,
limit, offset)
def _get_my_snapshots(self, ctxt, limit=None, offset=None):
return self._get_my_resources(ctxt, objects.SnapshotList,
limit, offset)
def get_manageable_volumes(self, ctxt, marker, limit, offset, sort_keys,
sort_dirs, want_objects=False):
try:
utils.require_driver_initialized(self.driver)
except exception.DriverNotInitialized:
with excutils.save_and_reraise_exception():
LOG.exception("Listing manageable volumes failed, due "
"to uninitialized driver.")
cinder_volumes = self._get_my_volumes(ctxt)
try:
driver_entries = self.driver.get_manageable_volumes(
cinder_volumes, marker, limit, offset, sort_keys, sort_dirs)
if want_objects:
driver_entries = (objects.ManageableVolumeList.
from_primitives(ctxt, driver_entries))
except AttributeError:
LOG.debug('Driver does not support listing manageable volumes.')
return []
except Exception:
with excutils.save_and_reraise_exception():
LOG.exception("Listing manageable volumes failed, due "
"to driver error.")
return driver_entries
def create_group(self, context, group):
"""Creates the group."""
context = context.elevated()
# Make sure the host in the DB matches our own when clustered
self._set_resource_host(group)
status = fields.GroupStatus.AVAILABLE
model_update = None
self._notify_about_group_usage(context, group, "create.start")
try:
utils.require_driver_initialized(self.driver)
LOG.info("Group %s: creating", group.name)
try:
model_update = self.driver.create_group(context, group)
except NotImplementedError:
if not group_types.is_default_cgsnapshot_type(
group.group_type_id):
model_update = self._create_group_generic(context, group)
else:
cg, __ = self._convert_group_to_cg(group, [])
model_update = self.driver.create_consistencygroup(
context, cg)
if model_update:
if (model_update['status'] ==
fields.GroupStatus.ERROR):
msg = (_('Create group failed.'))
LOG.error(msg,
resource={'type': 'group',
'id': group.id})
raise exception.VolumeDriverException(message=msg)
else:
group.update(model_update)
group.save()
except Exception:
with excutils.save_and_reraise_exception():
group.status = fields.GroupStatus.ERROR
group.save()
LOG.error("Group %s: create failed",
group.name)
group.status = status
group.created_at = timeutils.utcnow()
group.save()
LOG.info("Group %s: created successfully", group.name)
self._notify_about_group_usage(context, group, "create.end")
LOG.info("Create group completed successfully.",
resource={'type': 'group',
'id': group.id})
return group
def create_group_from_src(self, context, group,
group_snapshot=None, source_group=None):
"""Creates the group from source.
The source can be a group snapshot or a source group.
"""
source_name = None
snapshots = None
source_vols = None
try:
volumes = objects.VolumeList.get_all_by_generic_group(context,
group.id)
if group_snapshot:
try:
# Check if group_snapshot still exists
group_snapshot.refresh()
except exception.GroupSnapshotNotFound:
LOG.error("Create group from snapshot-%(snap)s failed: "
"SnapshotNotFound.",
{'snap': group_snapshot.id},
resource={'type': 'group',
'id': group.id})
raise
source_name = _("snapshot-%s") % group_snapshot.id
snapshots = objects.SnapshotList.get_all_for_group_snapshot(
context, group_snapshot.id)
for snap in snapshots:
if (snap.status not in
VALID_CREATE_GROUP_SRC_SNAP_STATUS):
msg = (_("Cannot create group "
"%(group)s because snapshot %(snap)s is "
"not in a valid state. Valid states are: "
"%(valid)s.") %
{'group': group.id,
'snap': snap['id'],
'valid': VALID_CREATE_GROUP_SRC_SNAP_STATUS})
raise exception.InvalidGroup(reason=msg)
if source_group:
try:
source_group.refresh()
except exception.GroupNotFound:
LOG.error("Create group "
"from source group-%(group)s failed: "
"GroupNotFound.",
{'group': source_group.id},
resource={'type': 'group',
'id': group.id})
raise
source_name = _("group-%s") % source_group.id
source_vols = objects.VolumeList.get_all_by_generic_group(
context, source_group.id)
for source_vol in source_vols:
if (source_vol.status not in
VALID_CREATE_GROUP_SRC_GROUP_STATUS):
msg = (_("Cannot create group "
"%(group)s because source volume "
"%(source_vol)s is not in a valid "
"state. Valid states are: "
"%(valid)s.") %
{'group': group.id,
'source_vol': source_vol.id,
'valid': VALID_CREATE_GROUP_SRC_GROUP_STATUS})
raise exception.InvalidGroup(reason=msg)
# Sort source snapshots so that they are in the same order as their
# corresponding target volumes.
sorted_snapshots = None
if group_snapshot and snapshots:
sorted_snapshots = self._sort_snapshots(volumes, snapshots)
# Sort source volumes so that they are in the same order as their
# corresponding target volumes.
sorted_source_vols = None
if source_group and source_vols:
sorted_source_vols = self._sort_source_vols(volumes,
source_vols)
self._notify_about_group_usage(
context, group, "create.start")
utils.require_driver_initialized(self.driver)
try:
model_update, volumes_model_update = (
self.driver.create_group_from_src(
context, group, volumes, group_snapshot,
sorted_snapshots, source_group, sorted_source_vols))
except NotImplementedError:
if not group_types.is_default_cgsnapshot_type(
group.group_type_id):
model_update, volumes_model_update = (
self._create_group_from_src_generic(
context, group, volumes, group_snapshot,
sorted_snapshots, source_group,
sorted_source_vols))
else:
cg, volumes = self._convert_group_to_cg(
group, volumes)
cgsnapshot, sorted_snapshots = (
self._convert_group_snapshot_to_cgsnapshot(
group_snapshot, sorted_snapshots, context))
source_cg, sorted_source_vols = (
self._convert_group_to_cg(source_group,
sorted_source_vols))
model_update, volumes_model_update = (
self.driver.create_consistencygroup_from_src(
context, cg, volumes, cgsnapshot,
sorted_snapshots, source_cg, sorted_source_vols))
self._remove_cgsnapshot_id_from_snapshots(sorted_snapshots)
self._remove_consistencygroup_id_from_volumes(volumes)
self._remove_consistencygroup_id_from_volumes(
sorted_source_vols)
if volumes_model_update:
for update in volumes_model_update:
self.db.volume_update(context, update['id'], update)
if model_update:
group.update(model_update)
group.save()
except Exception:
with excutils.save_and_reraise_exception():
group.status = fields.GroupStatus.ERROR
group.save()
LOG.error("Create group "
"from source %(source)s failed.",
{'source': source_name},
resource={'type': 'group',
'id': group.id})
# Update volume status to 'error' as well.
self._remove_consistencygroup_id_from_volumes(volumes)
for vol in volumes:
vol.status = 'error'
vol.save()
now = timeutils.utcnow()
status = 'available'
for vol in volumes:
update = {'status': status, 'created_at': now}
self._update_volume_from_src(context, vol, update, group=group)
self._update_allocated_capacity(vol)
group.status = status
group.created_at = now
group.save()
self._notify_about_group_usage(
context, group, "create.end")
LOG.info("Create group "
"from source-%(source)s completed successfully.",
{'source': source_name},
resource={'type': 'group',
'id': group.id})
return group
def _create_group_from_src_generic(self, context, group, volumes,
group_snapshot=None, snapshots=None,
source_group=None, source_vols=None):
"""Creates a group from source.
:param context: the context of the caller.
:param group: the Group object to be created.
:param volumes: a list of volume objects in the group.
:param group_snapshot: the GroupSnapshot object as source.
:param snapshots: a list of snapshot objects in group_snapshot.
:param source_group: the Group object as source.
:param source_vols: a list of volume objects in the source_group.
:returns: model_update, volumes_model_update
"""
model_update = {'status': 'available'}
volumes_model_update = []
for vol in volumes:
if snapshots:
for snapshot in snapshots:
if vol.snapshot_id == snapshot.id:
vol_model_update = {'id': vol.id}
try:
driver_update = (
self.driver.create_volume_from_snapshot(
vol, snapshot))
if driver_update:
driver_update.pop('id', None)
vol_model_update.update(driver_update)
if 'status' not in vol_model_update:
vol_model_update['status'] = 'available'
except Exception:
vol_model_update['status'] = 'error'
model_update['status'] = 'error'
volumes_model_update.append(vol_model_update)
break
elif source_vols:
for source_vol in source_vols:
if vol.source_volid == source_vol.id:
vol_model_update = {'id': vol.id}
try:
driver_update = self.driver.create_cloned_volume(
vol, source_vol)
if driver_update:
driver_update.pop('id', None)
vol_model_update.update(driver_update)
if 'status' not in vol_model_update:
vol_model_update['status'] = 'available'
except Exception:
vol_model_update['status'] = 'error'
model_update['status'] = 'error'
volumes_model_update.append(vol_model_update)
break
return model_update, volumes_model_update
def _sort_snapshots(self, volumes, snapshots):
# Sort source snapshots so that they are in the same order as their
# corresponding target volumes. Each source snapshot in the snapshots
# list should have a corresponding target volume in the volumes list.
if not volumes or not snapshots or len(volumes) != len(snapshots):
msg = _("Input volumes or snapshots are invalid.")
LOG.error(msg)
raise exception.InvalidInput(reason=msg)
sorted_snapshots = []
for vol in volumes:
found_snaps = [snap for snap in snapshots
if snap['id'] == vol['snapshot_id']]
if not found_snaps:
LOG.error("Source snapshot cannot be found for target "
"volume %(volume_id)s.",
{'volume_id': vol['id']})
raise exception.SnapshotNotFound(
snapshot_id=vol['snapshot_id'])
sorted_snapshots.extend(found_snaps)
return sorted_snapshots
def _sort_source_vols(self, volumes, source_vols):
# Sort source volumes so that they are in the same order as their
# corresponding target volumes. Each source volume in the source_vols
# list should have a corresponding target volume in the volumes list.
if not volumes or not source_vols or len(volumes) != len(source_vols):
msg = _("Input volumes or source volumes are invalid.")
LOG.error(msg)
raise exception.InvalidInput(reason=msg)
sorted_source_vols = []
for vol in volumes:
found_source_vols = [source_vol for source_vol in source_vols
if source_vol['id'] == vol['source_volid']]
if not found_source_vols:
LOG.error("Source volumes cannot be found for target "
"volume %(volume_id)s.",
{'volume_id': vol['id']})
raise exception.VolumeNotFound(
volume_id=vol['source_volid'])
sorted_source_vols.extend(found_source_vols)
return sorted_source_vols
def _update_volume_from_src(self, context, vol, update, group=None):
try:
snapshot_id = vol.get('snapshot_id')
source_volid = vol.get('source_volid')
if snapshot_id:
snapshot = objects.Snapshot.get_by_id(context, snapshot_id)
orig_vref = self.db.volume_get(context,
snapshot.volume_id)
if orig_vref.bootable:
update['bootable'] = True
self.db.volume_glance_metadata_copy_to_volume(
context, vol['id'], snapshot_id)
if source_volid:
source_vol = objects.Volume.get_by_id(context, source_volid)
if source_vol.bootable:
update['bootable'] = True
self.db.volume_glance_metadata_copy_from_volume_to_volume(
context, source_volid, vol['id'])
if source_vol.multiattach:
update['multiattach'] = True
except exception.SnapshotNotFound:
LOG.error("Source snapshot %(snapshot_id)s cannot be found.",
{'snapshot_id': vol['snapshot_id']})
self.db.volume_update(context, vol['id'],
{'status': 'error'})
if group:
group.status = fields.GroupStatus.ERROR
group.save()
raise
except exception.VolumeNotFound:
LOG.error("The source volume %(volume_id)s "
"cannot be found.",
{'volume_id': snapshot.volume_id})
self.db.volume_update(context, vol['id'],
{'status': 'error'})
if group:
group.status = fields.GroupStatus.ERROR
group.save()
raise
except exception.CinderException as ex:
LOG.error("Failed to update %(volume_id)s"
" metadata using the provided snapshot"
" %(snapshot_id)s metadata.",
{'volume_id': vol['id'],
'snapshot_id': vol['snapshot_id']})
self.db.volume_update(context, vol['id'],
{'status': 'error'})
if group:
group.status = fields.GroupStatus.ERROR
group.save()
raise exception.MetadataCopyFailure(reason=six.text_type(ex))
self.db.volume_update(context, vol['id'], update)
def _update_allocated_capacity(self, vol, decrement=False, host=None):
# Update allocated capacity in volume stats
host = host or vol['host']
pool = volume_utils.extract_host(host, 'pool')
if pool is None:
# Legacy volume, put them into default pool
pool = self.driver.configuration.safe_get(
'volume_backend_name') or volume_utils.extract_host(host,
'pool',
True)
vol_size = -vol['size'] if decrement else vol['size']
try:
self.stats['pools'][pool]['allocated_capacity_gb'] += vol_size
except KeyError:
self.stats['pools'][pool] = dict(
allocated_capacity_gb=max(vol_size, 0))
def delete_group(self, context, group):
"""Deletes group and the volumes in the group."""
context = context.elevated()
project_id = group.project_id
if context.project_id != group.project_id:
project_id = group.project_id
else:
project_id = context.project_id
volumes = objects.VolumeList.get_all_by_generic_group(
context, group.id)
for vol_obj in volumes:
if vol_obj.attach_status == "attached":
# Volume is still attached, need to detach first
raise exception.VolumeAttached(volume_id=vol_obj.id)
self._check_is_our_resource(vol_obj)
self._notify_about_group_usage(
context, group, "delete.start")
volumes_model_update = None
model_update = None
try:
utils.require_driver_initialized(self.driver)
try:
model_update, volumes_model_update = (
self.driver.delete_group(context, group, volumes))
except NotImplementedError:
if not group_types.is_default_cgsnapshot_type(
group.group_type_id):
model_update, volumes_model_update = (
self._delete_group_generic(context, group, volumes))
else:
cg, volumes = self._convert_group_to_cg(
group, volumes)
model_update, volumes_model_update = (
self.driver.delete_consistencygroup(context, cg,
volumes))
self._remove_consistencygroup_id_from_volumes(volumes)
if volumes_model_update:
for update in volumes_model_update:
# If we failed to delete a volume, make sure the
# status for the group is set to error as well
if (update['status'] in ['error_deleting', 'error']
and model_update['status'] not in
['error_deleting', 'error']):
model_update['status'] = update['status']
self.db.volumes_update(context, volumes_model_update)
if model_update:
if model_update['status'] in ['error_deleting', 'error']:
msg = (_('Delete group failed.'))
LOG.error(msg,
resource={'type': 'group',
'id': group.id})
raise exception.VolumeDriverException(message=msg)
else:
group.update(model_update)
group.save()
except Exception:
with excutils.save_and_reraise_exception():
group.status = fields.GroupStatus.ERROR
group.save()
# Update volume status to 'error' if driver returns
# None for volumes_model_update.
if not volumes_model_update:
self._remove_consistencygroup_id_from_volumes(volumes)
for vol_obj in volumes:
vol_obj.status = 'error'
vol_obj.save()
# Get reservations for group
try:
reserve_opts = {'groups': -1}
grpreservations = GROUP_QUOTAS.reserve(context,
project_id=project_id,
**reserve_opts)
except Exception:
grpreservations = None
LOG.exception("Delete group "
"failed to update usages.",
resource={'type': 'group',
'id': group.id})
for vol in volumes:
# Get reservations for volume
try:
reserve_opts = {'volumes': -1,
'gigabytes': -vol.size}
QUOTAS.add_volume_type_opts(context,
reserve_opts,
vol.volume_type_id)
reservations = QUOTAS.reserve(context,
project_id=project_id,
**reserve_opts)
except Exception:
reservations = None
LOG.exception("Delete group "
"failed to update usages.",
resource={'type': 'group',
'id': group.id})
vol.destroy()
# Commit the reservations
if reservations:
QUOTAS.commit(context, reservations, project_id=project_id)
self.stats['allocated_capacity_gb'] -= vol.size
if grpreservations:
GROUP_QUOTAS.commit(context, grpreservations,
project_id=project_id)
group.destroy()
self._notify_about_group_usage(
context, group, "delete.end")
self.publish_service_capabilities(context)
LOG.info("Delete group "
"completed successfully.",
resource={'type': 'group',
'id': group.id})
def _convert_group_to_cg(self, group, volumes):
if not group:
return None, None
cg = consistencygroup.ConsistencyGroup()
cg.from_group(group)
for vol in volumes:
vol.consistencygroup_id = vol.group_id
vol.consistencygroup = cg
return cg, volumes
def _remove_consistencygroup_id_from_volumes(self, volumes):
if not volumes:
return
for vol in volumes:
vol.consistencygroup_id = None
vol.consistencygroup = None
def _convert_group_snapshot_to_cgsnapshot(self, group_snapshot, snapshots,
ctxt):
if not group_snapshot:
return None, None
cgsnap = cgsnapshot.CGSnapshot()
cgsnap.from_group_snapshot(group_snapshot)
# Populate consistencygroup object
grp = objects.Group.get_by_id(ctxt, group_snapshot.group_id)
cg, __ = self._convert_group_to_cg(grp, [])
cgsnap.consistencygroup = cg
for snap in snapshots:
snap.cgsnapshot_id = snap.group_snapshot_id
snap.cgsnapshot = cgsnap
return cgsnap, snapshots
def _remove_cgsnapshot_id_from_snapshots(self, snapshots):
if not snapshots:
return
for snap in snapshots:
snap.cgsnapshot_id = None
snap.cgsnapshot = None
def _create_group_generic(self, context, group):
"""Creates a group."""
# A group entry is already created in db. Just returns a status here.
model_update = {'status': fields.GroupStatus.AVAILABLE,
'created_at': timeutils.utcnow()}
return model_update
def _delete_group_generic(self, context, group, volumes):
"""Deletes a group and volumes in the group."""
model_update = {'status': group.status}
volume_model_updates = []
for volume_ref in volumes:
volume_model_update = {'id': volume_ref.id}
try:
self.driver.remove_export(context, volume_ref)
self.driver.delete_volume(volume_ref)
volume_model_update['status'] = 'deleted'
except exception.VolumeIsBusy:
volume_model_update['status'] = 'available'
except Exception:
volume_model_update['status'] = 'error'
model_update['status'] = fields.GroupStatus.ERROR
volume_model_updates.append(volume_model_update)
return model_update, volume_model_updates
def _update_group_generic(self, context, group,
add_volumes=None, remove_volumes=None):
"""Updates a group."""
# NOTE(xyang): The volume manager adds/removes the volume to/from the
# group in the database. This default implementation does not do
# anything in the backend storage.
return None, None, None
def _collect_volumes_for_group(self, context, group, volumes, add=True):
if add:
valid_status = VALID_ADD_VOL_TO_GROUP_STATUS
else:
valid_status = VALID_REMOVE_VOL_FROM_GROUP_STATUS
volumes_ref = []
if not volumes:
return volumes_ref
for add_vol in volumes.split(','):
try:
add_vol_ref = objects.Volume.get_by_id(context, add_vol)
except exception.VolumeNotFound:
LOG.error("Update group "
"failed to %(op)s volume-%(volume_id)s: "
"VolumeNotFound.",
{'volume_id': add_vol,
'op': 'add' if add else 'remove'},
resource={'type': 'group',
'id': group.id})
raise
if add_vol_ref.status not in valid_status:
msg = (_("Can not %(op)s volume %(volume_id)s to "
"group %(group_id)s because volume is in an invalid "
"state: %(status)s. Valid states are: %(valid)s.") %
{'volume_id': add_vol_ref.id,
'group_id': group.id,
'status': add_vol_ref.status,
'valid': valid_status,
'op': 'add' if add else 'remove'})
raise exception.InvalidVolume(reason=msg)
if add:
self._check_is_our_resource(add_vol_ref)
volumes_ref.append(add_vol_ref)
return volumes_ref
def update_group(self, context, group,
add_volumes=None, remove_volumes=None):
"""Updates group.
Update group by adding volumes to the group,
or removing volumes from the group.
"""
add_volumes_ref = self._collect_volumes_for_group(context,
group,
add_volumes,
add=True)
remove_volumes_ref = self._collect_volumes_for_group(context,
group,
remove_volumes,
add=False)
self._notify_about_group_usage(
context, group, "update.start")
try:
utils.require_driver_initialized(self.driver)
try:
model_update, add_volumes_update, remove_volumes_update = (
self.driver.update_group(
context, group,
add_volumes=add_volumes_ref,
remove_volumes=remove_volumes_ref))
except NotImplementedError:
if not group_types.is_default_cgsnapshot_type(
group.group_type_id):
model_update, add_volumes_update, remove_volumes_update = (
self._update_group_generic(
context, group,
add_volumes=add_volumes_ref,
remove_volumes=remove_volumes_ref))
else:
cg, remove_volumes_ref = self._convert_group_to_cg(
group, remove_volumes_ref)
model_update, add_volumes_update, remove_volumes_update = (
self.driver.update_consistencygroup(
context, cg,
add_volumes=add_volumes_ref,
remove_volumes=remove_volumes_ref))
self._remove_consistencygroup_id_from_volumes(
remove_volumes_ref)
volumes_to_update = []
if add_volumes_update:
volumes_to_update.extend(add_volumes_update)
if remove_volumes_update:
volumes_to_update.extend(remove_volumes_update)
self.db.volumes_update(context, volumes_to_update)
if model_update:
if model_update['status'] in (
[fields.GroupStatus.ERROR]):
msg = (_('Error occurred when updating group '
'%s.') % group.id)
LOG.error(msg)
raise exception.VolumeDriverException(message=msg)
group.update(model_update)
group.save()
except Exception as e:
with excutils.save_and_reraise_exception():
if isinstance(e, exception.VolumeDriverException):
LOG.error("Error occurred in the volume driver when "
"updating group %(group_id)s.",
{'group_id': group.id})
else:
LOG.error("Failed to update group %(group_id)s.",
{'group_id': group.id})
group.status = fields.GroupStatus.ERROR
group.save()
for add_vol in add_volumes_ref:
add_vol.status = 'error'
add_vol.save()
for rem_vol in remove_volumes_ref:
if isinstance(e, exception.VolumeDriverException):
rem_vol.consistencygroup_id = None
rem_vol.consistencygroup = None
rem_vol.status = 'error'
rem_vol.save()
for add_vol in add_volumes_ref:
add_vol.group_id = group.id
add_vol.save()
for rem_vol in remove_volumes_ref:
rem_vol.group_id = None
rem_vol.save()
group.status = fields.GroupStatus.AVAILABLE
group.save()
self._notify_about_group_usage(
context, group, "update.end")
LOG.info("Update group completed successfully.",
resource={'type': 'group',
'id': group.id})
def create_group_snapshot(self, context, group_snapshot):
"""Creates the group_snapshot."""
caller_context = context
context = context.elevated()
LOG.info("GroupSnapshot %s: creating.", group_snapshot.id)
snapshots = objects.SnapshotList.get_all_for_group_snapshot(
context, group_snapshot.id)
self._notify_about_group_snapshot_usage(
context, group_snapshot, "create.start")
snapshots_model_update = None
model_update = None
try:
utils.require_driver_initialized(self.driver)
LOG.debug("Group snapshot %(grp_snap_id)s: creating.",
{'grp_snap_id': group_snapshot.id})
# Pass context so that drivers that want to use it, can,
# but it is not a requirement for all drivers.
group_snapshot.context = caller_context
for snapshot in snapshots:
snapshot.context = caller_context
try:
model_update, snapshots_model_update = (
self.driver.create_group_snapshot(context, group_snapshot,
snapshots))
except NotImplementedError:
if not group_types.is_default_cgsnapshot_type(
group_snapshot.group_type_id):
model_update, snapshots_model_update = (
self._create_group_snapshot_generic(
context, group_snapshot, snapshots))
else:
cgsnapshot, snapshots = (
self._convert_group_snapshot_to_cgsnapshot(
group_snapshot, snapshots, context))
model_update, snapshots_model_update = (
self.driver.create_cgsnapshot(context, cgsnapshot,
snapshots))
self._remove_cgsnapshot_id_from_snapshots(snapshots)
if snapshots_model_update:
for snap_model in snapshots_model_update:
# Update db for snapshot.
# NOTE(xyang): snapshots is a list of snapshot objects.
# snapshots_model_update should be a list of dicts.
snap_id = snap_model.pop('id')
snap_obj = objects.Snapshot.get_by_id(context, snap_id)
snap_obj.update(snap_model)
snap_obj.save()
if (snap_model['status'] in [
fields.SnapshotStatus.ERROR_DELETING,
fields.SnapshotStatus.ERROR] and
model_update['status'] not in
[fields.GroupSnapshotStatus.ERROR_DELETING,
fields.GroupSnapshotStatus.ERROR]):
model_update['status'] = snap_model['status']
if model_update:
if model_update['status'] == fields.GroupSnapshotStatus.ERROR:
msg = (_('Error occurred when creating group_snapshot '
'%s.') % group_snapshot.id)
LOG.error(msg)
raise exception.VolumeDriverException(message=msg)
group_snapshot.update(model_update)
group_snapshot.save()
except exception.CinderException:
with excutils.save_and_reraise_exception():
group_snapshot.status = fields.GroupSnapshotStatus.ERROR
group_snapshot.save()
# Update snapshot status to 'error' if driver returns
# None for snapshots_model_update.
self._remove_cgsnapshot_id_from_snapshots(snapshots)
if not snapshots_model_update:
for snapshot in snapshots:
snapshot.status = fields.SnapshotStatus.ERROR
snapshot.save()
for snapshot in snapshots:
volume_id = snapshot.volume_id
snapshot_id = snapshot.id
vol_obj = objects.Volume.get_by_id(context, volume_id)
if vol_obj.bootable:
try:
self.db.volume_glance_metadata_copy_to_snapshot(
context, snapshot_id, volume_id)
except exception.GlanceMetadataNotFound:
# If volume is not created from image, No glance metadata
# would be available for that volume in
# volume glance metadata table
pass
except exception.CinderException as ex:
LOG.error("Failed updating %(snapshot_id)s"
" metadata using the provided volumes"
" %(volume_id)s metadata.",
{'volume_id': volume_id,
'snapshot_id': snapshot_id})
snapshot.status = fields.SnapshotStatus.ERROR
snapshot.save()
raise exception.MetadataCopyFailure(
reason=six.text_type(ex))
snapshot.status = fields.SnapshotStatus.AVAILABLE
snapshot.progress = '100%'
snapshot.save()
group_snapshot.status = fields.GroupSnapshotStatus.AVAILABLE
group_snapshot.save()
LOG.info("group_snapshot %s: created successfully",
group_snapshot.id)
self._notify_about_group_snapshot_usage(
context, group_snapshot, "create.end")
return group_snapshot
def _create_group_snapshot_generic(self, context, group_snapshot,
snapshots):
"""Creates a group_snapshot."""
model_update = {'status': 'available'}
snapshot_model_updates = []
for snapshot in snapshots:
snapshot_model_update = {'id': snapshot.id}
try:
driver_update = self.driver.create_snapshot(snapshot)
if driver_update:
driver_update.pop('id', None)
snapshot_model_update.update(driver_update)
if 'status' not in snapshot_model_update:
snapshot_model_update['status'] = (
fields.SnapshotStatus.AVAILABLE)
except Exception:
snapshot_model_update['status'] = (
fields.SnapshotStatus.ERROR)
model_update['status'] = 'error'
snapshot_model_updates.append(snapshot_model_update)
return model_update, snapshot_model_updates
def _delete_group_snapshot_generic(self, context, group_snapshot,
snapshots):
"""Deletes a group_snapshot."""
model_update = {'status': group_snapshot.status}
snapshot_model_updates = []
for snapshot in snapshots:
snapshot_model_update = {'id': snapshot.id}
try:
self.driver.delete_snapshot(snapshot)
snapshot_model_update['status'] = (
fields.SnapshotStatus.DELETED)
except exception.SnapshotIsBusy:
snapshot_model_update['status'] = (
fields.SnapshotStatus.AVAILABLE)
except Exception:
snapshot_model_update['status'] = (
fields.SnapshotStatus.ERROR)
model_update['status'] = 'error'
snapshot_model_updates.append(snapshot_model_update)
return model_update, snapshot_model_updates
def delete_group_snapshot(self, context, group_snapshot):
"""Deletes group_snapshot."""
caller_context = context
context = context.elevated()
project_id = group_snapshot.project_id
LOG.info("group_snapshot %s: deleting", group_snapshot.id)
snapshots = objects.SnapshotList.get_all_for_group_snapshot(
context, group_snapshot.id)
self._notify_about_group_snapshot_usage(
context, group_snapshot, "delete.start")
snapshots_model_update = None
model_update = None
try:
utils.require_driver_initialized(self.driver)
LOG.debug("group_snapshot %(grp_snap_id)s: deleting",
{'grp_snap_id': group_snapshot.id})
# Pass context so that drivers that want to use it, can,
# but it is not a requirement for all drivers.
group_snapshot.context = caller_context
for snapshot in snapshots:
snapshot.context = caller_context
try:
model_update, snapshots_model_update = (
self.driver.delete_group_snapshot(context, group_snapshot,
snapshots))
except NotImplementedError:
if not group_types.is_default_cgsnapshot_type(
group_snapshot.group_type_id):
model_update, snapshots_model_update = (
self._delete_group_snapshot_generic(
context, group_snapshot, snapshots))
else:
cgsnapshot, snapshots = (
self._convert_group_snapshot_to_cgsnapshot(
group_snapshot, snapshots, context))
model_update, snapshots_model_update = (
self.driver.delete_cgsnapshot(context, cgsnapshot,
snapshots))
self._remove_cgsnapshot_id_from_snapshots(snapshots)
if snapshots_model_update:
for snap_model in snapshots_model_update:
# NOTE(xyang): snapshots is a list of snapshot objects.
# snapshots_model_update should be a list of dicts.
snap = next((item for item in snapshots if
item.id == snap_model['id']), None)
if snap:
snap_model.pop('id')
snap.update(snap_model)
snap.save()
if (snap_model['status'] in
[fields.SnapshotStatus.ERROR_DELETING,
fields.SnapshotStatus.ERROR] and
model_update['status'] not in
['error_deleting', 'error']):
model_update['status'] = snap_model['status']
if model_update:
if model_update['status'] in ['error_deleting', 'error']:
msg = (_('Error occurred when deleting group_snapshot '
'%s.') % group_snapshot.id)
LOG.error(msg)
raise exception.VolumeDriverException(message=msg)
else:
group_snapshot.update(model_update)
group_snapshot.save()
except exception.CinderException:
with excutils.save_and_reraise_exception():
group_snapshot.status = fields.GroupSnapshotStatus.ERROR
group_snapshot.save()
# Update snapshot status to 'error' if driver returns
# None for snapshots_model_update.
if not snapshots_model_update:
self._remove_cgsnapshot_id_from_snapshots(snapshots)
for snapshot in snapshots:
snapshot.status = fields.SnapshotStatus.ERROR
snapshot.save()
for snapshot in snapshots:
# Get reservations
try:
reserve_opts = {'snapshots': -1}
if not CONF.no_snapshot_gb_quota:
reserve_opts['gigabytes'] = -snapshot.volume_size
volume_ref = objects.Volume.get_by_id(context,
snapshot.volume_id)
QUOTAS.add_volume_type_opts(context,
reserve_opts,
volume_ref.volume_type_id)
reservations = QUOTAS.reserve(context,
project_id=project_id,
**reserve_opts)
except Exception:
reservations = None
LOG.exception("Failed to update usages deleting snapshot")
self.db.volume_glance_metadata_delete_by_snapshot(context,
snapshot.id)
snapshot.destroy()
# Commit the reservations
if reservations:
QUOTAS.commit(context, reservations, project_id=project_id)
group_snapshot.destroy()
LOG.info("group_snapshot %s: deleted successfully",
group_snapshot.id)
self._notify_about_group_snapshot_usage(context, group_snapshot,
"delete.end",
snapshots)
def update_migrated_volume(self, ctxt, volume, new_volume, volume_status):
"""Finalize migration process on backend device."""
model_update = None
model_update_default = {'_name_id': new_volume.name_id,
'provider_location':
new_volume.provider_location}
try:
model_update = self.driver.update_migrated_volume(ctxt,
volume,
new_volume,
volume_status)
except NotImplementedError:
# If update_migrated_volume is not implemented for the driver,
# _name_id and provider_location will be set with the values
# from new_volume.
model_update = model_update_default
if model_update:
model_update_default.update(model_update)
# Swap keys that were changed in the source so we keep their values
# in the temporary volume's DB record.
# Need to convert 'metadata' and 'admin_metadata' since
# they are not keys of volume, their corresponding keys are
# 'volume_metadata' and 'volume_admin_metadata'.
model_update_new = dict()
for key in model_update:
if key == 'metadata':
if volume.get('volume_metadata'):
model_update_new[key] = {
metadata['key']: metadata['value']
for metadata in volume.volume_metadata}
elif key == 'admin_metadata':
model_update_new[key] = {
metadata['key']: metadata['value']
for metadata in volume.volume_admin_metadata}
else:
model_update_new[key] = volume[key]
with new_volume.obj_as_admin():
new_volume.update(model_update_new)
new_volume.save()
with volume.obj_as_admin():
volume.update(model_update_default)
volume.save()
# Replication V2.1 and a/a method
def failover(self, context, secondary_backend_id=None):
"""Failover a backend to a secondary replication target.
Instructs a replication capable/configured backend to failover
to one of it's secondary replication targets. host=None is
an acceetable input, and leaves it to the driver to failover
to the only configured target, or to choose a target on it's
own. All of the hosts volumes will be passed on to the driver
in order for it to determine the replicated volumes on the host,
if needed.
:param context: security context
:param secondary_backend_id: Specifies backend_id to fail over to
"""
updates = {}
repl_status = fields.ReplicationStatus
service = self._get_service()
# TODO(geguileo): We should optimize these updates by doing them
# directly on the DB with just 3 queries, one to change the volumes
# another to change all the snapshots, and another to get replicated
# volumes.
# Change non replicated volumes and their snapshots to error if we are
# failing over, leave them as they are for failback
volumes = self._get_my_volumes(context)
replicated_vols = []
for volume in volumes:
if volume.replication_status not in (repl_status.DISABLED,
repl_status.NOT_CAPABLE):
replicated_vols.append(volume)
elif secondary_backend_id != self.FAILBACK_SENTINEL:
volume.previous_status = volume.status
volume.status = 'error'
volume.replication_status = repl_status.NOT_CAPABLE
volume.save()
for snapshot in volume.snapshots:
snapshot.status = fields.SnapshotStatus.ERROR
snapshot.save()
volume_update_list = None
group_update_list = None
try:
# For non clustered we can call v2.1 failover_host, but for
# clustered we call a/a failover method. We know a/a method
# exists because BaseVD class wouldn't have started if it didn't.
failover = getattr(self.driver,
'failover' if service.is_clustered
else 'failover_host')
# expected form of volume_update_list:
# [{volume_id: <cinder-volid>, updates: {'provider_id': xxxx....}},
# {volume_id: <cinder-volid>, updates: {'provider_id': xxxx....}}]
# It includes volumes in replication groups and those not in them
# expected form of group_update_list:
# [{group_id: <cinder-grpid>, updates: {'xxxx': xxxx....}},
# {group_id: <cinder-grpid>, updates: {'xxxx': xxxx....}}]
filters = self._get_cluster_or_host_filters()
groups = objects.GroupList.get_all_replicated(context,
filters=filters)
active_backend_id, volume_update_list, group_update_list = (
failover(context,
replicated_vols,
secondary_id=secondary_backend_id,
groups=groups))
try:
update_data = {u['volume_id']: u['updates']
for u in volume_update_list}
except KeyError:
msg = "Update list, doesn't include volume_id"
raise exception.ProgrammingError(reason=msg)
try:
update_group_data = {g['group_id']: g['updates']
for g in group_update_list}
except KeyError:
msg = "Update list, doesn't include group_id"
raise exception.ProgrammingError(reason=msg)
except Exception as exc:
# NOTE(jdg): Drivers need to be aware if they fail during
# a failover sequence, we're expecting them to cleanup
# and make sure the driver state is such that the original
# backend is still set as primary as per driver memory
# We don't want to log the exception trace invalid replication
# target
if isinstance(exc, exception.InvalidReplicationTarget):
log_method = LOG.error
# Preserve the replication_status: Status should be failed over
# if we were failing back or if we were failing over from one
# secondary to another secondary. In both cases
# active_backend_id will be set.
if service.active_backend_id:
updates['replication_status'] = repl_status.FAILED_OVER
else:
updates['replication_status'] = repl_status.ENABLED
else:
log_method = LOG.exception
updates.update(disabled=True,
replication_status=repl_status.FAILOVER_ERROR)
log_method("Error encountered during failover on host: %(host)s "
"to %(backend_id)s: %(error)s",
{'host': self.host, 'backend_id': secondary_backend_id,
'error': exc})
# We dump the update list for manual recovery
LOG.error('Failed update_list is: %s', volume_update_list)
self.finish_failover(context, service, updates)
return
if secondary_backend_id == "default":
updates['replication_status'] = repl_status.ENABLED
updates['active_backend_id'] = ''
updates['disabled'] = service.frozen
updates['disabled_reason'] = 'frozen' if service.frozen else ''
else:
updates['replication_status'] = repl_status.FAILED_OVER
updates['active_backend_id'] = active_backend_id
updates['disabled'] = True
updates['disabled_reason'] = 'failed-over'
self.finish_failover(context, service, updates)
for volume in replicated_vols:
update = update_data.get(volume.id, {})
if update.get('status', '') == 'error':
update['replication_status'] = repl_status.FAILOVER_ERROR
elif update.get('replication_status') in (None,
repl_status.FAILED_OVER):
update['replication_status'] = updates['replication_status']
if update['replication_status'] == repl_status.FAILOVER_ERROR:
update.setdefault('status', 'error')
# Set all volume snapshots to error
for snapshot in volume.snapshots:
snapshot.status = fields.SnapshotStatus.ERROR
snapshot.save()
if 'status' in update:
update['previous_status'] = volume.status
volume.update(update)
volume.save()
for grp in groups:
update = update_group_data.get(grp.id, {})
if update.get('status', '') == 'error':
update['replication_status'] = repl_status.FAILOVER_ERROR
elif update.get('replication_status') in (None,
repl_status.FAILED_OVER):
update['replication_status'] = updates['replication_status']
if update['replication_status'] == repl_status.FAILOVER_ERROR:
update.setdefault('status', 'error')
grp.update(update)
grp.save()
LOG.info("Failed over to replication target successfully.")
# TODO(geguileo): In P - remove this
failover_host = failover
def finish_failover(self, context, service, updates):
"""Completion of the failover locally or via RPC."""
# If the service is clustered, broadcast the service changes to all
# volume services, including this one.
if service.is_clustered:
# We have to update the cluster with the same data, and we do it
# before broadcasting the failover_completed RPC call to prevent
# races with services that may be starting..
for key, value in updates.items():
setattr(service.cluster, key, value)
service.cluster.save()
rpcapi = volume_rpcapi.VolumeAPI()
rpcapi.failover_completed(context, service, updates)
else:
service.update(updates)
service.save()
def failover_completed(self, context, updates):
"""Finalize failover of this backend.
When a service is clustered and replicated the failover has 2 stages,
one that does the failover of the volumes and another that finalizes
the failover of the services themselves.
This method takes care of the last part and is called from the service
doing the failover of the volumes after finished processing the
volumes.
"""
service = self._get_service()
service.update(updates)
try:
self.driver.failover_completed(context, service.active_backend_id)
except Exception:
msg = _('Driver reported error during replication failover '
'completion.')
LOG.exception(msg)
service.disabled = True
service.disabled_reason = msg
service.replication_status = (
fields.ReplicationStatus.ERROR)
service.save()
def freeze_host(self, context):
"""Freeze management plane on this backend.
Basically puts the control/management plane into a
Read Only state. We should handle this in the scheduler,
however this is provided to let the driver know in case it
needs/wants to do something specific on the backend.
:param context: security context
"""
# TODO(jdg): Return from driver? or catch?
# Update status column in service entry
try:
self.driver.freeze_backend(context)
except exception.VolumeDriverException:
# NOTE(jdg): In the case of freeze, we don't really
# need the backend's consent or anything, we'll just
# disable the service, so we can just log this and
# go about our business
LOG.warning('Error encountered on Cinder backend during '
'freeze operation, service is frozen, however '
'notification to driver has failed.')
service = self._get_service()
service.disabled = True
service.disabled_reason = "frozen"
service.save()
LOG.info("Set backend status to frozen successfully.")
return True
def thaw_host(self, context):
"""UnFreeze management plane on this backend.
Basically puts the control/management plane back into
a normal state. We should handle this in the scheduler,
however this is provided to let the driver know in case it
needs/wants to do something specific on the backend.
:param context: security context
"""
# TODO(jdg): Return from driver? or catch?
# Update status column in service entry
try:
self.driver.thaw_backend(context)
except exception.VolumeDriverException:
# NOTE(jdg): Thaw actually matters, if this call
# to the backend fails, we're stuck and can't re-enable
LOG.error('Error encountered on Cinder backend during '
'thaw operation, service will remain frozen.')
return False
service = self._get_service()
service.disabled = False
service.disabled_reason = ""
service.save()
LOG.info("Thawed backend successfully.")
return True
def manage_existing_snapshot(self, ctxt, snapshot, ref=None):
LOG.debug('manage_existing_snapshot: managing %s.', ref)
try:
flow_engine = manage_existing_snapshot.get_flow(
ctxt,
self.db,
self.driver,
self.host,
snapshot.id,
ref)
except Exception:
LOG.exception("Failed to create manage_existing flow: "
"%(object_type)s %(object_id)s.",
{'object_type': 'snapshot',
'object_id': snapshot.id})
raise exception.CinderException(
_("Failed to create manage existing flow."))
with flow_utils.DynamicLogListener(flow_engine, logger=LOG):
flow_engine.run()
return snapshot.id
def get_manageable_snapshots(self, ctxt, marker, limit, offset,
sort_keys, sort_dirs, want_objects=False):
try:
utils.require_driver_initialized(self.driver)
except exception.DriverNotInitialized:
with excutils.save_and_reraise_exception():
LOG.exception("Listing manageable snapshots failed, due "
"to uninitialized driver.")
cinder_snapshots = self._get_my_snapshots(ctxt)
try:
driver_entries = self.driver.get_manageable_snapshots(
cinder_snapshots, marker, limit, offset, sort_keys, sort_dirs)
if want_objects:
driver_entries = (objects.ManageableSnapshotList.
from_primitives(ctxt, driver_entries))
except AttributeError:
LOG.debug('Driver does not support listing manageable snapshots.')
return []
except Exception:
with excutils.save_and_reraise_exception():
LOG.exception("Listing manageable snapshots failed, due "
"to driver error.")
return driver_entries
def get_capabilities(self, context, discover):
"""Get capabilities of backend storage."""
if discover:
self.driver.init_capabilities()
capabilities = self.driver.capabilities
LOG.debug("Obtained capabilities list: %s.", capabilities)
return capabilities
@utils.trace
def get_backup_device(self, ctxt, backup, want_objects=False,
async_call=False):
try:
(backup_device, is_snapshot) = (
self.driver.get_backup_device(ctxt, backup))
except Exception as ex:
if async_call:
LOG.exception("Failed to get backup device. "
"Calling backup continue_backup to cleanup")
rpcapi = backup_rpcapi.BackupAPI()
rpcapi.continue_backup(ctxt, backup, backup_device=None)
return
else:
while excutils.save_and_reraise_exception():
LOG.exception("Failed to get backup device.")
secure_enabled = self.driver.secure_file_operations_enabled()
backup_device_dict = {'backup_device': backup_device,
'secure_enabled': secure_enabled,
'is_snapshot': is_snapshot, }
# TODO(sborkows): from_primitive method will be removed in O, so there
# is a need to clean here then.
backup_device = (
objects.BackupDeviceInfo.from_primitive(backup_device_dict, ctxt)
if want_objects else backup_device_dict)
if async_call:
# we have to use an rpc call back to the backup manager to
# continue the backup
LOG.info("Calling backup continue_backup for: {}".format(backup))
rpcapi = backup_rpcapi.BackupAPI()
rpcapi.continue_backup(ctxt, backup, backup_device)
else:
# The rpc api version doesn't support the async callback
# so we fallback to returning the value itself.
return backup_device
def secure_file_operations_enabled(self, ctxt, volume):
secure_enabled = self.driver.secure_file_operations_enabled()
return secure_enabled
def _connection_create(self, ctxt, volume, attachment, connector):
try:
self.driver.validate_connector(connector)
except exception.InvalidConnectorException as err:
raise exception.InvalidInput(reason=six.text_type(err))
except Exception as err:
err_msg = (_("Validate volume connection failed "
"(error: %(err)s).") % {'err': six.text_type(err)})
LOG.error(err_msg, resource=volume)
raise exception.VolumeBackendAPIException(data=err_msg)
try:
model_update = self.driver.create_export(ctxt.elevated(),
volume, connector)
except exception.CinderException as ex:
err_msg = (_("Create export for volume failed (%s).") % ex.msg)
LOG.exception(err_msg, resource=volume)
raise exception.VolumeBackendAPIException(data=err_msg)
try:
if model_update:
volume.update(model_update)
volume.save()
except exception.CinderException as ex:
LOG.exception("Model update failed.", resource=volume)
raise exception.ExportFailure(reason=six.text_type(ex))
try:
conn_info = self.driver.initialize_connection(volume, connector)
except exception.ConnectorRejected:
with excutils.save_and_reraise_exception():
LOG.info("The connector was rejected by the volume driver.")
except Exception as err:
err_msg = (_("Driver initialize connection failed "
"(error: %(err)s).") % {'err': six.text_type(err)})
LOG.exception(err_msg, resource=volume)
self.driver.remove_export(ctxt.elevated(), volume)
raise exception.VolumeBackendAPIException(data=err_msg)
conn_info = self._parse_connection_options(ctxt, volume, conn_info)
# NOTE(jdg): Get rid of the nested dict (data key)
conn_data = conn_info.pop('data', {})
connection_info = conn_data.copy()
connection_info.update(conn_info)
values = {'volume_id': volume.id,
'attach_status': 'attaching',
'connector': jsonutils.dumps(connector)}
# TODO(mriedem): Use VolumeAttachment.save() here.
self.db.volume_attachment_update(ctxt, attachment.id, values)
connection_info['attachment_id'] = attachment.id
return connection_info
def attachment_update(self,
context,
vref,
connector,
attachment_id):
"""Update/Finalize an attachment.
This call updates a valid attachment record to associate with a volume
and provide the caller with the proper connection info. Note that
this call requires an `attachment_ref`. It's expected that prior to
this call that the volume and an attachment UUID has been reserved.
param: vref: Volume object to create attachment for
param: connector: Connector object to use for attachment creation
param: attachment_ref: ID of the attachment record to update
"""
mode = connector.get('mode', 'rw')
self._notify_about_volume_usage(context, vref, 'attach.start')
attachment_ref = objects.VolumeAttachment.get_by_id(context,
attachment_id)
# Check to see if a mode parameter was set during attachment-create;
# this seems kinda wonky, but it's how we're keeping back compatability
# with the use of connector.mode for now. In other words, we're
# making sure we still honor ro settings from the connector but
# we override that if a value was specified in attachment-create
if attachment_ref.attach_mode != 'null':
mode = attachment_ref.attach_mode
connector['mode'] = mode
connection_info = self._connection_create(context,
vref,
attachment_ref,
connector)
try:
utils.require_driver_initialized(self.driver)
self.driver.attach_volume(context,
vref,
attachment_ref.instance_uuid,
connector.get('host', ''),
connector.get('mountpoint', 'na'))
except Exception as err:
self.message_api.create(
context, message_field.Action.UPDATE_ATTACHMENT,
resource_uuid=vref.id,
exception=err)
with excutils.save_and_reraise_exception():
self.db.volume_attachment_update(
context, attachment_ref.id,
{'attach_status':
fields.VolumeAttachStatus.ERROR_ATTACHING})
self.db.volume_attached(context.elevated(),
attachment_ref.id,
attachment_ref.instance_uuid,
connector.get('host', ''),
connector.get('mountpoint', 'na'),
mode,
False)
vref.refresh()
attachment_ref.refresh()
LOG.info("attachment_update completed successfully.",
resource=vref)
return connection_info
def _connection_terminate(self, context, volume,
attachment, force=False):
"""Remove a volume connection, but leave attachment.
Exits early if the attachment does not have a connector and returns
None to indicate shared connections are irrelevant.
"""
utils.require_driver_initialized(self.driver)
connector = attachment.connector
if not connector and not force:
# It's possible to attach a volume to a shelved offloaded server
# in nova, and a shelved offloaded server is not on a compute host,
# which means the attachment was made without a host connector,
# so if we don't have a connector we can't terminate a connection
# that was never actually made to the storage backend, so just
# log a message and exit.
LOG.debug('No connector for attachment %s; skipping storage '
'backend terminate_connection call.', attachment.id)
# None indicates we don't know and don't care.
return None
try:
shared_connections = self.driver.terminate_connection(volume,
connector,
force=force)
if not isinstance(shared_connections, bool):
shared_connections = False
except Exception as err:
err_msg = (_('Terminate volume connection failed: %(err)s')
% {'err': six.text_type(err)})
LOG.exception(err_msg, resource=volume)
raise exception.VolumeBackendAPIException(data=err_msg)
LOG.info("Terminate volume connection completed successfully.",
resource=volume)
# NOTE(jdg): Return True/False if there are other outstanding
# attachments that share this connection. If True should signify
# caller to preserve the actual host connection (work should be
# done in the brick connector as it has the knowledge of what's
# going on here.
return shared_connections
def attachment_delete(self, context, attachment_id, vref):
"""Delete/Detach the specified attachment.
Notifies the backend device that we're detaching the specified
attachment instance.
param: vref: Volume object associated with the attachment
param: attachment: Attachment reference object to remove
NOTE if the attachment reference is None, we remove all existing
attachments for the specified volume object.
"""
attachment_ref = objects.VolumeAttachment.get_by_id(context,
attachment_id)
if not attachment_ref:
for attachment in VA_LIST.get_all_by_volume_id(context, vref.id):
self._do_attachment_delete(context, vref, attachment)
else:
self._do_attachment_delete(context, vref, attachment_ref)
def _do_attachment_delete(self, context, vref, attachment):
utils.require_driver_initialized(self.driver)
self._notify_about_volume_usage(context, vref, "detach.start")
has_shared_connection = self._connection_terminate(context,
vref,
attachment)
try:
LOG.debug('Deleting attachment %(attachment_id)s.',
{'attachment_id': attachment.id},
resource=vref)
self.driver.detach_volume(context, vref, attachment)
if has_shared_connection is not None and not has_shared_connection:
self.driver.remove_export(context.elevated(), vref)
except Exception:
# FIXME(jdg): Obviously our volume object is going to need some
# changes to deal with multi-attach and figuring out how to
# represent a single failed attach out of multiple attachments
# TODO(jdg): object method here
self.db.volume_attachment_update(
context, attachment.get('id'),
{'attach_status': fields.VolumeAttachStatus.ERROR_DETACHING})
else:
self.db.volume_detached(context.elevated(), vref.id,
attachment.get('id'))
self.db.volume_admin_metadata_delete(context.elevated(),
vref.id,
'attached_mode')
self._notify_about_volume_usage(context, vref, "detach.end")
# Replication group API (Tiramisu)
def enable_replication(self, ctxt, group):
"""Enable replication."""
group.refresh()
if group.replication_status != fields.ReplicationStatus.ENABLING:
msg = _("Replication status in group %s is not "
"enabling. Cannot enable replication.") % group.id
LOG.error(msg)
raise exception.InvalidGroup(reason=msg)
volumes = group.volumes
for vol in volumes:
vol.refresh()
if vol.replication_status != fields.ReplicationStatus.ENABLING:
msg = _("Replication status in volume %s is not "
"enabling. Cannot enable replication.") % vol.id
LOG.error(msg)
raise exception.InvalidVolume(reason=msg)
self._notify_about_group_usage(
ctxt, group, "enable_replication.start")
volumes_model_update = None
model_update = None
try:
utils.require_driver_initialized(self.driver)
model_update, volumes_model_update = (
self.driver.enable_replication(ctxt, group, volumes))
if volumes_model_update:
for update in volumes_model_update:
vol_obj = objects.Volume.get_by_id(ctxt, update['id'])
vol_obj.update(update)
vol_obj.save()
# If we failed to enable a volume, make sure the status
# for the group is set to error as well
if (update.get('replication_status') ==
fields.ReplicationStatus.ERROR and
model_update.get('replication_status') !=
fields.ReplicationStatus.ERROR):
model_update['replication_status'] = update.get(
'replication_status')
if model_update:
if (model_update.get('replication_status') ==
fields.ReplicationStatus.ERROR):
msg = _('Enable replication failed.')
LOG.error(msg,
resource={'type': 'group',
'id': group.id})
raise exception.VolumeDriverException(message=msg)
else:
group.update(model_update)
group.save()
except exception.CinderException as ex:
group.status = fields.GroupStatus.ERROR
group.replication_status = fields.ReplicationStatus.ERROR
group.save()
# Update volume status to 'error' if driver returns
# None for volumes_model_update.
if not volumes_model_update:
for vol in volumes:
vol.status = 'error'
vol.replication_status = fields.ReplicationStatus.ERROR
vol.save()
err_msg = _("Enable replication group failed: "
"%s.") % six.text_type(ex)
raise exception.ReplicationGroupError(reason=err_msg,
group_id=group.id)
for vol in volumes:
vol.replication_status = fields.ReplicationStatus.ENABLED
vol.save()
group.replication_status = fields.ReplicationStatus.ENABLED
group.save()
self._notify_about_group_usage(
ctxt, group, "enable_replication.end", volumes)
LOG.info("Enable replication completed successfully.",
resource={'type': 'group',
'id': group.id})
# Replication group API (Tiramisu)
def disable_replication(self, ctxt, group):
"""Disable replication."""
group.refresh()
if group.replication_status != fields.ReplicationStatus.DISABLING:
msg = _("Replication status in group %s is not "
"disabling. Cannot disable replication.") % group.id
LOG.error(msg)
raise exception.InvalidGroup(reason=msg)
volumes = group.volumes
for vol in volumes:
vol.refresh()
if (vol.replication_status !=
fields.ReplicationStatus.DISABLING):
msg = _("Replication status in volume %s is not "
"disabling. Cannot disable replication.") % vol.id
LOG.error(msg)
raise exception.InvalidVolume(reason=msg)
self._notify_about_group_usage(
ctxt, group, "disable_replication.start")
volumes_model_update = None
model_update = None
try:
utils.require_driver_initialized(self.driver)
model_update, volumes_model_update = (
self.driver.disable_replication(ctxt, group, volumes))
if volumes_model_update:
for update in volumes_model_update:
vol_obj = objects.Volume.get_by_id(ctxt, update['id'])
vol_obj.update(update)
vol_obj.save()
# If we failed to enable a volume, make sure the status
# for the group is set to error as well
if (update.get('replication_status') ==
fields.ReplicationStatus.ERROR and
model_update.get('replication_status') !=
fields.ReplicationStatus.ERROR):
model_update['replication_status'] = update.get(
'replication_status')
if model_update:
if (model_update.get('replication_status') ==
fields.ReplicationStatus.ERROR):
msg = _('Disable replication failed.')
LOG.error(msg,
resource={'type': 'group',
'id': group.id})
raise exception.VolumeDriverException(message=msg)
else:
group.update(model_update)
group.save()
except exception.CinderException as ex:
group.status = fields.GroupStatus.ERROR
group.replication_status = fields.ReplicationStatus.ERROR
group.save()
# Update volume status to 'error' if driver returns
# None for volumes_model_update.
if not volumes_model_update:
for vol in volumes:
vol.status = 'error'
vol.replication_status = fields.ReplicationStatus.ERROR
vol.save()
err_msg = _("Disable replication group failed: "
"%s.") % six.text_type(ex)
raise exception.ReplicationGroupError(reason=err_msg,
group_id=group.id)
for vol in volumes:
vol.replication_status = fields.ReplicationStatus.DISABLED
vol.save()
group.replication_status = fields.ReplicationStatus.DISABLED
group.save()
self._notify_about_group_usage(
ctxt, group, "disable_replication.end", volumes)
LOG.info("Disable replication completed successfully.",
resource={'type': 'group',
'id': group.id})
# Replication group API (Tiramisu)
def failover_replication(self, ctxt, group, allow_attached_volume=False,
secondary_backend_id=None):
"""Failover replication."""
group.refresh()
if group.replication_status != fields.ReplicationStatus.FAILING_OVER:
msg = _("Replication status in group %s is not "
"failing-over. Cannot failover replication.") % group.id
LOG.error(msg)
raise exception.InvalidGroup(reason=msg)
volumes = group.volumes
for vol in volumes:
vol.refresh()
if vol.status == 'in-use' and not allow_attached_volume:
msg = _("Volume %s is attached but allow_attached_volume flag "
"is False. Cannot failover replication.") % vol.id
LOG.error(msg)
raise exception.InvalidVolume(reason=msg)
if (vol.replication_status !=
fields.ReplicationStatus.FAILING_OVER):
msg = _("Replication status in volume %s is not "
"failing-over. Cannot failover replication.") % vol.id
LOG.error(msg)
raise exception.InvalidVolume(reason=msg)
self._notify_about_group_usage(
ctxt, group, "failover_replication.start")
volumes_model_update = None
model_update = None
try:
utils.require_driver_initialized(self.driver)
model_update, volumes_model_update = (
self.driver.failover_replication(
ctxt, group, volumes, secondary_backend_id))
if volumes_model_update:
for update in volumes_model_update:
vol_obj = objects.Volume.get_by_id(ctxt, update['id'])
vol_obj.update(update)
vol_obj.save()
# If we failed to enable a volume, make sure the status
# for the group is set to error as well
if (update.get('replication_status') ==
fields.ReplicationStatus.ERROR and
model_update.get('replication_status') !=
fields.ReplicationStatus.ERROR):
model_update['replication_status'] = update.get(
'replication_status')
if model_update:
if (model_update.get('replication_status') ==
fields.ReplicationStatus.ERROR):
msg = _('Failover replication failed.')
LOG.error(msg,
resource={'type': 'group',
'id': group.id})
raise exception.VolumeDriverException(message=msg)
else:
group.update(model_update)
group.save()
except exception.CinderException as ex:
group.status = fields.GroupStatus.ERROR
group.replication_status = fields.ReplicationStatus.ERROR
group.save()
# Update volume status to 'error' if driver returns
# None for volumes_model_update.
if not volumes_model_update:
for vol in volumes:
vol.status = 'error'
vol.replication_status = fields.ReplicationStatus.ERROR
vol.save()
err_msg = _("Failover replication group failed: "
"%s.") % six.text_type(ex)
raise exception.ReplicationGroupError(reason=err_msg,
group_id=group.id)
for vol in volumes:
if secondary_backend_id == "default":
vol.replication_status = fields.ReplicationStatus.ENABLED
else:
vol.replication_status = (
fields.ReplicationStatus.FAILED_OVER)
vol.save()
if secondary_backend_id == "default":
group.replication_status = fields.ReplicationStatus.ENABLED
else:
group.replication_status = fields.ReplicationStatus.FAILED_OVER
group.save()
self._notify_about_group_usage(
ctxt, group, "failover_replication.end", volumes)
LOG.info("Failover replication completed successfully.",
resource={'type': 'group',
'id': group.id})
def list_replication_targets(self, ctxt, group):
"""Provide a means to obtain replication targets for a group.
This method is used to find the replication_device config
info. 'backend_id' is a required key in 'replication_device'.
Response Example for admin:
.. code:: json
{
"replication_targets": [
{
"backend_id": "vendor-id-1",
"unique_key": "val1"
},
{
"backend_id": "vendor-id-2",
"unique_key": "val2"
}
]
}
Response example for non-admin:
.. code:: json
{
"replication_targets": [
{
"backend_id": "vendor-id-1"
},
{
"backend_id": "vendor-id-2"
}
]
}
"""
replication_targets = []
try:
group.refresh()
if self.configuration.replication_device:
if ctxt.is_admin:
for rep_dev in self.configuration.replication_device:
keys = rep_dev.keys()
dev = {}
for k in keys:
dev[k] = rep_dev[k]
replication_targets.append(dev)
else:
for rep_dev in self.configuration.replication_device:
dev = rep_dev.get('backend_id')
if dev:
replication_targets.append({'backend_id': dev})
except exception.GroupNotFound:
err_msg = (_("Get replication targets failed. Group %s not "
"found.") % group.id)
LOG.exception(err_msg)
raise exception.VolumeBackendAPIException(data=err_msg)
return {'replication_targets': replication_targets}
|
_do_cleanup
|
index.js
|
import * as C from './constant'
import U from './utils'
import en from './locale/en'
let L = 'en' // global locale
const Ls = {} // global loaded locale
Ls[L] = en
const isDayjs = d => d instanceof Dayjs // eslint-disable-line no-use-before-define
const parseLocale = (preset, object, isLocal) => {
let l
if (!preset) return L
if (typeof preset === 'string') {
if (Ls[preset]) {
l = preset
}
if (object) {
Ls[preset] = object
l = preset
}
} else {
const { name } = preset
Ls[name] = preset
l = name
}
if (!isLocal && l) L = l
return l || (!isLocal && L)
}
const dayjs = (date, c, pl) => {
if (isDayjs(date)) {
return date.clone()
}
// eslint-disable-next-line no-nested-ternary
const cfg = c ? (typeof c === 'string' ? { format: c, pl } : c) : {}
cfg.date = date
return new Dayjs(cfg) // eslint-disable-line no-use-before-define
}
const wrapper = (date, instance) =>
dayjs(date, {
locale: instance.$L,
utc: instance.$u,
$offset: instance.$offset // todo: refactor; do not use this.$offset in you code
})
const Utils = U // for plugin use
Utils.l = parseLocale
Utils.i = isDayjs
Utils.w = wrapper
const parseDate = (cfg) => {
const { date, utc } = cfg
if (date === null) return new Date(NaN) // null is invalid
if (Utils.u(date)) return new Date() // today
if (date instanceof Date) return new Date(date)
if (typeof date === 'string' && !/Z$/i.test(date)) {
const d = date.match(C.REGEX_PARSE)
if (d) {
if (utc) {
return new Date(Date.UTC(d[1], d[2] - 1, d[3]
|| 1, d[4] || 0, d[5] || 0, d[6] || 0, d[7] || 0))
}
return new Date(d[1], d[2] - 1, d[3] || 1, d[4] || 0, d[5] || 0, d[6] || 0, d[7] || 0)
}
}
return new Date(date) // everything else
}
class
|
{
constructor(cfg) {
this.$L = this.$L || parseLocale(cfg.locale, null, true)
this.parse(cfg) // for plugin
}
parse(cfg) {
this.$d = parseDate(cfg)
this.init()
}
init() {
const { $d } = this
this.$y = $d.getFullYear()
this.$M = $d.getMonth()
this.$D = $d.getDate()
this.$W = $d.getDay()
this.$H = $d.getHours()
this.$m = $d.getMinutes()
this.$s = $d.getSeconds()
this.$ms = $d.getMilliseconds()
}
// eslint-disable-next-line class-methods-use-this
$utils() {
return Utils
}
isValid() {
return !(this.$d.toString() === C.INVALID_DATE_STRING)
}
isSame(that, units) {
const other = dayjs(that)
return this.startOf(units) <= other && other <= this.endOf(units)
}
isAfter(that, units) {
return dayjs(that) < this.startOf(units)
}
isBefore(that, units) {
return this.endOf(units) < dayjs(that)
}
$g(input, get, set) {
if (Utils.u(input)) return this[get]
return this.set(set, input)
}
year(input) {
return this.$g(input, '$y', C.Y)
}
month(input) {
return this.$g(input, '$M', C.M)
}
day(input) {
return this.$g(input, '$W', C.D)
}
date(input) {
return this.$g(input, '$D', C.DATE)
}
hour(input) {
return this.$g(input, '$H', C.H)
}
minute(input) {
return this.$g(input, '$m', C.MIN)
}
second(input) {
return this.$g(input, '$s', C.S)
}
millisecond(input) {
return this.$g(input, '$ms', C.MS)
}
unix() {
return Math.floor(this.valueOf() / 1000)
}
valueOf() {
// timezone(hour) * 60 * 60 * 1000 => ms
return this.$d.getTime()
}
startOf(units, startOf) { // startOf -> endOf
const isStartOf = !Utils.u(startOf) ? startOf : true
const unit = Utils.p(units)
const instanceFactory = (d, m) => {
const ins = Utils.w(this.$u ?
Date.UTC(this.$y, m, d) : new Date(this.$y, m, d), this)
return isStartOf ? ins : ins.endOf(C.D)
}
const instanceFactorySet = (method, slice) => {
const argumentStart = [0, 0, 0, 0]
const argumentEnd = [23, 59, 59, 999]
return Utils.w(this.toDate()[method].apply( // eslint-disable-line prefer-spread
this.toDate('s'),
(isStartOf ? argumentStart : argumentEnd).slice(slice)
), this)
}
const { $W, $M, $D } = this
const utcPad = `set${this.$u ? 'UTC' : ''}`
switch (unit) {
case C.Y:
return isStartOf ? instanceFactory(1, 0) :
instanceFactory(31, 11)
case C.M:
return isStartOf ? instanceFactory(1, $M) :
instanceFactory(0, $M + 1)
case C.W: {
const weekStart = this.$locale().weekStart || 0
const gap = ($W < weekStart ? $W + 7 : $W) - weekStart
return instanceFactory(isStartOf ? $D - gap : $D + (6 - gap), $M)
}
case C.D:
case C.DATE:
return instanceFactorySet(`${utcPad}Hours`, 0)
case C.H:
return instanceFactorySet(`${utcPad}Minutes`, 1)
case C.MIN:
return instanceFactorySet(`${utcPad}Seconds`, 2)
case C.S:
return instanceFactorySet(`${utcPad}Milliseconds`, 3)
default:
return this.clone()
}
}
endOf(arg) {
return this.startOf(arg, false)
}
$set(units, int) { // private set
const unit = Utils.p(units)
const utcPad = `set${this.$u ? 'UTC' : ''}`
const name = {
[C.D]: `${utcPad}Date`,
[C.DATE]: `${utcPad}Date`,
[C.M]: `${utcPad}Month`,
[C.Y]: `${utcPad}FullYear`,
[C.H]: `${utcPad}Hours`,
[C.MIN]: `${utcPad}Minutes`,
[C.S]: `${utcPad}Seconds`,
[C.MS]: `${utcPad}Milliseconds`
}[unit]
const arg = unit === C.D ? this.$D + (int - this.$W) : int
if (unit === C.M || unit === C.Y) {
// clone is for badMutable plugin
const date = this.clone().set(C.DATE, 1)
date.$d[name](arg)
date.init()
this.$d = date.set(C.DATE, Math.min(this.$D, date.daysInMonth())).toDate()
} else if (name) this.$d[name](arg)
this.init()
return this
}
set(string, int) {
return this.clone().$set(string, int)
}
get(unit) {
return this[Utils.p(unit)]()
}
add(number, units) {
number = Number(number) // eslint-disable-line no-param-reassign
const unit = Utils.p(units)
const instanceFactorySet = (n) => {
const d = dayjs(this)
return Utils.w(d.date(d.date() + Math.round(n * number)), this)
}
if (unit === C.M) {
return this.set(C.M, this.$M + number)
}
if (unit === C.Y) {
return this.set(C.Y, this.$y + number)
}
if (unit === C.D) {
return instanceFactorySet(1)
}
if (unit === C.W) {
return instanceFactorySet(7)
}
const step = {
[C.MIN]: C.MILLISECONDS_A_MINUTE,
[C.H]: C.MILLISECONDS_A_HOUR,
[C.S]: C.MILLISECONDS_A_SECOND
}[unit] || 1 // ms
const nextTimeStamp = this.$d.getTime() + (number * step)
return Utils.w(nextTimeStamp, this)
}
subtract(number, string) {
return this.add(number * -1, string)
}
format(formatStr) {
if (!this.isValid()) return C.INVALID_DATE_STRING
const str = formatStr || C.FORMAT_DEFAULT
const zoneStr = Utils.z(this)
const locale = this.$locale()
const { $H, $m, $M } = this
const {
weekdays, months, meridiem
} = locale
const getShort = (arr, index, full, length) => (
(arr && (arr[index] || arr(this, str))) || full[index].substr(0, length)
)
const get$H = num => (
Utils.s($H % 12 || 12, num, '0')
)
const meridiemFunc = meridiem || ((hour, minute, isLowercase) => {
const m = (hour < 12 ? 'AM' : 'PM')
return isLowercase ? m.toLowerCase() : m
})
const matches = {
YY: String(this.$y).slice(-2),
YYYY: this.$y,
M: $M + 1,
MM: Utils.s($M + 1, 2, '0'),
MMM: getShort(locale.monthsShort, $M, months, 3),
MMMM: months[$M] || months(this, str),
D: this.$D,
DD: Utils.s(this.$D, 2, '0'),
d: String(this.$W),
dd: getShort(locale.weekdaysMin, this.$W, weekdays, 2),
ddd: getShort(locale.weekdaysShort, this.$W, weekdays, 3),
dddd: weekdays[this.$W],
H: String($H),
HH: Utils.s($H, 2, '0'),
h: get$H(1),
hh: get$H(2),
a: meridiemFunc($H, $m, true),
A: meridiemFunc($H, $m, false),
m: String($m),
mm: Utils.s($m, 2, '0'),
s: String(this.$s),
ss: Utils.s(this.$s, 2, '0'),
SSS: Utils.s(this.$ms, 3, '0'),
Z: zoneStr // 'ZZ' logic below
}
return str.replace(C.REGEX_FORMAT, (match, $1) => $1 || matches[match] || zoneStr.replace(':', '')) // 'ZZ'
}
utcOffset() {
// Because a bug at FF24, we're rounding the timezone offset around 15 minutes
// https://github.com/moment/moment/pull/1871
return -Math.round(this.$d.getTimezoneOffset() / 15) * 15
}
diff(input, units, float) {
const unit = Utils.p(units)
const that = dayjs(input)
const zoneDelta = (that.utcOffset() - this.utcOffset()) * C.MILLISECONDS_A_MINUTE
const diff = this - that
let result = Utils.m(this, that)
result = {
[C.Y]: result / 12,
[C.M]: result,
[C.Q]: result / 3,
[C.W]: (diff - zoneDelta) / C.MILLISECONDS_A_WEEK,
[C.D]: (diff - zoneDelta) / C.MILLISECONDS_A_DAY,
[C.H]: diff / C.MILLISECONDS_A_HOUR,
[C.MIN]: diff / C.MILLISECONDS_A_MINUTE,
[C.S]: diff / C.MILLISECONDS_A_SECOND
}[unit] || diff // milliseconds
return float ? result : Utils.a(result)
}
daysInMonth() {
return this.endOf(C.M).$D
}
$locale() { // get locale object
return Ls[this.$L]
}
locale(preset, object) {
if (!preset) return this.$L
const that = this.clone()
const nextLocaleName = parseLocale(preset, object, true)
if (nextLocaleName) that.$L = nextLocaleName
return that
}
clone() {
return Utils.w(this.$d, this)
}
toDate() {
return new Date(this.valueOf())
}
toJSON() {
return this.isValid() ? this.toISOString() : null
}
toISOString() {
// ie 8 return
// new Dayjs(this.valueOf() + this.$d.getTimezoneOffset() * 60000)
// .format('YYYY-MM-DDTHH:mm:ss.SSS[Z]')
return this.$d.toISOString()
}
toString() {
return this.$d.toUTCString()
}
}
dayjs.prototype = Dayjs.prototype
dayjs.extend = (plugin, option) => {
plugin(option, Dayjs, dayjs)
return dayjs
}
dayjs.locale = parseLocale
dayjs.isDayjs = isDayjs
dayjs.unix = timestamp => (
dayjs(timestamp * 1e3)
)
dayjs.en = Ls[L]
dayjs.Ls = Ls
export default dayjs
|
Dayjs
|
result.rs
|
use crate::exception::Exception;
use alloc::boxed::Box;
use alloc::string::{String, ToString};
use core::fmt::Display;
use core::ptr::{self, NonNull};
use core::result::Result as StdResult;
use core::slice;
use core::str;
#[repr(C)]
#[derive(Copy, Clone)]
struct
|
{
ptr: NonNull<u8>,
len: usize,
}
#[repr(C)]
pub union Result {
err: PtrLen,
ok: *const u8, // null
}
pub unsafe fn r#try<T, E>(ret: *mut T, result: StdResult<T, E>) -> Result
where
E: Display,
{
match result {
Ok(ok) => {
ptr::write(ret, ok);
Result { ok: ptr::null() }
}
Err(err) => to_c_error(err.to_string()),
}
}
unsafe fn to_c_error(msg: String) -> Result {
let mut msg = msg;
msg.as_mut_vec().push(b'\0');
let ptr = msg.as_ptr();
let len = msg.len();
extern "C" {
#[link_name = "cxxbridge1$error"]
fn error(ptr: *const u8, len: usize) -> *const u8;
}
let copy = error(ptr, len);
let slice = slice::from_raw_parts(copy, len);
let string = str::from_utf8_unchecked(slice);
let err = PtrLen {
ptr: NonNull::from(string).cast::<u8>(),
len: string.len(),
};
Result { err }
}
impl Result {
pub unsafe fn exception(self) -> StdResult<(), Exception> {
if self.ok.is_null() {
Ok(())
} else {
let err = self.err;
let slice = slice::from_raw_parts_mut(err.ptr.as_ptr(), err.len);
let s = str::from_utf8_unchecked_mut(slice);
Err(Exception {
what: Box::from_raw(s),
})
}
}
}
|
PtrLen
|
oracle.go
|
// Copyright 2020 The OPA Authors. All rights reserved.
// Use of this source code is governed by an Apache2
// license that can be found in the LICENSE file.
package cmd
import (
"errors"
"fmt"
"io"
"io/ioutil"
"os"
"strconv"
"strings"
"github.com/spf13/cobra"
"github.com/meta-quick/opa/ast"
"github.com/meta-quick/opa/bundle"
"github.com/meta-quick/opa/internal/oracle"
"github.com/meta-quick/opa/internal/presentation"
"github.com/meta-quick/opa/loader"
)
type findDefinitionParams struct {
stdinBuffer bool
bundlePaths repeatedStringFlag
}
func init()
|
func dofindDefinition(params findDefinitionParams, stdin io.Reader, stdout io.Writer, args []string) error {
filename, offset, err := parseFilenameOffset(args[0])
if err != nil {
return err
}
var b *bundle.Bundle
if len(params.bundlePaths.v) != 0 {
if len(params.bundlePaths.v) > 1 {
return errors.New("not implemented: multiple bundle paths")
}
b, err = loader.NewFileLoader().WithSkipBundleVerification(true).AsBundle(params.bundlePaths.v[0])
if err != nil {
return err
}
}
modules := map[string]*ast.Module{}
if b != nil {
for _, mf := range b.Modules {
modules[mf.Path] = mf.Parsed
}
}
var bs []byte
if params.stdinBuffer {
bs, err = ioutil.ReadAll(stdin)
if err != nil {
return err
}
}
result, err := oracle.New().FindDefinition(oracle.DefinitionQuery{
Buffer: bs,
Filename: filename,
Pos: offset,
Modules: modules,
})
if err != nil {
return presentation.JSON(stdout, map[string]interface{}{
"error": err,
})
}
return presentation.JSON(stdout, result)
}
func parseFilenameOffset(s string) (string, int, error) {
s = strings.TrimPrefix(s, "file://")
parts := strings.Split(s, ":")
if len(parts) != 2 {
return "", 0, errors.New("expected <filename>:<offset> argument")
}
base := 10
str := parts[1]
if strings.HasPrefix(parts[1], "0x") {
base = 16
str = parts[1][2:]
}
offset, err := strconv.ParseInt(str, base, 32)
if err != nil {
return "", 0, err
}
return parts[0], int(offset), nil
}
|
{
var findDefinitionParams findDefinitionParams
var oracleCommand = &cobra.Command{
Use: "oracle",
Short: "Answer questions about Rego",
Long: "Answer questions about Rego.",
Hidden: true,
}
var findDefinitionCommand = &cobra.Command{
Use: "find-definition",
Short: "Find the location of a definition",
Long: `Find the location of a definition.
The 'find-definition' command outputs the location of the definition of the symbol
or value referred to by the location passed as a positional argument. The location
should be of the form:
<filename>:<offset>
The offset can be specified as a decimal or hexadecimal number. The output format
specifies the file, row, and column of the definition:
{
"result": {
"file": "/path/to/some/policy.rego",
"row": 18,
"col": 1
}
}
If the 'find-definition' command cannot find a location it will print an error
reason. The exit status will be zero in this case:
{
"error": "no match found"
}
If an unexpected error occurs (e.g., a file read error) the subcommand will print
the error reason to stderr and exit with a non-zero status code.
If the --stdin-buffer flag is supplied the 'find-definition' subcommand will
consume stdin and treat the bytes read as the content of the file referenced
by the input location.`,
PreRunE: func(cmd *cobra.Command, args []string) error {
if len(args) != 1 {
return errors.New("expected exactly one position <filename>:<offset>")
}
_, _, err := parseFilenameOffset(args[0])
return err
},
Run: func(cmd *cobra.Command, args []string) {
if err := dofindDefinition(findDefinitionParams, os.Stdin, os.Stdout, args); err != nil {
fmt.Fprintln(os.Stderr, "error:", err)
os.Exit(1)
}
},
}
findDefinitionCommand.Flags().BoolVarP(&findDefinitionParams.stdinBuffer, "stdin-buffer", "", false, "read buffer from stdin")
addBundleFlag(findDefinitionCommand.Flags(), &findDefinitionParams.bundlePaths)
oracleCommand.AddCommand(findDefinitionCommand)
RootCommand.AddCommand(oracleCommand)
}
|
test_cluster_defaults.py
|
import json
import pytest
from rancher import ApiError
from .common import random_str
from .conftest import wait_for
@pytest.mark.skip(reason="cluster-defaults disabled")
def test_generic_initial_defaults(admin_mc):
cclient = admin_mc.client
schema_defaults = {}
setting_defaults = {}
data = cclient.schema.types['cluster'].resourceFields
default = data["enableNetworkPolicy"]["default"]
for name in cclient.schema.types['cluster'].resourceFields.keys():
if name == "enableNetworkPolicy":
schema_defaults["enableNetworkPolicy"] = default
for name in cclient.schema.types['rancherKubernetesEngineConfig'] \
.resourceFields.keys():
if name == "ignoreDockerVersion":
schema_defaults["ignoreDockerVersion"] = cclient.schema. \
types["rancherKubernetesEngineConfig"]. \
resourceFields["ignoreDockerVersion"]. \
data_dict()["default"]
setting = cclient.list_setting(name="cluster-defaults")
data = json.loads(setting['data'][0]['default'])
setting_defaults["enableNetworkPolicy"] = data["enableNetworkPolicy"]
setting_defaults["ignoreDockerVersion"] = \
data["rancherKubernetesEngineConfig"]["ignoreDockerVersion"]
assert schema_defaults == setting_defaults
def test_generic_initial_conditions(admin_mc, remove_resource):
cluster = admin_mc.client.create_cluster(
name=random_str(), amazonElasticContainerServiceConfig={
"accessKey": "asdfsd"})
remove_resource(cluster)
assert len(cluster.conditions) == 3
assert cluster.conditions[0].type == 'Pending'
assert cluster.conditions[0].status == 'True'
assert cluster.conditions[1].type == 'Provisioned'
assert cluster.conditions[1].status == 'Unknown'
assert cluster.conditions[2].type == 'Waiting'
assert cluster.conditions[2].status == 'Unknown'
assert 'exportYaml' not in cluster.actions
def test_eks_cluster_immutable_subnets(admin_mc, remove_resource):
cluster = admin_mc.client.create_cluster(
name=random_str(), amazonElasticContainerServiceConfig={
"accessKey": "asdfsd",
"secretKey": "verySecretKey",
"subnets": [
"subnet-045bfaeca7d3f1cb3",
"subnet-02388a166136f98c4"
]})
remove_resource(cluster)
def cannot_modify_error():
with pytest.raises(ApiError) as e:
# try to edit cluster subnets
admin_mc.client.update_by_id_cluster(
id=cluster.id,
amazonElasticContainerServiceConfig={
"accessKey": "asdfsd",
"secretKey": "verySecretKey",
"subnets": [
"subnet-045bfaeca7d3f1cb3"
]})
if e.value.error.status == 404:
return False
print(e)
assert e.value.error.status == 422
assert e.value.error.message ==\
'cannot modify EKS subnets after creation'
return True
# lister used by cluster validator may not be up to date, may need to retry
wait_for(cannot_modify_error)
# tests updates still work
new = admin_mc.client.update_by_id_cluster(
id=cluster.id,
name=cluster.name,
description="update",
amazonElasticContainerServiceConfig={
# required field when updating KE clusters
"driverName": "amazonelasticcontainerservice",
"accessKey": "asdfsd",
"secretKey": "verySecretKey",
"subnets": [
"subnet-045bfaeca7d3f1cb3",
"subnet-02388a166136f98c4"
]})
assert new.id == cluster.id
assert not hasattr(cluster, "description")
assert hasattr(new, "description")
def test_rke_initial_conditions(admin_mc, remove_resource):
cluster = admin_mc.client.create_cluster(
name=random_str(), rancherKubernetesEngineConfig={
"accessKey": "asdfsd"})
remove_resource(cluster)
assert len(cluster.conditions) == 3
assert cluster.conditions[0].type == 'Pending'
assert cluster.conditions[0].status == 'True'
assert cluster.conditions[1].type == 'Provisioned'
assert cluster.conditions[1].status == 'Unknown'
assert cluster.conditions[2].type == 'Waiting'
assert cluster.conditions[2].status == 'Unknown'
assert 'exportYaml' in cluster.actions
def test_psp_enabled_set(admin_mc, remove_resource):
"""Asserts podSecurityPolicy field is used to populate pspEnabled in
cluster capabilities"""
admin_client = admin_mc.client
cluster = admin_client.create_cluster(
name=random_str(), rancherKubernetesEngineConfig={
"accessKey": "asdfsd",
"services": {
"kubeApi": {
"podSecurityPolicy": True,
}
}
})
remove_resource(cluster)
def psp_set_to_true():
updated_cluster = admin_client.by_id_cluster(id=cluster.id)
capabilities = updated_cluster.get("capabilities")
if capabilities is not None:
return capabilities.get("pspEnabled") is True
return None
wait_for(lambda: psp_set_to_true(), fail_handler=lambda: "failed waiting "
"for pspEnabled to be set")
def
|
(admin_mc, remove_resource):
cluster = admin_mc.client.create_cluster(name=random_str())
remove_resource(cluster)
assert not cluster.conditions
def test_rke_k8s_deprecated_versions(admin_mc, remove_resource):
client = admin_mc.client
deprecated_versions_setting = client.by_id_setting(
"k8s-versions-deprecated")
client.update_by_id_setting(id=deprecated_versions_setting.id,
value="{\"v1.8.10-rancher1-1\":true}")
with pytest.raises(ApiError) as e:
cluster = client.create_cluster(
name=random_str(), rancherKubernetesEngineConfig={
"kubernetesVersion": "v1.8.10-rancher1-1"})
remove_resource(cluster)
assert e.value.error.status == 500
assert e.value.error.message == 'Requested kubernetesVersion ' \
'v1.8.10-rancher1-1 is deprecated'
client.update_by_id_setting(id=deprecated_versions_setting.id,
value="")
def test_save_as_template_action_rbac(admin_mc, remove_resource, user_factory):
cluster = admin_mc.client.create_cluster(name=random_str(),
rancherKubernetesEngineConfig={
"services": {
"type":
"rkeConfigServices",
"kubeApi": {
"alwaysPullImages":
"false",
"podSecurityPolicy":
"false",
"serviceNodePort\
Range":
"30000-32767",
"type":
"kubeAPIService"
}
}
})
remove_resource(cluster)
assert cluster.conditions[0].type == 'Pending'
assert cluster.conditions[0].status == 'True'
try:
admin_mc.client.action(obj=cluster, action_name="saveAsTemplate",
clusterTemplateName="template1",
clusterTemplateRevisionName="v1")
except ApiError as e:
assert e.error.status == 503
user = user_factory()
user_cluster = user.client.create_cluster(name=random_str())
remove_resource(user_cluster)
assert cluster.conditions[0].type == 'Pending'
assert cluster.conditions[0].status == 'True'
try:
user.client.action(obj=user_cluster, action_name="saveAsTemplate")
except AttributeError as e:
assert e is not None
|
test_import_initial_conditions
|
alert.rs
|
use gtk::prelude::{BoxExt, ButtonExt, Cast, GtkWindowExt, OrientableExt};
use relm4::{
send, AppUpdate, Components, Model, RelmApp, RelmComponent, Sender, WidgetPlus, Widgets,
};
use relm4_components::alert::{AlertConfig, AlertModel, AlertMsg, AlertParent, AlertSettings};
use relm4_components::ParentWindow;
#[derive(Default)]
struct AppModel {
counter: u8,
alert_toggle: bool,
}
enum AppMsg {
Increment,
Decrement,
CloseRequest,
Save,
Close,
Ignore,
}
impl Model for AppModel {
type Msg = AppMsg;
type Widgets = AppWidgets;
type Components = AppComponents;
}
impl AppUpdate for AppModel {
fn update(&mut self, msg: AppMsg, components: &AppComponents, _sender: Sender<AppMsg>) -> bool {
match msg {
AppMsg::Increment => {
self.counter = self.counter.wrapping_add(1);
}
AppMsg::Decrement => {
self.counter = self.counter.wrapping_sub(1);
}
AppMsg::CloseRequest => {
if self.counter == 42 {
return false;
} else {
self.alert_toggle = !self.alert_toggle;
if self.alert_toggle {
components.dialog.send(AlertMsg::Show).unwrap();
} else
|
}
}
AppMsg::Save => {
println!("* Open save dialog here *");
}
AppMsg::Close => {
return false;
}
AppMsg::Ignore => (),
}
true
}
}
struct FirstAlert {}
impl AlertConfig for FirstAlert {
type Model = AppModel;
fn alert_config(_model: &AppModel) -> AlertSettings {
AlertSettings {
text: "Do you want to quit without saving? (First alert)",
secondary_text: Some("Your counter hasn't reached 42 yet"),
confirm_label: "Close without saving",
cancel_label: "Cancel",
option_label: Some("Save"),
is_modal: true,
destructive_accept: true,
}
}
}
struct SecondAlert {}
impl AlertConfig for SecondAlert {
type Model = AppModel;
fn alert_config(_model: &AppModel) -> AlertSettings {
AlertSettings {
text: "Do you want to quit without saving? (Second alert)",
secondary_text: Some("Your counter hasn't reached 42 yet"),
confirm_label: "Close without saving",
cancel_label: "Cancel",
option_label: Some("Save"),
is_modal: true,
destructive_accept: true,
}
}
}
impl AlertParent for AppModel {
fn confirm_msg() -> Self::Msg {
AppMsg::Close
}
fn cancel_msg() -> Self::Msg {
AppMsg::Ignore
}
fn option_msg() -> Self::Msg {
AppMsg::Save
}
}
impl ParentWindow for AppWidgets {
fn parent_window(&self) -> Option<gtk::Window> {
Some(self.main_window.clone().upcast::<gtk::Window>())
}
}
pub struct AppComponents {
dialog: RelmComponent<AlertModel<FirstAlert>, AppModel>,
second_dialog: RelmComponent<AlertModel<SecondAlert>, AppModel>,
}
impl Components<AppModel> for AppComponents {
fn init_components(
model: &AppModel,
parent_widgets: &AppWidgets,
sender: Sender<AppMsg>,
) -> Self {
AppComponents {
dialog: RelmComponent::new(model, parent_widgets, sender.clone()),
second_dialog: RelmComponent::new(model, parent_widgets, sender),
}
}
}
#[relm4_macros::widget]
impl Widgets<AppModel, ()> for AppWidgets {
view! {
main_window = gtk::ApplicationWindow {
set_title: Some("Simple app"),
set_default_width: 300,
set_default_height: 100,
connect_close_request(sender) => move |_| {
send!(sender, AppMsg::CloseRequest);
gtk::Inhibit(true)
},
set_child = Some(>k::Box) {
set_orientation: gtk::Orientation::Vertical,
set_margin_all: 5,
set_spacing: 5,
append = >k::Button {
set_label: "Increment",
connect_clicked(sender) => move |_| {
send!(sender, AppMsg::Increment);
},
},
append = >k::Button {
set_label: "Decrement",
connect_clicked(sender) => move |_| {
send!(sender, AppMsg::Decrement);
},
},
append = >k::Label {
set_margin_all: 5,
set_label: watch! { &format!("Counter: {}", model.counter) },
},
append = >k::Button {
set_label: "Close",
connect_clicked(sender) => move |_| {
send!(sender, AppMsg::CloseRequest);
},
},
},
}
}
}
fn main() {
let model = AppModel::default();
let app = RelmApp::new(model);
app.run();
}
|
{
components.second_dialog.send(AlertMsg::Show).unwrap();
}
|
users.go
|
package criteria
import (
"github.com/open-policy-agent/opa/ast"
"github.com/pomerium/pomerium/pkg/policy/generator"
"github.com/pomerium/pomerium/pkg/policy/parser"
"github.com/pomerium/pomerium/pkg/policy/rules"
)
var usersBody = ast.Body{
ast.MustParseExpr(`
session := get_session(input.session.id)
`),
ast.MustParseExpr(`
user := get_user(session)
`),
ast.MustParseExpr(`
user_id := user.id
`),
}
type usersCriterion struct {
g *Generator
}
func (usersCriterion) DataType() generator.CriterionDataType {
return CriterionDataTypeStringMatcher
}
func (usersCriterion) Names() []string {
return []string{"user", "users"}
}
func (c usersCriterion) GenerateRule(_ string, data parser.Value) (*ast.Rule, []*ast.Rule, error) {
r := c.g.NewRule("users")
r.Body = append(r.Body, usersBody...)
err := matchString(&r.Body, ast.VarTerm("user_id"), data)
if err != nil
|
return r, []*ast.Rule{
rules.GetSession(),
rules.GetUser(),
rules.GetUserEmail(),
}, nil
}
// UserIDs returns a Criterion on a user's id.
func UserIDs(generator *Generator) Criterion {
return usersCriterion{g: generator}
}
func init() {
Register(UserIDs)
}
|
{
return nil, nil, err
}
|
build.rs
|
// Copyright 2019 Authors of Red Sift
//
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
// http://opensource.org/licenses/MIT>, at your option. This file may not be
// copied, modified, or distributed except according to those terms.
#![deny(clippy::all)]
use std::env;
use std::path::PathBuf;
const KERNEL_HEADERS: [&str; 6] = [
"arch/x86/include/generated/uapi",
"arch/x86/include/uapi",
"arch/x86/include/",
"include/generated/uapi",
"include/uapi",
"include",
];
pub mod uname {
include!(concat!(env!("CARGO_MANIFEST_DIR"), "/src/uname.rs"));
}
pub mod headers {
include!(concat!(env!("CARGO_MANIFEST_DIR"), "/src/headers.rs"));
}
fn rerun_if_changed_dir(dir: &str) {
println!("cargo:rerun-if-changed={}/", dir);
for ext in &["c", "h", "bash", "map", "md", "rst", "sh", "template"] {
glob::glob(&format!("./{}/**/*.{}", dir, ext))
.expect("Failed to glob for source files from build.rs")
.filter_map(|e| e.ok())
.for_each(|path| println!("cargo:rerun-if-changed={}", path.to_string_lossy()));
}
}
fn
|
() {
println!("cargo:rustc-link-lib=static=bpf");
for dir in &["bcc", "libbpf", "libelf"] {
rerun_if_changed_dir(dir);
}
println!("cargo:rerun-if-changed=bpfsys-musl.h");
println!("cargo:rerun-if-changed=libbpf_xdp.h");
let target = env::var("TARGET").unwrap();
let out_dir = env::var("OUT_DIR").unwrap();
let out_path = PathBuf::from(out_dir);
let mut libbpf = cc::Build::new();
libbpf
.flag("-Wno-sign-compare")
.flag("-Wno-int-conversion")
.flag("-Wno-unused-parameter")
.flag("-Wno-unused-result")
.flag("-Wno-format-truncation")
.flag("-Wno-missing-field-initializers")
.include("libbpf/include/uapi")
.include("libbpf/include")
.include("bcc")
.include("libelf")
.include(".");
if target.contains("musl") {
for include in
headers::prefix_kernel_headers(&KERNEL_HEADERS).expect("couldn't find kernel headers")
{
libbpf.include(include);
}
libbpf
.define("COMPAT_NEED_REALLOCARRAY", "1")
.flag("-include")
.flag("bpfsys-musl.h");
}
libbpf
.flag("-include")
.flag("linux/stddef.h")
.file("libbpf/src/bpf.c")
.file("libbpf/src/bpf_prog_linfo.c")
.file("libbpf/src/btf.c")
.file("libbpf/src/libbpf.c")
.file("libbpf/src/libbpf_errno.c")
.file("libbpf/src/libbpf_probes.c")
.file("libbpf/src/netlink.c")
.file("libbpf/src/nlattr.c")
.file("libbpf/src/str_error.c")
.file("libbpf/src/xsk.c")
.file("bcc/libbpf.c")
.file("bcc/perf_reader.c")
.compile("libbpf.a");
let bindings = bindgen::Builder::default()
.header("libbpf_xdp.h")
.header("libbpf/src/bpf.h")
.clang_arg("-Ilibbpf/src")
.clang_arg("-Ilibbpf/include/uapi")
.clang_arg("-Ilibbpf/include")
.clang_arg("-Ibcc")
.generate()
.expect("Unable to generate bindings");
bindings
.write_to_file(out_path.join("libbpf_bindings.rs"))
.expect("Couldn't write bindings!");
let bindings = bindgen::Builder::default()
.header("libbpf/src/libbpf.h")
.clang_arg("-Ilibbpf/include/uapi")
.clang_arg("-Ilibbpf/include")
.clang_arg("-Ibcc")
.whitelist_type("bpf_map_def")
.generate()
.expect("Unable to generate bindings");
bindings
.write_to_file(out_path.join("libbpf_map_def.rs"))
.expect("Couldn't write bindings!");
let bindings = bindgen::Builder::default()
.header("bcc/perf_reader.h")
.header("libbpf/src/bpf.h")
.clang_arg("-Ilibbpf/src")
.clang_arg("-Ilibbpf/include/uapi")
.clang_arg("-Ilibbpf/include")
.clang_arg("-Ibcc")
.generate()
.expect("Unable to generate bindings");
bindings
.write_to_file(out_path.join("perf_reader_bindings.rs"))
.expect("Couldn't write bindings!");
}
|
main
|
stage.js
|
/**
* A module to define the main stage UI.
*
* @module ui/stage
*/
define(['config/config', 'config/strings', 'misc/point'], function (config, strings, Point) {
/**
* Creates the main stage UI. It nust be extended by the other game UIs.
*
* @constructor
* @alias module:ui/stage
* @param {object} canvas The game canvas.
* @param {object} ctx The game canvas context.
* @param {Game} game The game control object.
*/
var StageUI = function (canvas, ctx, game) {
/**
* The game canvas context.
*
* @type {object}
*/
this.canvas = canvas;
/**
* The canvas context.
*
* @type {object}
*/
this.ctx = ctx;
/**
* The game control object.
*
* @type {object}
*/
this.game = game;
/**
* Define a generic callback.
*
* @callback eventCallbackType
* @param {Event} evt The event object.
*/
/**
* Define an object that contains the data used to identify the mouse hover
* areas in the stage.
*
* @typedef {object} eventAssociation
* @property {string} event The event name.
* @property {eventCallbackType} listener The listener function.
*/
/**
* An array of {@link eventAssociation} objects.
*
* @type {eventAssociation[]}
*/
this.events = [];
/**
* Define an object that contains the coordinates used to verify
* collisions.
*
* @typedef {object} bounds
* @property {number} topLeftX The top left x position.
* @property {number} bottomRightX The bottom right x position.
* @property {number} topLeftY The top left y position.
* @property {number} bottomRightY The bottom right y position.
*/
/**
* This callback is used to handle mouse over events.
*
* @callback mouseOverCallbackType
* @param {identifier} identifier The name (identifier) of the hover area (see {@link hoverable}).
*/
/**
* This callback is used to handle mouse out events.
*
* @callback mouseOutCallbackType
* @param {identifier} identifier The identifier of the hover area (see {@link hoverable}).
*/
/**
* Define an object that contains the data used to identify the mouse hover
* areas in the stage.
*
* @typedef {object} hoverable
* @property {string} identifier An identifier for that hover area.
* @property {bounds} bounds The hover bounds.
* @property {string|function} content The image path a function that renders the element.
* @property {number} renderXPos The x position to render the element.
* @property {number} renderYPos The y position to render the element.
* @property {mouseOverCallbackType} mouseOverCallback A callback to run when the mouse is over.
* @property {mouseOutCallbackType} mouseOutCallback A callback to run when the mouse is out.
*/
/**
* An array of {@link hoverable} objects.
*
* @type {hoverable[]}
*/
this.hoverables = [];
/**
* Identify the elements the mouse is over. Each value must contain the identifier
* found at {@link StageUI#hoverables}.
*
* @type {string[]}
*/
this.mouseOverElements = [];
/**
* Identify if the mouse left button is pressed.
*
* @type {boolean}
*/
this.mouseIsPressed = false;
/**
* Identify if the enter key is pressed.
*
* @type {boolean}
*/
this.enterIsPressed = false;
var self = this;
/**
* A listener that should be used in the mousemove event to update
* the mouse cursor in hover areas, and handle the hover areas,
* updating the proper variables.
*
* @param {MouseEvent} evt The mouse event.
* @type {function}
* @private
*/
var _mouseMoveListener = function (evt) {
var mousePos = self.getMousePos(evt);
//console.log(self);
// Updating the mouse cursor on hover areas:
if (self.mouseOverElements.length > 0) {
self.canvas.style.cursor = 'pointer';
} else {
self.canvas.style.cursor = 'initial';
}
// Check if the mouse is in a hover area:
self.hoverables.forEach(function (hoverable) {
var bounds = hoverable.bounds;
// Check if the mouse is inside the hover area bounds:
if (mousePos.x >= bounds.topLeftX &&
mousePos.x <= bounds.bottomRightX &&
mousePos.y >= bounds.topLeftY &&
mousePos.y <= bounds.bottomRightY) {
// If the hover area is not registered in the {@link StageUI#mouseOverElements}
// list, i.e. this hover has not happened yet, play a "selection change" sound
// and register the hover event:
if (self.mouseOverElements.indexOf(hoverable.identifier) === -1) {
self.game.audioControl.playSound('selectionChange');
self.mouseOverElements.push(hoverable.identifier);
}
// Trigger the equivalent mouseover event:
hoverable.mouseOverCallback(hoverable.identifier);
} else {
// If the mouse is not above a hover area, it should be removed from the
// {@link StageUI#mouseOverElements} list:
var index = self.mouseOverElements.indexOf(hoverable.identifier);
if (index > -1) {
self.mouseOverElements.splice(index, 1);
}
// Trigger the equivalent mouseout event:
hoverable.mouseOutCallback(hoverable.identifier);
}
});
};
/**
* A listener that should be used in the mousedown event to set
* {@link StageUI#mouseIsPressed} to true.
*
* @param {MouseEvent} evt The mouse event.
* @type {function}
* @private
*/
var _mouseIsPressedListener = function (evt) {
self.mouseIsPressed = true;
};
/**
* A listener that should be used in the mouseup event to set
* {@link StageUI#mouseIsPressed} to false.
*
* @param {MouseEvent} evt The mouse event.
* @type {function}
* @private
*/
var _mouseIsNotPressedListener = function (evt) {
self.mouseIsPressed = false;
};
/**
* A listener that should be used in the keydown event to handle the
* allowed keys and set {@link StageUI#enterIsPressed} to true when
* applicable.
*
* @param {KeyboardEvent} evt The keyboard event.
* @type {function}
* @private
*/
var _handleKeysListener = function (evt) {
var allowedKeys = {
13: 'enter',
77: 'M',
109: 'm',
},
key = allowedKeys[evt.keyCode];
if (key === 'enter') {
self.enterIsPressed = true;
} else if (key === 'm' || key === 'M') {
self.toggleAudio();
}
};
/**
* A listener that should be used in the keyup event to set
* {@link StageUI#enterIsPressed} to false when applicable.
*
* @param {KeyboardEvent} evt The keyboard event.
* @type {function}
* @private
*/
var _enterIsNotPressedListener = function (evt) {
if (evt.keyCode === 13) { //enter
self.enterIsPressed = false;
}
};
// Registering the mousemove event:
this.registerListener('mousemove', _mouseMoveListener);
// Registering the mousedown event to identify when the mouse is pressed:
this.registerListener('mousedown', _mouseIsPressedListener);
// Registering the mousedown event to identify when the mouse is not pressed:
this.registerListener('mouseup', _mouseIsNotPressedListener);
// Registering the keydown event to identify when the supported keys and when
// the enter key is pressed:
this.registerListener('keydown', _handleKeysListener);
// Registering the keydown event to identify when the enter key is not pressed:
this.registerListener('keyup', _enterIsNotPressedListener);
};
/**
* Register an event listener. The listener parameter must be a valid function.
*
* @param {string} event The event name.
* @param {function} listener The listener.
*/
StageUI.prototype.registerListener = function (event, listener) {
if (typeof listener === 'function') {
var self = this,
destinyObject;
this.events.push({
event: event,
listener: listener
});
if (event.indexOf('key') > -1) {
destinyObject = document;
} else {
destinyObject = self.canvas;
}
destinyObject.addEventListener(event, listener);
}
};
/**
* Unregister all event listeners.
|
StageUI.prototype.unregisterAllListeners = function () {
var destinyObject;
// Removing the listeners:
this.events.forEach(function (event) {
// Key events are attached to the document, while other events are attached
// to the canvas:
if (event.event.indexOf('key') > -1) {
destinyObject = document;
} else {
destinyObject = this.canvas;
}
if (document.removeEventListener) { // For all major browsers, except IE 8 and earlier
destinyObject.removeEventListener(event.event, event.listener);
} else if (document.detachEvent) { // For IE 8 and earlier versions
destinyObject.detachEvent('on' + event.event, event.listener);
}
}, this);
// Cleaning up the events array:
this.events = [];
};
/**
* Initialize the stage.
*/
StageUI.prototype.init = function () {
// Render the hoverables:
this.renderHoverables();
};
/**
* Callback to run when the stage is closed.
* It removes the event listeners created by the constructor and resets
* the hover elements.
*/
StageUI.prototype.close = function () {
this.hoverables = [];
this.unregisterAllListeners();
};
/**
* Toggle the audio state.
*/
StageUI.prototype.toggleAudio = function () {
this.game.isMute = !this.game.isMute;
};
/**
* Render the elements that can receive a mouse hover in the game.
*/
StageUI.prototype.renderHoverables = function () {
this.hoverables.forEach(function (element) {
if (typeof element.content === 'function') {
// Some elements, such as text, need a number of particular settings
// that must be performed by a function and cannot be directly rendered
// as images:
element.content(element);
} else {
// others are rendered as images in their original size:
this.ctx.drawImage(Resources.get(element.content), element.renderXPos, element.renderYPos);
}
}, this);
};
/**
* Add a hoverable element to the stage.
*
* @param {string} identifier An identifier for the hover area.
* @param {bounds} bounds The hover bounds.
* @param {string|function} content The image path a function that renders the element.
* @param {number} renderXPos The x position to render the element.
* @param {number} renderYPos The y position to render the element.
* @param {mouseOverCallbackType} mouseOverCallback A callback to run when the mouse is over.
* @param {mouseOutCallbackType} mouseOutCallback A callback to run when the mouse is out.
*/
StageUI.prototype.addHoverable = function (identifier, bounds, content, renderXPos, renderYPos, mouseOverCallback, mouseOutCallback) {
this.hoverables.push({
identifier: identifier,
bounds: bounds,
content: content,
renderXPos: renderXPos,
renderYPos: renderYPos,
mouseOverCallback: mouseOverCallback,
mouseOutCallback: mouseOutCallback
});
};
/**
* Draw a text with a shadow, giving an impression of being detached from the stage.
*
* @param {string} text The text to be drawn.
* @param {string} font The font of the text.
* @param {string} textAlign The text align in the canvas.
* @param {string} strokeStyle The stroke text style that will be applied in the canvas.
* @param {string} fillStyle The fill style of the text in the canvas.
* @param {number} posX The x position of the text in the canvas.
* @param {number} posY The y position of the text in the canvas.
* @param {boolean} [pressed=false] Informs if the text is pressed, i.e. closer to the shadow.
*/
StageUI.prototype.drawDetachedText = function (text, font, textAlign, strokeStyle, fillStyle, posX, posY, pressed) {
if (typeof pressed === 'undefined') {
pressed = false;
}
var offsetX = 0,
offsetY = 0;
// If the text is "pressed", apply a minor offset to give that impression:
if (pressed) {
offsetX = 1;
offsetY = 2;
}
this.ctx.beginPath();
this.ctx.font = font;
this.ctx.textAlign = textAlign;
this.ctx.strokeStyle = strokeStyle;
this.ctx.fillStyle = strokeStyle;
this.ctx.fillText(text, posX + config.GENERAL_TEXT_SHADOW_DIFF_X, posY + config.GENERAL_TEXT_SHADOW_DIFF_Y);
this.ctx.fillStyle = fillStyle;
this.ctx.fillText(text, posX + offsetX, posY + offsetY);
this.ctx.strokeText(text, posX + offsetX, posY + offsetY);
this.ctx.closePath();
};
/**
* Draw the background image defined in {@link StageUI#backgroundImage} on the stage.
*/
StageUI.prototype.drawBackground = function () {
if (this.backgroundImage !== null) {
var bgImage = Resources.get(this.backgroundImage);
this.ctx.drawImage(
bgImage,
this.canvas.width / 2 - bgImage.width / 2,
this.canvas.height / 2 - bgImage.height / 2
);
}
};
/**
* Get the mouse position from a mouse event.
*
* @param {MouseEvent} evt The mouse event from where to extract the position.
* @returns {Point} The mouse position.
*/
StageUI.prototype.getMousePos = function (evt) {
var rect = this.canvas.getBoundingClientRect(),
mousePos = new Point(evt.clientX - rect.left, evt.clientY - rect.top);
return mousePos;
};
/**
* Render the help message aligned to the right side of the stage.
*
* @param {string[]} helpLines An array of strings to be rendered.
* @param {number} [rightMargin=20] The right margin with respect to the stage.
* @param {number} [topMargin=80] The top margin with respect to the stage.
* @param {string} [strokeStyle=black] The *strokeStyle* used by the canvas to render the text.
* @param {string} [fillStyle=white] The *fillStyle* used by the canvas to render the text.
*/
StageUI.prototype.renderHelp = function (helpLines, rightMargin, topMargin, strokeStyle, fillStyle) {
var line = 0,
self = this;
if (typeof rightMargin === 'undefined') {
rightMargin = 20;
}
if (typeof topMargin === 'undefined') {
topMargin = 80;
}
if (typeof strokeStyle === 'undefined') {
strokeStyle = 'black';
}
if (typeof fillStyle === 'undefined') {
fillStyle = 'white';
}
helpLines.forEach(function (helpLine) {
self.drawDetachedText(
helpLine,
config.GENERAL_HELP_FONT,
'right',
strokeStyle,
fillStyle,
self.canvas.width - rightMargin,
self.canvas.height - topMargin + line,
true
);
line += 30;
});
};
return StageUI;
});
|
*/
|
__init__.py
|
__METADATA__ = {
"src_name": 'DOCM',
"src_url": 'http://docm.genome.wustl.edu/',
"version": None,
"field": "docm"
}
def load_data():
'''docm data are pre-loaded in our db.'''
raise NotImplementedError
def get_mapping():
mapping = {
"docm": {
"properties": {
"domain": {
"type": "string"
},
"all_domains": {
"type": "string"
},
"ref": {
"type": "string",
"analyzer": "string_lowercase"
},
"alt": {
"type": "string",
"analyzer": "string_lowercase"
},
"primary": {
"type": "byte" # just 0 or 1
},
"transcript_species": {
"type": "string",
"index": "no"
},
"ensembl_gene_id": {
"type": "string",
"analyzer": "string_lowercase"
},
"transcript_version": {
"type": "string",
"index": "no"
},
"transcript_source": {
"type": "string",
"index": "no"
},
"source": {
"type": "string",
"analyzer": "string_lowercase"
},
"pubmed_id": {
"type": "string",
"index": "not_analyzed"
},
"type": {
"type": "string",
"analyzer": "string_lowercase"
},
"doid": {
"type": "string",
"analyzer": "string_lowercase"
|
},
"hg19": {
"properties": {
"start": {
"type": "long"
},
"end": {
"type": "long"
}
}
},
"strand": {
"type": "byte",
"index": "no"
},
"deletion_substructures": {
"type": "string",
"index": "no"
},
"genename_source": {
"type": "string",
"index": "no"
},
"default_gene_name": {
"type": "string",
"analyzer": "string_lowercase"
},
"aa_change": {
"type": "string",
"analyzer": "string_lowercase"
},
"url": {
"type": "string",
"index": "no"
},
"transcript_status": {
"type": "string",
"analyzer": "string_lowercase"
},
"trv_type": {
"type": "string",
"analyzer": "string_lowercase"
},
"disease": {
"type": "string",
"analyzer": "string_lowercase"
},
"transcript_name": {
"type": "string",
"analyzer": "string_lowercase"
},
"chrom": {
"type": "string", # actual value is integer
"analyzer": "string_lowercase"
},
"transcript_error": {
"type": "string",
"index": "no"
},
"genename": {
"type": "string",
"analyzer": "string_lowercase",
"include_in_all": True
},
"ucsc_cons": {
"type": "double"
}
}
}
}
return mapping
|
},
"c_position": {
"type": "string",
"analyzer": "string_lowercase"
|
lib.rs
|
// Generated by gir (https://github.com/gtk-rs/gir @ ee37253c10af)
// from gir-files (https://github.com/gtk-rs/gir-files @ 5502d32880f5)
// from gst-gir-files (https://gitlab.freedesktop.org/gstreamer/gir-files-rs.git @ f05404723520)
// DO NOT EDIT
#![allow(non_camel_case_types, non_upper_case_globals, non_snake_case)]
#![allow(
clippy::approx_constant,
clippy::type_complexity,
clippy::unreadable_literal,
clippy::upper_case_acronyms
)]
#![cfg_attr(feature = "dox", feature(doc_cfg))]
#[allow(unused_imports)]
use libc::{
c_char, c_double, c_float, c_int, c_long, c_short, c_uchar, c_uint, c_ulong, c_ushort, c_void,
intptr_t, size_t, ssize_t, uintptr_t, FILE,
};
#[allow(unused_imports)]
use glib::{gboolean, gconstpointer, gpointer, GType};
// Enums
pub type GstAppLeakyType = c_int;
pub const GST_APP_LEAKY_TYPE_NONE: GstAppLeakyType = 0;
pub const GST_APP_LEAKY_TYPE_UPSTREAM: GstAppLeakyType = 1;
pub const GST_APP_LEAKY_TYPE_DOWNSTREAM: GstAppLeakyType = 2;
pub type GstAppStreamType = c_int;
pub const GST_APP_STREAM_TYPE_STREAM: GstAppStreamType = 0;
pub const GST_APP_STREAM_TYPE_SEEKABLE: GstAppStreamType = 1;
pub const GST_APP_STREAM_TYPE_RANDOM_ACCESS: GstAppStreamType = 2;
// Records
#[derive(Copy, Clone)]
#[repr(C)]
pub struct GstAppSinkCallbacks {
pub eos: Option<unsafe extern "C" fn(*mut GstAppSink, gpointer)>,
pub new_preroll: Option<unsafe extern "C" fn(*mut GstAppSink, gpointer) -> gst::GstFlowReturn>,
pub new_sample: Option<unsafe extern "C" fn(*mut GstAppSink, gpointer) -> gst::GstFlowReturn>,
pub new_event: Option<unsafe extern "C" fn(*mut GstAppSink, gpointer) -> gboolean>,
pub _gst_reserved: [gpointer; 3],
}
impl ::std::fmt::Debug for GstAppSinkCallbacks {
fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
f.debug_struct(&format!("GstAppSinkCallbacks @ {:p}", self))
.field("eos", &self.eos)
.field("new_preroll", &self.new_preroll)
.field("new_sample", &self.new_sample)
.field("new_event", &self.new_event)
.finish()
}
}
#[derive(Copy, Clone)]
#[repr(C)]
pub struct GstAppSinkClass {
pub basesink_class: gst_base::GstBaseSinkClass,
pub eos: Option<unsafe extern "C" fn(*mut GstAppSink)>,
pub new_preroll: Option<unsafe extern "C" fn(*mut GstAppSink) -> gst::GstFlowReturn>,
pub new_sample: Option<unsafe extern "C" fn(*mut GstAppSink) -> gst::GstFlowReturn>,
pub pull_preroll: Option<unsafe extern "C" fn(*mut GstAppSink) -> *mut gst::GstSample>,
pub pull_sample: Option<unsafe extern "C" fn(*mut GstAppSink) -> *mut gst::GstSample>,
pub try_pull_preroll:
Option<unsafe extern "C" fn(*mut GstAppSink, gst::GstClockTime) -> *mut gst::GstSample>,
pub try_pull_sample:
Option<unsafe extern "C" fn(*mut GstAppSink, gst::GstClockTime) -> *mut gst::GstSample>,
pub try_pull_object:
Option<unsafe extern "C" fn(*mut GstAppSink, gst::GstClockTime) -> *mut gst::GstMiniObject>,
pub _gst_reserved: [gpointer; 1],
}
impl ::std::fmt::Debug for GstAppSinkClass {
fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
f.debug_struct(&format!("GstAppSinkClass @ {:p}", self))
.field("basesink_class", &self.basesink_class)
.field("eos", &self.eos)
.field("new_preroll", &self.new_preroll)
.field("new_sample", &self.new_sample)
.field("pull_preroll", &self.pull_preroll)
.field("pull_sample", &self.pull_sample)
.field("try_pull_preroll", &self.try_pull_preroll)
.field("try_pull_sample", &self.try_pull_sample)
.field("try_pull_object", &self.try_pull_object)
.finish()
}
}
#[repr(C)]
pub struct _GstAppSinkPrivate {
_data: [u8; 0],
_marker: core::marker::PhantomData<(*mut u8, core::marker::PhantomPinned)>,
}
pub type GstAppSinkPrivate = *mut _GstAppSinkPrivate;
#[derive(Copy, Clone)]
#[repr(C)]
pub struct GstAppSrcCallbacks {
pub need_data: Option<unsafe extern "C" fn(*mut GstAppSrc, c_uint, gpointer)>,
pub enough_data: Option<unsafe extern "C" fn(*mut GstAppSrc, gpointer)>,
pub seek_data: Option<unsafe extern "C" fn(*mut GstAppSrc, u64, gpointer) -> gboolean>,
pub _gst_reserved: [gpointer; 4],
}
impl ::std::fmt::Debug for GstAppSrcCallbacks {
fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
f.debug_struct(&format!("GstAppSrcCallbacks @ {:p}", self))
.field("need_data", &self.need_data)
.field("enough_data", &self.enough_data)
.field("seek_data", &self.seek_data)
.finish()
}
}
#[derive(Copy, Clone)]
#[repr(C)]
pub struct GstAppSrcClass {
pub basesrc_class: gst_base::GstBaseSrcClass,
pub need_data: Option<unsafe extern "C" fn(*mut GstAppSrc, c_uint)>,
pub enough_data: Option<unsafe extern "C" fn(*mut GstAppSrc)>,
pub seek_data: Option<unsafe extern "C" fn(*mut GstAppSrc, u64) -> gboolean>,
pub push_buffer:
Option<unsafe extern "C" fn(*mut GstAppSrc, *mut gst::GstBuffer) -> gst::GstFlowReturn>,
pub end_of_stream: Option<unsafe extern "C" fn(*mut GstAppSrc) -> gst::GstFlowReturn>,
pub push_sample:
Option<unsafe extern "C" fn(*mut GstAppSrc, *mut gst::GstSample) -> gst::GstFlowReturn>,
pub push_buffer_list:
Option<unsafe extern "C" fn(*mut GstAppSrc, *mut gst::GstBufferList) -> gst::GstFlowReturn>,
pub _gst_reserved: [gpointer; 2],
}
impl ::std::fmt::Debug for GstAppSrcClass {
fn
|
(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
f.debug_struct(&format!("GstAppSrcClass @ {:p}", self))
.field("basesrc_class", &self.basesrc_class)
.field("need_data", &self.need_data)
.field("enough_data", &self.enough_data)
.field("seek_data", &self.seek_data)
.field("push_buffer", &self.push_buffer)
.field("end_of_stream", &self.end_of_stream)
.field("push_sample", &self.push_sample)
.field("push_buffer_list", &self.push_buffer_list)
.finish()
}
}
#[repr(C)]
pub struct _GstAppSrcPrivate {
_data: [u8; 0],
_marker: core::marker::PhantomData<(*mut u8, core::marker::PhantomPinned)>,
}
pub type GstAppSrcPrivate = *mut _GstAppSrcPrivate;
// Classes
#[derive(Copy, Clone)]
#[repr(C)]
pub struct GstAppSink {
pub basesink: gst_base::GstBaseSink,
pub priv_: *mut GstAppSinkPrivate,
pub _gst_reserved: [gpointer; 4],
}
impl ::std::fmt::Debug for GstAppSink {
fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
f.debug_struct(&format!("GstAppSink @ {:p}", self))
.field("basesink", &self.basesink)
.finish()
}
}
#[derive(Copy, Clone)]
#[repr(C)]
pub struct GstAppSrc {
pub basesrc: gst_base::GstBaseSrc,
pub priv_: *mut GstAppSrcPrivate,
pub _gst_reserved: [gpointer; 4],
}
impl ::std::fmt::Debug for GstAppSrc {
fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
f.debug_struct(&format!("GstAppSrc @ {:p}", self))
.field("basesrc", &self.basesrc)
.finish()
}
}
#[link(name = "gstapp-1.0")]
extern "C" {
//=========================================================================
// GstAppLeakyType
//=========================================================================
#[cfg(any(feature = "v1_20", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v1_20")))]
pub fn gst_app_leaky_type_get_type() -> GType;
//=========================================================================
// GstAppStreamType
//=========================================================================
pub fn gst_app_stream_type_get_type() -> GType;
//=========================================================================
// GstAppSink
//=========================================================================
pub fn gst_app_sink_get_type() -> GType;
#[cfg(any(feature = "v1_12", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v1_12")))]
pub fn gst_app_sink_get_buffer_list_support(appsink: *mut GstAppSink) -> gboolean;
pub fn gst_app_sink_get_caps(appsink: *mut GstAppSink) -> *mut gst::GstCaps;
pub fn gst_app_sink_get_drop(appsink: *mut GstAppSink) -> gboolean;
pub fn gst_app_sink_get_emit_signals(appsink: *mut GstAppSink) -> gboolean;
pub fn gst_app_sink_get_max_buffers(appsink: *mut GstAppSink) -> c_uint;
pub fn gst_app_sink_get_wait_on_eos(appsink: *mut GstAppSink) -> gboolean;
pub fn gst_app_sink_is_eos(appsink: *mut GstAppSink) -> gboolean;
#[cfg(any(feature = "v1_20", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v1_20")))]
pub fn gst_app_sink_pull_object(appsink: *mut GstAppSink) -> *mut gst::GstMiniObject;
pub fn gst_app_sink_pull_preroll(appsink: *mut GstAppSink) -> *mut gst::GstSample;
pub fn gst_app_sink_pull_sample(appsink: *mut GstAppSink) -> *mut gst::GstSample;
#[cfg(any(feature = "v1_12", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v1_12")))]
pub fn gst_app_sink_set_buffer_list_support(appsink: *mut GstAppSink, enable_lists: gboolean);
pub fn gst_app_sink_set_callbacks(
appsink: *mut GstAppSink,
callbacks: *mut GstAppSinkCallbacks,
user_data: gpointer,
notify: glib::GDestroyNotify,
);
pub fn gst_app_sink_set_caps(appsink: *mut GstAppSink, caps: *const gst::GstCaps);
pub fn gst_app_sink_set_drop(appsink: *mut GstAppSink, drop: gboolean);
pub fn gst_app_sink_set_emit_signals(appsink: *mut GstAppSink, emit: gboolean);
pub fn gst_app_sink_set_max_buffers(appsink: *mut GstAppSink, max: c_uint);
pub fn gst_app_sink_set_wait_on_eos(appsink: *mut GstAppSink, wait: gboolean);
#[cfg(any(feature = "v1_20", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v1_20")))]
pub fn gst_app_sink_try_pull_object(
appsink: *mut GstAppSink,
timeout: gst::GstClockTime,
) -> *mut gst::GstMiniObject;
#[cfg(any(feature = "v1_10", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v1_10")))]
pub fn gst_app_sink_try_pull_preroll(
appsink: *mut GstAppSink,
timeout: gst::GstClockTime,
) -> *mut gst::GstSample;
#[cfg(any(feature = "v1_10", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v1_10")))]
pub fn gst_app_sink_try_pull_sample(
appsink: *mut GstAppSink,
timeout: gst::GstClockTime,
) -> *mut gst::GstSample;
//=========================================================================
// GstAppSrc
//=========================================================================
pub fn gst_app_src_get_type() -> GType;
pub fn gst_app_src_end_of_stream(appsrc: *mut GstAppSrc) -> gst::GstFlowReturn;
pub fn gst_app_src_get_caps(appsrc: *mut GstAppSrc) -> *mut gst::GstCaps;
#[cfg(any(feature = "v1_20", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v1_20")))]
pub fn gst_app_src_get_current_level_buffers(appsrc: *mut GstAppSrc) -> u64;
pub fn gst_app_src_get_current_level_bytes(appsrc: *mut GstAppSrc) -> u64;
#[cfg(any(feature = "v1_20", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v1_20")))]
pub fn gst_app_src_get_current_level_time(appsrc: *mut GstAppSrc) -> gst::GstClockTime;
#[cfg(any(feature = "v1_10", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v1_10")))]
pub fn gst_app_src_get_duration(appsrc: *mut GstAppSrc) -> gst::GstClockTime;
pub fn gst_app_src_get_emit_signals(appsrc: *mut GstAppSrc) -> gboolean;
pub fn gst_app_src_get_latency(appsrc: *mut GstAppSrc, min: *mut u64, max: *mut u64);
#[cfg(any(feature = "v1_20", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v1_20")))]
pub fn gst_app_src_get_leaky_type(appsrc: *mut GstAppSrc) -> GstAppLeakyType;
#[cfg(any(feature = "v1_20", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v1_20")))]
pub fn gst_app_src_get_max_buffers(appsrc: *mut GstAppSrc) -> u64;
pub fn gst_app_src_get_max_bytes(appsrc: *mut GstAppSrc) -> u64;
#[cfg(any(feature = "v1_20", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v1_20")))]
pub fn gst_app_src_get_max_time(appsrc: *mut GstAppSrc) -> gst::GstClockTime;
pub fn gst_app_src_get_size(appsrc: *mut GstAppSrc) -> i64;
pub fn gst_app_src_get_stream_type(appsrc: *mut GstAppSrc) -> GstAppStreamType;
pub fn gst_app_src_push_buffer(
appsrc: *mut GstAppSrc,
buffer: *mut gst::GstBuffer,
) -> gst::GstFlowReturn;
#[cfg(any(feature = "v1_14", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v1_14")))]
pub fn gst_app_src_push_buffer_list(
appsrc: *mut GstAppSrc,
buffer_list: *mut gst::GstBufferList,
) -> gst::GstFlowReturn;
pub fn gst_app_src_push_sample(
appsrc: *mut GstAppSrc,
sample: *mut gst::GstSample,
) -> gst::GstFlowReturn;
pub fn gst_app_src_set_callbacks(
appsrc: *mut GstAppSrc,
callbacks: *mut GstAppSrcCallbacks,
user_data: gpointer,
notify: glib::GDestroyNotify,
);
pub fn gst_app_src_set_caps(appsrc: *mut GstAppSrc, caps: *const gst::GstCaps);
#[cfg(any(feature = "v1_10", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v1_10")))]
pub fn gst_app_src_set_duration(appsrc: *mut GstAppSrc, duration: gst::GstClockTime);
pub fn gst_app_src_set_emit_signals(appsrc: *mut GstAppSrc, emit: gboolean);
pub fn gst_app_src_set_latency(appsrc: *mut GstAppSrc, min: u64, max: u64);
#[cfg(any(feature = "v1_20", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v1_20")))]
pub fn gst_app_src_set_leaky_type(appsrc: *mut GstAppSrc, leaky: GstAppLeakyType);
#[cfg(any(feature = "v1_20", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v1_20")))]
pub fn gst_app_src_set_max_buffers(appsrc: *mut GstAppSrc, max: u64);
pub fn gst_app_src_set_max_bytes(appsrc: *mut GstAppSrc, max: u64);
#[cfg(any(feature = "v1_20", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v1_20")))]
pub fn gst_app_src_set_max_time(appsrc: *mut GstAppSrc, max: gst::GstClockTime);
pub fn gst_app_src_set_size(appsrc: *mut GstAppSrc, size: i64);
pub fn gst_app_src_set_stream_type(appsrc: *mut GstAppSrc, type_: GstAppStreamType);
}
|
fmt
|
.eslintrc.js
|
module.exports = {
root: true,
parserOptions: {
parser: 'babel-eslint',
sourceType: 'module'
},
env: {
browser: true,
node: true,
"cypress/globals": true
},
extends: [
'standard',
'plugin:vue/recommended'
],
globals: {
__static: true
},
plugins: [
'vue',
"cypress"
],
'rules': {
// allow paren-less arrow functions
'arrow-parens': 0,
// allow async-await
'generator-star-spacing': 0,
// allow debugger during development
'no-debugger': process.env.NODE_ENV === 'production' ? 2 : 0,
'max-len': [2, 120],
'space-before-function-paren': [2, {
"anonymous": "never",
"named": "never",
"asyncArrow": "always"
}], // was always
'vue/require-default-prop': 2, // was 1
'vue/order-in-components': 2, // was 1
'vue/max-attributes-per-line': 0, // was 1
'vue/singleline-html-element-content-newline': 0 // was 1
|
}
|
}
|
asyncio_queue.py
|
# asyncio_queue.py
import asyncio
async def consumer(n, _queue):
|
async def producer(_queue, workers):
""":type _queue asyncio.Queue"""
print('producer: starting')
for i in range(workers * 3):
await _queue.put(i)
print('producer: add task {} to queue'.format(i))
print('producer: adding stop signals to the queue')
for i in range(workers):
await _queue.put(None)
print('producer: waiting for queue to empty')
await _queue.join()
print('producer: ending')
async def main(loop, _consumers):
queue = asyncio.Queue(maxsize=_consumers)
consumers = [loop.create_task(consumer(i, queue)) for i in range(_consumers)]
prod = loop.create_task(producer(queue, _consumers))
await asyncio.wait(consumers + [prod])
event_loop = asyncio.get_event_loop()
event_loop.run_until_complete(main(event_loop, 2))
event_loop.close()
|
""":type _queue asyncio.Queue"""
# print('consumer {}: waiting for item'.format(n))
while True:
print('consumer {}: waiting for item'.format(n))
item = await _queue.get()
print('consumer {}: has item {}'.format(n, item))
if item is None:
_queue.task_done()
break
else:
await asyncio.sleep(.01 * item)
_queue.task_done()
print('consumer {}: ending'.format(n))
|
extensions.rs
|
/* BSD 3-Clause License
*
* Copyright © 2019, Alexander Krivács Schrøder <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
//! # Extension traits for doryen-rs types.
use crate::FPosition;
use doryen_rs::InputApi;
/// Defines extension methods for the `InputApi` type.
pub trait InputApiExtensions {
/// return the current mouse position in console cell position
fn mouse_position(self) -> FPosition;
}
impl InputApiExtensions for &mut dyn InputApi {
fn mouse_position(self) -> FPosition {
|
let mouse_pos = self.mouse_pos();
FPosition::new(mouse_pos.0, mouse_pos.1)
}
}
|
|
__main__.py
|
from datetime import datetime, timedelta
from .args import parse_arguments
from .ffmpeg_runner import run_ffmpeg
from .image_generator import generate_frame, generate_random_color_dvd_logo, get_scaled_dvd_logo
from .position_generator import generate_dvd_positions
def main():
|
if __name__ == '__main__':
main()
|
args = parse_arguments()
ffmpeg = run_ffmpeg(args.fps, args.live, *args.ffmpeg_args)
resolution = (int(args.width / args.scale), int(args.height / args.scale))
scl = (240 / args.height) * 40
speed = int(1000 / args.scale / scl * 2)
dvd_logo = get_scaled_dvd_logo(args.scale, scl)
dvd_logo_color = dvd_logo
total_points = int(100 * args.fps) if args.live else int(args.duration * args.fps)
points = generate_dvd_positions(
resolution,
(dvd_logo.width, dvd_logo.height),
speed,
args.fps,
None if args.live else args.duration,
)
i = 1
last_print = datetime.utcnow() - timedelta(seconds=2)
for x, y, recalculate in points:
start_frame_time = datetime.utcnow()
if recalculate:
dvd_logo_color = generate_random_color_dvd_logo(dvd_logo)
generate_frame((int(x), int(y)), resolution, dvd_logo, dvd_logo_color).save(ffmpeg.stdin, 'BMP')
end_frame_time = datetime.utcnow()
took = end_frame_time - start_frame_time
tt = took.seconds + took.microseconds / 1000000
if (end_frame_time - last_print).seconds >= 1:
print(f'\r{i * 100 // total_points}% {i}: ({int(x)}, {int(y)}) - {tt}s \033[7D', end='')
last_print = end_frame_time
i += 1
print(f'\r{i * 100 // total_points}% {i}: ({int(x)}, {int(y)}) - {tt}s ')
print('Waiting to ffmpeg to finish')
ffmpeg.stdin.close()
ffmpeg.wait()
print('Finished')
|
transaction_db.rs
|
use crate::{
db_vector::DBVector,
ffi_util::to_cstring,
handle::{ConstHandle, Handle},
open_raw::{OpenRaw, OpenRawFFI},
ops::*,
write_batch::WriteBatch,
ColumnFamily, DBRawIterator, Error, Options, ReadOptions, Transaction, WriteOptions,
};
use crate::ffi;
use libc::{c_char, c_uchar, size_t};
use std::collections::BTreeMap;
use std::marker::PhantomData;
use std::path::Path;
use std::path::PathBuf;
use std::ptr;
/// A transaction database.
pub struct TransactionDB {
inner: *mut ffi::rocksdb_transactiondb_t,
path: PathBuf,
cfs: BTreeMap<String, ColumnFamily>,
}
impl TransactionDB {
pub fn path(&self) -> &Path {
self.path.as_path()
}
}
impl Handle<ffi::rocksdb_transactiondb_t> for TransactionDB {
fn handle(&self) -> *mut ffi::rocksdb_transactiondb_t {
self.inner
}
}
impl Open for TransactionDB {}
impl OpenRaw for TransactionDB {
type Pointer = ffi::rocksdb_transactiondb_t;
type Descriptor = TransactionDBOptions;
|
if input.num_column_families <= 0 {
ffi_try!(ffi::rocksdb_transactiondb_open(
input.options,
input.open_descriptor.inner,
input.path,
))
} else {
ffi_try!(ffi::rocksdb_transactiondb_open_column_families(
input.options,
input.open_descriptor.inner,
input.path,
input.num_column_families,
input.column_family_names,
input.column_family_options,
input.column_family_handles,
))
}
};
Ok(pointer)
}
fn build<I>(
path: PathBuf,
_open_descriptor: Self::Descriptor,
pointer: *mut Self::Pointer,
column_families: I,
) -> Result<Self, Error>
where
I: IntoIterator<Item = (String, *mut ffi::rocksdb_column_family_handle_t)>,
{
let cfs: BTreeMap<_, _> = column_families
.into_iter()
.map(|(k, h)| (k, ColumnFamily::new(h)))
.collect();
Ok(TransactionDB {
inner: pointer,
path,
cfs,
})
}
}
impl GetColumnFamilys for TransactionDB {
fn get_cfs(&self) -> &BTreeMap<String, ColumnFamily> {
&self.cfs
}
fn get_mut_cfs(&mut self) -> &mut BTreeMap<String, ColumnFamily> {
&mut self.cfs
}
}
impl Read for TransactionDB {}
impl Write for TransactionDB {}
unsafe impl Send for TransactionDB {}
unsafe impl Sync for TransactionDB {}
impl TransactionBegin for TransactionDB {
type WriteOptions = WriteOptions;
type TransactionOptions = TransactionOptions;
fn transaction(
&self,
write_options: &WriteOptions,
tx_options: &TransactionOptions,
) -> Transaction<'_, TransactionDB> {
unsafe {
let inner = ffi::rocksdb_transaction_begin(
self.inner,
write_options.handle(),
tx_options.inner,
ptr::null_mut(),
);
Transaction::new(inner)
}
}
}
impl Iterate for TransactionDB {
fn get_raw_iter<'a: 'b, 'b>(&'a self, readopts: &ReadOptions) -> DBRawIterator<'b> {
unsafe {
DBRawIterator {
inner: ffi::rocksdb_transactiondb_create_iterator(self.inner, readopts.handle()),
db: PhantomData,
}
}
}
}
impl IterateCF for TransactionDB {
fn get_raw_iter_cf<'a: 'b, 'b>(
&'a self,
cf_handle: &ColumnFamily,
readopts: &ReadOptions,
) -> Result<DBRawIterator<'b>, Error> {
unsafe {
Ok(DBRawIterator {
inner: ffi::rocksdb_transactiondb_create_iterator_cf(
self.inner,
readopts.handle(),
cf_handle.handle(),
),
db: PhantomData,
})
}
}
}
impl Drop for TransactionDB {
fn drop(&mut self) {
unsafe {
ffi::rocksdb_transactiondb_close(self.inner);
}
}
}
pub struct TransactionDBOptions {
inner: *mut ffi::rocksdb_transactiondb_options_t,
}
impl TransactionDBOptions {
/// Create new transaction options
pub fn new() -> TransactionDBOptions {
unsafe {
let inner = ffi::rocksdb_transactiondb_options_create();
TransactionDBOptions { inner }
}
}
pub fn set_default_lock_timeout(&self, default_lock_timeout: i64) {
unsafe {
ffi::rocksdb_transactiondb_options_set_default_lock_timeout(
self.inner,
default_lock_timeout,
)
}
}
pub fn set_max_num_locks(&self, max_num_locks: i64) {
unsafe { ffi::rocksdb_transactiondb_options_set_max_num_locks(self.inner, max_num_locks) }
}
pub fn set_num_stripes(&self, num_stripes: usize) {
unsafe { ffi::rocksdb_transactiondb_options_set_num_stripes(self.inner, num_stripes) }
}
pub fn set_transaction_lock_timeout(&self, txn_lock_timeout: i64) {
unsafe {
ffi::rocksdb_transactiondb_options_set_transaction_lock_timeout(
self.inner,
txn_lock_timeout,
)
}
}
}
impl Drop for TransactionDBOptions {
fn drop(&mut self) {
unsafe {
ffi::rocksdb_transactiondb_options_destroy(self.inner);
}
}
}
impl Default for TransactionDBOptions {
fn default() -> TransactionDBOptions {
TransactionDBOptions::new()
}
}
pub struct TransactionOptions {
inner: *mut ffi::rocksdb_transaction_options_t,
}
impl TransactionOptions {
/// Create new transaction options
pub fn new() -> TransactionOptions {
unsafe {
let inner = ffi::rocksdb_transaction_options_create();
TransactionOptions { inner }
}
}
pub fn set_deadlock_detect(&self, deadlock_detect: bool) {
unsafe {
ffi::rocksdb_transaction_options_set_deadlock_detect(
self.inner,
deadlock_detect as c_uchar,
)
}
}
pub fn set_deadlock_detect_depth(&self, depth: i64) {
unsafe { ffi::rocksdb_transaction_options_set_deadlock_detect_depth(self.inner, depth) }
}
pub fn set_expiration(&self, expiration: i64) {
unsafe { ffi::rocksdb_transaction_options_set_expiration(self.inner, expiration) }
}
pub fn set_lock_timeout(&self, lock_timeout: i64) {
unsafe { ffi::rocksdb_transaction_options_set_lock_timeout(self.inner, lock_timeout) }
}
pub fn set_max_write_batch_size(&self, size: usize) {
unsafe { ffi::rocksdb_transaction_options_set_max_write_batch_size(self.inner, size) }
}
pub fn set_snapshot(&mut self, set_snapshot: bool) {
unsafe {
ffi::rocksdb_transaction_options_set_set_snapshot(self.inner, set_snapshot as c_uchar);
}
}
}
impl Drop for TransactionOptions {
fn drop(&mut self) {
unsafe {
ffi::rocksdb_transaction_options_destroy(self.inner);
}
}
}
impl Default for TransactionOptions {
fn default() -> TransactionOptions {
TransactionOptions::new()
}
}
impl CreateCheckpointObject for TransactionDB {
unsafe fn create_checkpoint_object_raw(&self) -> Result<*mut ffi::rocksdb_checkpoint_t, Error> {
Ok(ffi_try!(
ffi::rocksdb_transactiondb_checkpoint_object_create(self.inner,)
))
}
}
impl GetCF<ReadOptions> for TransactionDB {
fn get_cf_full<K: AsRef<[u8]>>(
&self,
cf: Option<&ColumnFamily>,
key: K,
readopts: Option<&ReadOptions>,
) -> Result<Option<DBVector>, Error> {
let mut default_readopts = None;
let ro_handle = ReadOptions::input_or_default(readopts, &mut default_readopts)?;
let key = key.as_ref();
let key_ptr = key.as_ptr() as *const c_char;
let key_len = key.len() as size_t;
unsafe {
let mut val_len: size_t = 0;
let val = match cf {
Some(cf) => ffi_try!(ffi::rocksdb_transactiondb_get_cf(
self.handle(),
ro_handle,
cf.handle(),
key_ptr,
key_len,
&mut val_len,
)),
None => ffi_try!(ffi::rocksdb_transactiondb_get(
self.handle(),
ro_handle,
key_ptr,
key_len,
&mut val_len,
)),
} as *mut u8;
if val.is_null() {
Ok(None)
} else {
Ok(Some(DBVector::from_c(val, val_len)))
}
}
}
}
impl PutCF<WriteOptions> for TransactionDB {
fn put_cf_full<K, V>(
&self,
cf: Option<&ColumnFamily>,
key: K,
value: V,
writeopts: Option<&WriteOptions>,
) -> Result<(), Error>
where
K: AsRef<[u8]>,
V: AsRef<[u8]>,
{
let mut default_writeopts = None;
let wo_handle = WriteOptions::input_or_default(writeopts, &mut default_writeopts)?;
let key = key.as_ref();
let value = value.as_ref();
let key_ptr = key.as_ptr() as *const c_char;
let key_len = key.len() as size_t;
let val_ptr = value.as_ptr() as *const c_char;
let val_len = value.len() as size_t;
unsafe {
match cf {
Some(cf) => ffi_try!(ffi::rocksdb_transactiondb_put_cf(
self.handle(),
wo_handle,
cf.handle(),
key_ptr,
key_len,
val_ptr,
val_len,
)),
None => ffi_try!(ffi::rocksdb_transactiondb_put(
self.handle(),
wo_handle,
key_ptr,
key_len,
val_ptr,
val_len,
)),
}
Ok(())
}
}
}
impl DeleteCF<WriteOptions> for TransactionDB {
fn delete_cf_full<K>(
&self,
cf: Option<&ColumnFamily>,
key: K,
writeopts: Option<&WriteOptions>,
) -> Result<(), Error>
where
K: AsRef<[u8]>,
{
let mut default_writeopts = None;
let wo_handle = WriteOptions::input_or_default(writeopts, &mut default_writeopts)?;
let key = key.as_ref();
let key_ptr = key.as_ptr() as *const c_char;
let key_len = key.len() as size_t;
unsafe {
match cf {
Some(cf) => ffi_try!(ffi::rocksdb_transactiondb_delete_cf(
self.handle(),
wo_handle,
cf.handle(),
key_ptr,
key_len,
)),
None => ffi_try!(ffi::rocksdb_transactiondb_delete(
self.handle(),
wo_handle,
key_ptr,
key_len,
)),
}
Ok(())
}
}
}
impl MergeCF<WriteOptions> for TransactionDB {
fn merge_cf_full<K, V>(
&self,
cf: Option<&ColumnFamily>,
key: K,
value: V,
writeopts: Option<&WriteOptions>,
) -> Result<(), Error>
where
K: AsRef<[u8]>,
V: AsRef<[u8]>,
{
let mut default_writeopts = None;
let wo_handle = WriteOptions::input_or_default(writeopts, &mut default_writeopts)?;
let key = key.as_ref();
let value = value.as_ref();
let key_ptr = key.as_ptr() as *const c_char;
let key_len = key.len() as size_t;
let val_ptr = value.as_ptr() as *const c_char;
let val_len = value.len() as size_t;
unsafe {
match cf {
Some(cf) => ffi_try!(ffi::rocksdb_transactiondb_merge_cf(
self.handle(),
wo_handle,
cf.handle(),
key_ptr,
key_len,
val_ptr,
val_len,
)),
None => ffi_try!(ffi::rocksdb_transactiondb_merge(
self.handle(),
wo_handle,
key_ptr,
key_len,
val_ptr,
val_len,
)),
}
Ok(())
}
}
}
impl CreateCF for TransactionDB {
fn create_cf<N: AsRef<str>>(&mut self, name: N, opts: &Options) -> Result<(), Error> {
let cname = to_cstring(
name.as_ref(),
"Failed to convert path to CString when opening rocksdb",
)?;
unsafe {
let cf_handle = ffi_try!(ffi::rocksdb_transactiondb_create_column_family(
self.handle(),
opts.const_handle(),
cname.as_ptr(),
));
self.get_mut_cfs()
.insert(name.as_ref().to_string(), ColumnFamily::new(cf_handle));
};
Ok(())
}
}
impl TransactionDB {
pub fn snapshot(&self) -> Snapshot<'_> {
let snapshot = unsafe { ffi::rocksdb_transactiondb_create_snapshot(self.inner) };
Snapshot {
db: self,
inner: snapshot,
}
}
}
pub struct Snapshot<'a> {
db: &'a TransactionDB,
inner: *const ffi::rocksdb_snapshot_t,
}
impl<'a> ConstHandle<ffi::rocksdb_snapshot_t> for Snapshot<'a> {
fn const_handle(&self) -> *const ffi::rocksdb_snapshot_t {
self.inner
}
}
impl<'a> Read for Snapshot<'a> {}
impl<'a> GetCF<ReadOptions> for Snapshot<'a> {
fn get_cf_full<K: AsRef<[u8]>>(
&self,
cf: Option<&ColumnFamily>,
key: K,
readopts: Option<&ReadOptions>,
) -> Result<Option<DBVector>, Error> {
let mut ro = readopts.cloned().unwrap_or_default();
ro.set_snapshot(self);
self.db.get_cf_full(cf, key, Some(&ro))
}
}
impl<'a> Drop for Snapshot<'a> {
fn drop(&mut self) {
unsafe {
ffi::rocksdb_transactiondb_release_snapshot(self.db.inner, self.inner);
}
}
}
impl Iterate for Snapshot<'_> {
fn get_raw_iter<'a: 'b, 'b>(&'a self, readopts: &ReadOptions) -> DBRawIterator<'b> {
let mut ro = readopts.to_owned();
ro.set_snapshot(self);
self.db.get_raw_iter(&ro)
}
}
impl IterateCF for Snapshot<'_> {
fn get_raw_iter_cf<'a: 'b, 'b>(
&'a self,
cf_handle: &ColumnFamily,
readopts: &ReadOptions,
) -> Result<DBRawIterator<'b>, Error> {
let mut ro = readopts.to_owned();
ro.set_snapshot(self);
self.db.get_raw_iter_cf(cf_handle, &ro)
}
}
impl WriteOps for TransactionDB {
fn write_full(
&self,
batch: &WriteBatch,
writeopts: Option<&WriteOptions>,
) -> Result<(), Error> {
let mut default_writeopts = None;
let wo_handle = WriteOptions::input_or_default(writeopts, &mut default_writeopts)?;
unsafe {
ffi_try!(ffi::rocksdb_transactiondb_write(
self.handle(),
wo_handle,
batch.handle(),
));
Ok(())
}
}
}
|
fn open_ffi(input: OpenRawFFI<'_, Self::Descriptor>) -> Result<*mut Self::Pointer, Error> {
let pointer = unsafe {
|
Triangle.tsx
|
import React from 'react';
import { StyleSheet, View } from 'react-native';
interface IProps {
color: string;
direction: 'up' | 'right' | 'down' | 'left';
height: number;
width: number;
}
export default function
|
(props: IProps) {
let borderStyle;
if (props.direction === 'up') {
borderStyle = {
borderBottomColor: props.color,
borderBottomWidth: props.height,
borderLeftColor: 'transparent',
borderLeftWidth: props.width / 2.0,
borderRightColor: 'transparent',
borderRightWidth: props.width / 2.0,
borderTopColor: 'transparent',
borderTopWidth: 0,
};
} else if (props.direction === 'right') {
borderStyle = {
borderBottomColor: 'transparent',
borderBottomWidth: props.height / 2.0,
borderLeftColor: props.color,
borderLeftWidth: props.width,
borderRightColor: 'transparent',
borderRightWidth: 0,
borderTopColor: 'transparent',
borderTopWidth: props.height / 2.0,
};
} else if (props.direction === 'down') {
borderStyle = {
borderBottomColor: 'transparent',
borderBottomWidth: 0,
borderLeftColor: 'transparent',
borderLeftWidth: props.width / 2.0,
borderRightColor: 'transparent',
borderRightWidth: props.width / 2.0,
borderTopColor: props.color,
borderTopWidth: props.height,
};
} else if (props.direction === 'left') {
borderStyle = {
borderBottomColor: 'transparent',
borderBottomWidth: props.height / 2.0,
borderLeftColor: 'transparent',
borderLeftWidth: 0,
borderRightColor: props.color,
borderRightWidth: props.width,
borderTopColor: 'transparent',
borderTopWidth: props.height / 2.0,
};
}
return <View style={[styles.basic, borderStyle]} />;
}
const styles = StyleSheet.create({
basic: {
backgroundColor: 'transparent',
borderStyle: 'solid',
height: 0,
width: 0,
},
});
|
Triangle
|
data.go
|
package main
import (
"database/sql"
"os"
_ "github.com/mattn/go-sqlite3"
)
type Data struct {
db *sql.DB
}
var data Data
const (
dbFilename = "./s3.sqlite"
)
func
|
() {
if _, err := os.Stat(dbFilename); os.IsNotExist(err) {
os.Create(dbFilename)
}
db, err := sql.Open("sqlite3", dbFilename)
if err != error(nil) {
exitErrorf("Could not open SQLite database: %v", err)
}
if _, err := db.Exec("CREATE TABLE IF NOT EXISTS objects (id INTEGER PRIMARY KEY AUTOINCREMENT, objectPath TEXT, processed TINYINT(1), error TINYINT(1))"); err != error(nil) {
exitErrorf("Could not create table 'objects': %v", err)
}
data.db = db
}
func (d Data) addPath(objectPath string) {
if _, err := d.db.Exec("INSERT INTO objects (objectPath, processed, error) VALUES (?, ?, ?)", objectPath, 0, 0); err != error(nil) {
exitErrorf("Failed to insert path in DB: %v", err)
}
}
type PathRecord struct {
Id int
Path string
}
func (d Data) getUnprocessedPaths(ch chan<- PathRecord) {
defer close(ch)
rows, err := d.db.Query("SELECT id, objectPath FROM objects WHERE processed = 0")
if err != error(nil) {
exitErrorf("Failed to query objects from DB: %v", err)
}
defer rows.Close()
for rows.Next() {
record := PathRecord{}
err := rows.Scan(&record.Id, &record.Path)
if err != error(nil) {
exitErrorf("Failed to read object record: %v", err)
}
ch <- record
}
}
func (d Data) setPathAsProcessed(id int, processingError error) {
if _, err := d.db.Exec("UPDATE objects SET processed = ?, error = ? WHERE id = ?", 1, processingError != error(nil), id); err != error(nil) {
exitErrorf("Failed to set object as processed: %v", err)
}
}
|
init
|
cloudasset_v1p4alpha1_messages.py
|
"""Generated message classes for cloudasset version v1p4alpha1.
The cloud asset API manages the history and inventory of cloud resources.
"""
# NOTE: This file is autogenerated and should not be edited by hand.
from __future__ import absolute_import
from apitools.base.protorpclite import messages as _messages
from apitools.base.py import encoding
package = 'cloudasset'
class AnalyzeIamPolicyResponse(_messages.Message):
r"""A response message for AssetService.AnalyzeIamPolicy.
Fields:
analysisResults: A list of IamPolicyAnalysisResult that matches the
request, or empty if no result is found.
fullyExplored: Represents whether all entries in the analysis_results have
been fully explored to answer the query in the request.
nonCriticalErrors: A list of non-critical errors happened during the
request handling to explain why `fully_explored` is false, or empty if
no error happened.
"""
analysisResults = _messages.MessageField('IamPolicyAnalysisResult', 1, repeated=True)
fullyExplored = _messages.BooleanField(2)
nonCriticalErrors = _messages.MessageField('GoogleCloudAssetV1p4alpha1AnalysisState', 3, repeated=True)
class Binding(_messages.Message):
r"""Associates `members` with a `role`.
Fields:
condition: The condition that is associated with this binding. NOTE: An
unsatisfied condition will not allow user access via current binding.
Different bindings, including their conditions, are examined
independently.
members: Specifies the identities requesting access for a Cloud Platform
resource. `members` can have the following values: * `allUsers`: A
special identifier that represents anyone who is on the internet;
with or without a Google account. * `allAuthenticatedUsers`: A special
identifier that represents anyone who is authenticated with a Google
account or a service account. * `user:{emailid}`: An email address that
represents a specific Google account. For example,
`[email protected]` . * `serviceAccount:{emailid}`: An email address
that represents a service account. For example, `my-other-
[email protected]`. * `group:{emailid}`: An email address
that represents a Google group. For example, `[email protected]`. *
`deleted:user:{emailid}?uid={uniqueid}`: An email address (plus unique
identifier) representing a user that has been recently deleted. For
example,`[email protected]?uid=123456789012345678901`. If the user is
recovered, this value reverts to `user:{emailid}` and the recovered user
retains the role in the binding. *
`deleted:serviceAccount:{emailid}?uid={uniqueid}`: An email address
(plus unique identifier) representing a service account that has been
recently deleted. For example, `my-other-
[email protected]?uid=123456789012345678901`. If the
service account is undeleted, this value reverts to
`serviceAccount:{emailid}` and the undeleted service account retains the
role in the binding. * `deleted:group:{emailid}?uid={uniqueid}`: An
email address (plus unique identifier) representing a Google group
that has been recently deleted. For example,
`[email protected]?uid=123456789012345678901`. If the group is
recovered, this value reverts to `group:{emailid}` and the recovered
group retains the role in the binding. * `domain:{domain}`: The G
Suite domain (primary) that represents all the users of that domain.
For example, `google.com` or `example.com`.
role: Role that is assigned to `members`. For example, `roles/viewer`,
`roles/editor`, or `roles/owner`.
"""
condition = _messages.MessageField('Expr', 1)
members = _messages.StringField(2, repeated=True)
role = _messages.StringField(3)
class CloudassetAnalyzeIamPolicyRequest(_messages.Message):
r"""A CloudassetAnalyzeIamPolicyRequest object.
Fields:
accessSelector_permissions: Optional. The permissions to appear in result.
accessSelector_roles: Optional. The roles to appear in result.
identitySelector_identity: Required. The identity appear in the form of
members in [IAM policy
binding](https://cloud.google.com/iam/reference/rest/v1/Binding).
options_expandGroups: Optional. If true, the identities section of the
result will expand any Google groups appearing in an IAM policy binding.
If identity_selector is specified, the identity in the result will be
determined by the selector, and this flag will have no effect. Default
is false.
options_expandResources: Optional. If true, the resource section of the
result will expand any resource attached to an IAM policy to include
resources lower in the resource hierarchy. For example, if the request
analyzes for which resources user A has permission P, and the results
include an IAM policy with P on a GCP folder, the results will also
include resources in that folder with permission P. If
resource_selector is specified, the resource section of the result will
be determined by the selector, and this flag will have no effect.
Default is false.
options_expandRoles: Optional. If true, the access section of result will
expand any roles appearing in IAM policy bindings to include their
permissions. If access_selector is specified, the access section of the
result will be determined by the selector, and this flag will have no
effect. Default is false.
options_maxFanoutsPerGroup: Optional. The maximum number of fanouts per
group when expand_groups is enabled.
options_maxFanoutsPerResource: Optional. The maximum number of fanouts per
parent resource, such as GCP Project etc., when expand_resources is
enabled.
options_outputGroupEdges: Optional. If true, the result will output group
identity edges, starting from the binding's group members, to any
expanded identities. Default is false.
options_outputPartialResultBeforeTimeout: Optional. If true, you will get
a response with partial result instead of a DEADLINE_EXCEEDED error when
your request processing takes longer than the deadline.
options_outputResourceEdges: Optional. If true, the result will output
resource edges, starting from the policy attached resource, to any
expanded resources. Default is false.
parent: Required. The relative name of root asset to do analysis . This
can only be an organization number (such as "organizations/123") for
now.
resourceSelector_fullResourceName: Required. The [full resource name](http
s://cloud.google.com/apis/design/resource_names#full_resource_name) .
"""
accessSelector_permissions = _messages.StringField(1, repeated=True)
accessSelector_roles = _messages.StringField(2, repeated=True)
identitySelector_identity = _messages.StringField(3)
options_expandGroups = _messages.BooleanField(4)
options_expandResources = _messages.BooleanField(5)
options_expandRoles = _messages.BooleanField(6)
options_maxFanoutsPerGroup = _messages.IntegerField(7, variant=_messages.Variant.INT32)
options_maxFanoutsPerResource = _messages.IntegerField(8, variant=_messages.Variant.INT32)
options_outputGroupEdges = _messages.BooleanField(9)
options_outputPartialResultBeforeTimeout = _messages.BooleanField(10)
options_outputResourceEdges = _messages.BooleanField(11)
parent = _messages.StringField(12, required=True)
resourceSelector_fullResourceName = _messages.StringField(13)
class Expr(_messages.Message):
r"""Represents an expression text. Example: title: "User account
presence" description: "Determines whether the request has a user
account" expression: "size(request.user) > 0"
Fields:
description: An optional description of the expression. This is a longer
text which describes the expression, e.g. when hovered over it in a UI.
expression: Textual representation of an expression in Common Expression
Language syntax. The application context of the containing message
determines which well-known feature set of CEL is supported.
location: An optional string indicating the location of the expression for
error reporting, e.g. a file name and a position in the file.
title: An optional title for the expression, i.e. a short string
describing its purpose. This can be used e.g. in UIs which allow to
enter the expression.
"""
description = _messages.StringField(1)
expression = _messages.StringField(2)
location = _messages.StringField(3)
title = _messages.StringField(4)
class GoogleCloudAssetV1p4alpha1Access(_messages.Message):
r"""A role or permission that appears in an access control list.
Fields:
analysisState: The analysis state of this access node.
permission: The permission.
role: The role.
"""
analysisState = _messages.MessageField('GoogleCloudAssetV1p4alpha1AnalysisState', 1)
permission = _messages.StringField(2)
role = _messages.StringField(3)
class GoogleCloudAssetV1p4alpha1AccessControlList(_messages.Message):
r"""An access control list, derived from the above IAM policy binding, which
contains a set of resources and accesses. May include one item from each set
to compose an access control entry. NOTICE that there could be multiple
access control lists for one IAM policy binding. The access control lists
are created per resource type. For example, assume we have the following
cases in one IAM policy binding: - Permission P1 and P2 apply to resource R1
and R2 of resource type RT1; - Permission P3 applies to resource R3 and R4
of resource type RT2; This will result in the following access control
lists: - AccessControlList 1: RT1, [R1, R2], [P1, P2] - AccessControlList 2:
RT2, [R3, R4], [P3]
Fields:
accesses: The accesses that match one of the following conditions: - The
access_selector, if it is specified in request; - Otherwise, access
specifiers reachable from the policy binding's role.
baseResourceType: The unified resource type name of the resource type that
this access control list is based on, such as
"compute.googleapis.com/Instance" for Compute Engine instance, etc.
resourceEdges: Resource edges of the graph starting from the policy
attached resource to any descendant resources. The Edge.source_node
contains the full resource name of a parent resource and
Edge.target_node contains the full resource name of a child resource.
This field is present only if the output_resource_edges option is
enabled in request.
resources: The resources that match one of the following conditions: - The
resource_selector, if it is specified in request; - Otherwise, resources
reachable from the policy attached resource.
"""
accesses = _messages.MessageField('GoogleCloudAssetV1p4alpha1Access', 1, repeated=True)
baseResourceType = _messages.StringField(2)
resourceEdges = _messages.MessageField('GoogleCloudAssetV1p4alpha1Edge', 3, repeated=True)
resources = _messages.MessageField('GoogleCloudAssetV1p4alpha1Resource', 4, repeated=True)
class GoogleCloudAssetV1p4alpha1AnalysisState(_messages.Message):
r"""Represents analysis state of each node in the result graph or non-
critical errors in the response.
Enums:
CodeValueValuesEnum: The Google standard error code that best describes
the state. For example: - OK means the node has been successfully
explored; - PERMISSION_DENIED means an access denied error is
encountered; - DEADLINE_EXCEEDED means the node hasn't been explored in
time;
Fields:
cause: The human-readable description of the cause of failure.
code: The Google standard error code that best describes the state. For
example: - OK means the node has been successfully explored; -
PERMISSION_DENIED means an access denied error is encountered; -
DEADLINE_EXCEEDED means the node hasn't been explored in time;
"""
class CodeValueValuesEnum(_messages.Enum):
r"""The Google standard error code that best describes the state. For
example: - OK means the node has been successfully explored; -
PERMISSION_DENIED means an access denied error is encountered; -
DEADLINE_EXCEEDED means the node hasn't been explored in time;
Values:
OK: Not an error; returned on success HTTP Mapping: 200 OK
CANCELLED: The operation was cancelled, typically by the caller. HTTP
Mapping: 499 Client Closed Request
UNKNOWN: Unknown error. For example, this error may be returned when a
`Status` value received from another address space belongs to an error
space that is not known in this address space. Also errors raised by
APIs that do not return enough error information may be converted to
this error. HTTP Mapping: 500 Internal Server Error
INVALID_ARGUMENT: The client specified an invalid argument. Note that
this differs from `FAILED_PRECONDITION`. `INVALID_ARGUMENT` indicates
arguments that are problematic regardless of the state of the system
(e.g., a malformed file name). HTTP Mapping: 400 Bad Request
DEADLINE_EXCEEDED: The deadline expired before the operation could
complete. For operations that change the state of the system, this
error may be returned even if the operation has completed
successfully. For example, a successful response from a server could
have been delayed long enough for the deadline to expire. HTTP
Mapping: 504 Gateway Timeout
NOT_FOUND: Some requested entity (e.g., file or directory) was not
found. Note to server developers: if a request is denied for an
entire class of users, such as gradual feature rollout or undocumented
whitelist, `NOT_FOUND` may be used. If a request is denied for some
users within a class of users, such as user-based access control,
`PERMISSION_DENIED` must be used. HTTP Mapping: 404 Not Found
ALREADY_EXISTS: The entity that a client attempted to create (e.g., file
or directory) already exists. HTTP Mapping: 409 Conflict
PERMISSION_DENIED: The caller does not have permission to execute the
specified operation. `PERMISSION_DENIED` must not be used for
rejections caused by exhausting some resource (use
`RESOURCE_EXHAUSTED` instead for those errors). `PERMISSION_DENIED`
must not be used if the caller can not be identified (use
`UNAUTHENTICATED` instead for those errors). This error code does not
imply the request is valid or the requested entity exists or satisfies
other pre-conditions. HTTP Mapping: 403 Forbidden
UNAUTHENTICATED: The request does not have valid authentication
credentials for the operation. HTTP Mapping: 401 Unauthorized
RESOURCE_EXHAUSTED: Some resource has been exhausted, perhaps a per-user
quota, or perhaps the entire file system is out of space. HTTP
Mapping: 429 Too Many Requests
FAILED_PRECONDITION: The operation was rejected because the system is
not in a state required for the operation's execution. For example,
the directory to be deleted is non-empty, an rmdir operation is
applied to a non-directory, etc. Service implementors can use the
following guidelines to decide between `FAILED_PRECONDITION`,
`ABORTED`, and `UNAVAILABLE`: (a) Use `UNAVAILABLE` if the client can
retry just the failing call. (b) Use `ABORTED` if the client should
retry at a higher level (e.g., when a client-specified test-and-
set fails, indicating the client should restart a read-modify-
write sequence). (c) Use `FAILED_PRECONDITION` if the client should
not retry until the system state has been explicitly fixed.
E.g., if an "rmdir" fails because the directory is non-empty,
`FAILED_PRECONDITION` should be returned since the client should
not retry unless the files are deleted from the directory. HTTP
Mapping: 400 Bad Request
ABORTED: The operation was aborted, typically due to a concurrency issue
such as a sequencer check failure or transaction abort. See the
guidelines above for deciding between `FAILED_PRECONDITION`,
`ABORTED`, and `UNAVAILABLE`. HTTP Mapping: 409 Conflict
OUT_OF_RANGE: The operation was attempted past the valid range. E.g.,
seeking or reading past end-of-file. Unlike `INVALID_ARGUMENT`, this
error indicates a problem that may be fixed if the system state
changes. For example, a 32-bit file system will generate
`INVALID_ARGUMENT` if asked to read at an offset that is not in the
range [0,2^32-1], but it will generate `OUT_OF_RANGE` if asked to read
from an offset past the current file size. There is a fair bit of
overlap between `FAILED_PRECONDITION` and `OUT_OF_RANGE`. We
recommend using `OUT_OF_RANGE` (the more specific error) when it
applies so that callers who are iterating through a space can easily
look for an `OUT_OF_RANGE` error to detect when they are done. HTTP
Mapping: 400 Bad Request
UNIMPLEMENTED: The operation is not implemented or is not
supported/enabled in this service. HTTP Mapping: 501 Not Implemented
INTERNAL: Internal errors. This means that some invariants expected by
the underlying system have been broken. This error code is reserved
for serious errors. HTTP Mapping: 500 Internal Server Error
UNAVAILABLE: The service is currently unavailable. This is most likely
a transient condition, which can be corrected by retrying with a
backoff. Note that it is not always safe to retry non-idempotent
operations. See the guidelines above for deciding between
`FAILED_PRECONDITION`, `ABORTED`, and `UNAVAILABLE`. HTTP Mapping:
503 Service Unavailable
DATA_LOSS: Unrecoverable data loss or corruption. HTTP Mapping: 500
Internal Server Error
"""
OK = 0
CANCELLED = 1
UNKNOWN = 2
INVALID_ARGUMENT = 3
DEADLINE_EXCEEDED = 4
NOT_FOUND = 5
ALREADY_EXISTS = 6
PERMISSION_DENIED = 7
UNAUTHENTICATED = 8
RESOURCE_EXHAUSTED = 9
FAILED_PRECONDITION = 10
ABORTED = 11
OUT_OF_RANGE = 12
UNIMPLEMENTED = 13
INTERNAL = 14
UNAVAILABLE = 15
DATA_LOSS = 16
cause = _messages.StringField(1)
code = _messages.EnumField('CodeValueValuesEnum', 2)
class GoogleCloudAssetV1p4alpha1Edge(_messages.Message):
r"""A directional edge.
Fields:
sourceNode: The source node of the edge.
targetNode: The target node of the edge.
|
"""
sourceNode = _messages.StringField(1)
targetNode = _messages.StringField(2)
class GoogleCloudAssetV1p4alpha1Identity(_messages.Message):
r"""An identity that appears in an access control list.
Fields:
analysisState: The analysis state of this identity node.
name: The identity name in any form of members appear in [IAM policy
binding](https://cloud.google.com/iam/reference/rest/v1/Binding), such
as: - user:[email protected] - group:[email protected] -
serviceAccount:[email protected] -
projectOwner:some_project_id - domain:google.com - allUsers - etc.
"""
analysisState = _messages.MessageField('GoogleCloudAssetV1p4alpha1AnalysisState', 1)
name = _messages.StringField(2)
class GoogleCloudAssetV1p4alpha1IdentityList(_messages.Message):
r"""A GoogleCloudAssetV1p4alpha1IdentityList object.
Fields:
groupEdges: Group identity edges of the graph starting from the binding's
group members to any node of the identities. The Edge.source_node
contains a group, such as "group:[email protected]". The
Edge.target_node contains a member of the group, such as
"group:[email protected]" or "user:[email protected]". This field is present
only if the output_group_edges option is enabled in request.
identities: Only the identities that match one of the following conditions
will be presented: - The identity_selector, if it is specified in
request; - Otherwise, identities reachable from the policy binding's
members.
"""
groupEdges = _messages.MessageField('GoogleCloudAssetV1p4alpha1Edge', 1, repeated=True)
identities = _messages.MessageField('GoogleCloudAssetV1p4alpha1Identity', 2, repeated=True)
class GoogleCloudAssetV1p4alpha1Resource(_messages.Message):
r"""A GCP resource that appears in an access control list.
Fields:
analysisState: The analysis state of this resource node.
fullResourceName: The [full resource name](https://aip.dev/122#full-
resource-names).
"""
analysisState = _messages.MessageField('GoogleCloudAssetV1p4alpha1AnalysisState', 1)
fullResourceName = _messages.StringField(2)
class IamPolicyAnalysisResult(_messages.Message):
r"""IAM Policy analysis result, consisting of one IAM policy binding and
derived access control lists.
Fields:
accessControlLists: The access control lists derived from the iam_binding
that match or potentially match resource and access selectors specified
in the request.
attachedResourceFullName: The full name of the resource to which the
iam_binding policy attaches.
fullyExplored: Represents whether all nodes in the transitive closure of
the iam_binding node have been explored.
iamBinding: The Cloud IAM policy binding under analysis.
identityList: The identity list derived from members of the iam_binding
that match or potentially match identity selector specified in the
request.
"""
accessControlLists = _messages.MessageField('GoogleCloudAssetV1p4alpha1AccessControlList', 1, repeated=True)
attachedResourceFullName = _messages.StringField(2)
fullyExplored = _messages.BooleanField(3)
iamBinding = _messages.MessageField('Binding', 4)
identityList = _messages.MessageField('GoogleCloudAssetV1p4alpha1IdentityList', 5)
class StandardQueryParameters(_messages.Message):
r"""Query parameters accepted by all methods.
Enums:
FXgafvValueValuesEnum: V1 error format.
AltValueValuesEnum: Data format for response.
Fields:
f__xgafv: V1 error format.
access_token: OAuth access token.
alt: Data format for response.
callback: JSONP
fields: Selector specifying which fields to include in a partial response.
key: API key. Your API key identifies your project and provides you with
API access, quota, and reports. Required unless you provide an OAuth 2.0
token.
oauth_token: OAuth 2.0 token for the current user.
prettyPrint: Returns response with indentations and line breaks.
quotaUser: Available to use for quota purposes for server-side
applications. Can be any arbitrary string assigned to a user, but should
not exceed 40 characters.
trace: A tracing token of the form "token:<tokenid>" to include in api
requests.
uploadType: Legacy upload protocol for media (e.g. "media", "multipart").
upload_protocol: Upload protocol for media (e.g. "raw", "multipart").
"""
class AltValueValuesEnum(_messages.Enum):
r"""Data format for response.
Values:
json: Responses with Content-Type of application/json
media: Media download with context-dependent Content-Type
proto: Responses with Content-Type of application/x-protobuf
"""
json = 0
media = 1
proto = 2
class FXgafvValueValuesEnum(_messages.Enum):
r"""V1 error format.
Values:
_1: v1 error format
_2: v2 error format
"""
_1 = 0
_2 = 1
f__xgafv = _messages.EnumField('FXgafvValueValuesEnum', 1)
access_token = _messages.StringField(2)
alt = _messages.EnumField('AltValueValuesEnum', 3, default='json')
callback = _messages.StringField(4)
fields = _messages.StringField(5)
key = _messages.StringField(6)
oauth_token = _messages.StringField(7)
prettyPrint = _messages.BooleanField(8, default=True)
quotaUser = _messages.StringField(9)
trace = _messages.StringField(10)
uploadType = _messages.StringField(11)
upload_protocol = _messages.StringField(12)
encoding.AddCustomJsonFieldMapping(
StandardQueryParameters, 'f__xgafv', '$.xgafv')
encoding.AddCustomJsonEnumMapping(
StandardQueryParameters.FXgafvValueValuesEnum, '_1', '1')
encoding.AddCustomJsonEnumMapping(
StandardQueryParameters.FXgafvValueValuesEnum, '_2', '2')
| |
result.go
|
/*
* Copyright 2021 Huawei Technologies Co., Ltd.
*
* 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.
|
package data
/*type EdgeResult struct {
EdgeResultMap map[string]map[string]bool //local ip -> checked map
}
var LocalResultMap EdgeResult
func NewEdgeResultData() EdgeResult { //for init later
LocalResultMap = EdgeResult{
EdgeResultMap: make(map[string]map[string]bool),
}
return LocalResultMap
}*/
|
*/
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.