sync scaleway packages

multiple scaleway-cli packages were out of sync, unfortunately this
pulled in some other updates.
This commit is contained in:
James Bardin 2017-02-24 11:37:38 -05:00
parent 7bb3e5d7bb
commit 359170d5d7
16 changed files with 2565 additions and 9 deletions

View File

@ -1,5 +1,5 @@
Docker
Copyright 2012-2016 Docker, Inc.
Copyright 2012-2017 Docker, Inc.
This product includes software developed at Docker, Inc. (https://www.docker.com).

View File

@ -0,0 +1,602 @@
package namesgenerator
import (
"fmt"
"github.com/docker/docker/pkg/random"
)
var (
left = [...]string{
"admiring",
"adoring",
"affectionate",
"agitated",
"amazing",
"angry",
"awesome",
"blissful",
"boring",
"brave",
"clever",
"cocky",
"compassionate",
"competent",
"condescending",
"confident",
"cranky",
"dazzling",
"determined",
"distracted",
"dreamy",
"eager",
"ecstatic",
"elastic",
"elated",
"elegant",
"eloquent",
"epic",
"fervent",
"festive",
"flamboyant",
"focused",
"friendly",
"frosty",
"gallant",
"gifted",
"goofy",
"gracious",
"happy",
"hardcore",
"heuristic",
"hopeful",
"hungry",
"infallible",
"inspiring",
"jolly",
"jovial",
"keen",
"kind",
"laughing",
"loving",
"lucid",
"mystifying",
"modest",
"musing",
"naughty",
"nervous",
"nifty",
"nostalgic",
"objective",
"optimistic",
"peaceful",
"pedantic",
"pensive",
"practical",
"priceless",
"quirky",
"quizzical",
"relaxed",
"reverent",
"romantic",
"sad",
"serene",
"sharp",
"silly",
"sleepy",
"stoic",
"stupefied",
"suspicious",
"tender",
"thirsty",
"trusting",
"unruffled",
"upbeat",
"vibrant",
"vigilant",
"vigorous",
"wizardly",
"wonderful",
"xenodochial",
"youthful",
"zealous",
"zen",
}
// Docker, starting from 0.7.x, generates names from notable scientists and hackers.
// Please, for any amazing man that you add to the list, consider adding an equally amazing woman to it, and vice versa.
right = [...]string{
// Muhammad ibn Jābir al-Ḥarrānī al-Battānī was a founding father of astronomy. https://en.wikipedia.org/wiki/Mu%E1%B8%A5ammad_ibn_J%C4%81bir_al-%E1%B8%A4arr%C4%81n%C4%AB_al-Batt%C4%81n%C4%AB
"albattani",
// Frances E. Allen, became the first female IBM Fellow in 1989. In 2006, she became the first female recipient of the ACM's Turing Award. https://en.wikipedia.org/wiki/Frances_E._Allen
"allen",
// June Almeida - Scottish virologist who took the first pictures of the rubella virus - https://en.wikipedia.org/wiki/June_Almeida
"almeida",
// Maria Gaetana Agnesi - Italian mathematician, philosopher, theologian and humanitarian. She was the first woman to write a mathematics handbook and the first woman appointed as a Mathematics Professor at a University. https://en.wikipedia.org/wiki/Maria_Gaetana_Agnesi
"agnesi",
// Archimedes was a physicist, engineer and mathematician who invented too many things to list them here. https://en.wikipedia.org/wiki/Archimedes
"archimedes",
// Maria Ardinghelli - Italian translator, mathematician and physicist - https://en.wikipedia.org/wiki/Maria_Ardinghelli
"ardinghelli",
// Aryabhata - Ancient Indian mathematician-astronomer during 476-550 CE https://en.wikipedia.org/wiki/Aryabhata
"aryabhata",
// Wanda Austin - Wanda Austin is the President and CEO of The Aerospace Corporation, a leading architect for the US security space programs. https://en.wikipedia.org/wiki/Wanda_Austin
"austin",
// Charles Babbage invented the concept of a programmable computer. https://en.wikipedia.org/wiki/Charles_Babbage.
"babbage",
// Stefan Banach - Polish mathematician, was one of the founders of modern functional analysis. https://en.wikipedia.org/wiki/Stefan_Banach
"banach",
// John Bardeen co-invented the transistor - https://en.wikipedia.org/wiki/John_Bardeen
"bardeen",
// Jean Bartik, born Betty Jean Jennings, was one of the original programmers for the ENIAC computer. https://en.wikipedia.org/wiki/Jean_Bartik
"bartik",
// Laura Bassi, the world's first female professor https://en.wikipedia.org/wiki/Laura_Bassi
"bassi",
// Hugh Beaver, British engineer, founder of the Guinness Book of World Records https://en.wikipedia.org/wiki/Hugh_Beaver
"beaver",
// Alexander Graham Bell - an eminent Scottish-born scientist, inventor, engineer and innovator who is credited with inventing the first practical telephone - https://en.wikipedia.org/wiki/Alexander_Graham_Bell
"bell",
// Karl Friedrich Benz - a German automobile engineer. Inventor of the first practical motorcar. https://en.wikipedia.org/wiki/Karl_Benz
"benz",
// Homi J Bhabha - was an Indian nuclear physicist, founding director, and professor of physics at the Tata Institute of Fundamental Research. Colloquially known as "father of Indian nuclear programme"- https://en.wikipedia.org/wiki/Homi_J._Bhabha
"bhabha",
// Bhaskara II - Ancient Indian mathematician-astronomer whose work on calculus predates Newton and Leibniz by over half a millennium - https://en.wikipedia.org/wiki/Bh%C4%81skara_II#Calculus
"bhaskara",
// Elizabeth Blackwell - American doctor and first American woman to receive a medical degree - https://en.wikipedia.org/wiki/Elizabeth_Blackwell
"blackwell",
// Niels Bohr is the father of quantum theory. https://en.wikipedia.org/wiki/Niels_Bohr.
"bohr",
// Kathleen Booth, she's credited with writing the first assembly language. https://en.wikipedia.org/wiki/Kathleen_Booth
"booth",
// Anita Borg - Anita Borg was the founding director of the Institute for Women and Technology (IWT). https://en.wikipedia.org/wiki/Anita_Borg
"borg",
// Satyendra Nath Bose - He provided the foundation for BoseEinstein statistics and the theory of the BoseEinstein condensate. - https://en.wikipedia.org/wiki/Satyendra_Nath_Bose
"bose",
// Evelyn Boyd Granville - She was one of the first African-American woman to receive a Ph.D. in mathematics; she earned it in 1949 from Yale University. https://en.wikipedia.org/wiki/Evelyn_Boyd_Granville
"boyd",
// Brahmagupta - Ancient Indian mathematician during 598-670 CE who gave rules to compute with zero - https://en.wikipedia.org/wiki/Brahmagupta#Zero
"brahmagupta",
// Walter Houser Brattain co-invented the transistor - https://en.wikipedia.org/wiki/Walter_Houser_Brattain
"brattain",
// Emmett Brown invented time travel. https://en.wikipedia.org/wiki/Emmett_Brown (thanks Brian Goff)
"brown",
// Rachel Carson - American marine biologist and conservationist, her book Silent Spring and other writings are credited with advancing the global environmental movement. https://en.wikipedia.org/wiki/Rachel_Carson
"carson",
// Subrahmanyan Chandrasekhar - Astrophysicist known for his mathematical theory on different stages and evolution in structures of the stars. He has won nobel prize for physics - https://en.wikipedia.org/wiki/Subrahmanyan_Chandrasekhar
"chandrasekhar",
//Claude Shannon - The father of information theory and founder of digital circuit design theory. (https://en.wikipedia.org/wiki/Claude_Shannon)
"shannon",
// Joan Clarke - Bletchley Park code breaker during the Second World War who pioneered techniques that remained top secret for decades. Also an accomplished numismatist https://en.wikipedia.org/wiki/Joan_Clarke
"clarke",
// Jane Colden - American botanist widely considered the first female American botanist - https://en.wikipedia.org/wiki/Jane_Colden
"colden",
// Gerty Theresa Cori - American biochemist who became the third woman—and first American woman—to win a Nobel Prize in science, and the first woman to be awarded the Nobel Prize in Physiology or Medicine. Cori was born in Prague. https://en.wikipedia.org/wiki/Gerty_Cori
"cori",
// Seymour Roger Cray was an American electrical engineer and supercomputer architect who designed a series of computers that were the fastest in the world for decades. https://en.wikipedia.org/wiki/Seymour_Cray
"cray",
// This entry reflects a husband and wife team who worked together:
// Joan Curran was a Welsh scientist who developed radar and invented chaff, a radar countermeasure. https://en.wikipedia.org/wiki/Joan_Curran
// Samuel Curran was an Irish physicist who worked alongside his wife during WWII and invented the proximity fuse. https://en.wikipedia.org/wiki/Samuel_Curran
"curran",
// Marie Curie discovered radioactivity. https://en.wikipedia.org/wiki/Marie_Curie.
"curie",
// Charles Darwin established the principles of natural evolution. https://en.wikipedia.org/wiki/Charles_Darwin.
"darwin",
// Leonardo Da Vinci invented too many things to list here. https://en.wikipedia.org/wiki/Leonardo_da_Vinci.
"davinci",
// Edsger Wybe Dijkstra was a Dutch computer scientist and mathematical scientist. https://en.wikipedia.org/wiki/Edsger_W._Dijkstra.
"dijkstra",
// Donna Dubinsky - played an integral role in the development of personal digital assistants (PDAs) serving as CEO of Palm, Inc. and co-founding Handspring. https://en.wikipedia.org/wiki/Donna_Dubinsky
"dubinsky",
// Annie Easley - She was a leading member of the team which developed software for the Centaur rocket stage and one of the first African-Americans in her field. https://en.wikipedia.org/wiki/Annie_Easley
"easley",
// Thomas Alva Edison, prolific inventor https://en.wikipedia.org/wiki/Thomas_Edison
"edison",
// Albert Einstein invented the general theory of relativity. https://en.wikipedia.org/wiki/Albert_Einstein
"einstein",
// Gertrude Elion - American biochemist, pharmacologist and the 1988 recipient of the Nobel Prize in Medicine - https://en.wikipedia.org/wiki/Gertrude_Elion
"elion",
// Douglas Engelbart gave the mother of all demos: https://en.wikipedia.org/wiki/Douglas_Engelbart
"engelbart",
// Euclid invented geometry. https://en.wikipedia.org/wiki/Euclid
"euclid",
// Leonhard Euler invented large parts of modern mathematics. https://de.wikipedia.org/wiki/Leonhard_Euler
"euler",
// Pierre de Fermat pioneered several aspects of modern mathematics. https://en.wikipedia.org/wiki/Pierre_de_Fermat
"fermat",
// Enrico Fermi invented the first nuclear reactor. https://en.wikipedia.org/wiki/Enrico_Fermi.
"fermi",
// Richard Feynman was a key contributor to quantum mechanics and particle physics. https://en.wikipedia.org/wiki/Richard_Feynman
"feynman",
// Benjamin Franklin is famous for his experiments in electricity and the invention of the lightning rod.
"franklin",
// Galileo was a founding father of modern astronomy, and faced politics and obscurantism to establish scientific truth. https://en.wikipedia.org/wiki/Galileo_Galilei
"galileo",
// William Henry "Bill" Gates III is an American business magnate, philanthropist, investor, computer programmer, and inventor. https://en.wikipedia.org/wiki/Bill_Gates
"gates",
// Adele Goldberg, was one of the designers and developers of the Smalltalk language. https://en.wikipedia.org/wiki/Adele_Goldberg_(computer_scientist)
"goldberg",
// Adele Goldstine, born Adele Katz, wrote the complete technical description for the first electronic digital computer, ENIAC. https://en.wikipedia.org/wiki/Adele_Goldstine
"goldstine",
// Shafi Goldwasser is a computer scientist known for creating theoretical foundations of modern cryptography. Winner of 2012 ACM Turing Award. https://en.wikipedia.org/wiki/Shafi_Goldwasser
"goldwasser",
// James Golick, all around gangster.
"golick",
// Jane Goodall - British primatologist, ethologist, and anthropologist who is considered to be the world's foremost expert on chimpanzees - https://en.wikipedia.org/wiki/Jane_Goodall
"goodall",
// Lois Haibt - American computer scientist, part of the team at IBM that developed FORTRAN - https://en.wikipedia.org/wiki/Lois_Haibt
"haibt",
// Margaret Hamilton - Director of the Software Engineering Division of the MIT Instrumentation Laboratory, which developed on-board flight software for the Apollo space program. https://en.wikipedia.org/wiki/Margaret_Hamilton_(scientist)
"hamilton",
// Stephen Hawking pioneered the field of cosmology by combining general relativity and quantum mechanics. https://en.wikipedia.org/wiki/Stephen_Hawking
"hawking",
// Werner Heisenberg was a founding father of quantum mechanics. https://en.wikipedia.org/wiki/Werner_Heisenberg
"heisenberg",
// Grete Hermann was a German philosopher noted for her philosophical work on the foundations of quantum mechanics. https://en.wikipedia.org/wiki/Grete_Hermann
"hermann",
// Jaroslav Heyrovský was the inventor of the polarographic method, father of the electroanalytical method, and recipient of the Nobel Prize in 1959. His main field of work was polarography. https://en.wikipedia.org/wiki/Jaroslav_Heyrovsk%C3%BD
"heyrovsky",
// Dorothy Hodgkin was a British biochemist, credited with the development of protein crystallography. She was awarded the Nobel Prize in Chemistry in 1964. https://en.wikipedia.org/wiki/Dorothy_Hodgkin
"hodgkin",
// Erna Schneider Hoover revolutionized modern communication by inventing a computerized telephone switching method. https://en.wikipedia.org/wiki/Erna_Schneider_Hoover
"hoover",
// Grace Hopper developed the first compiler for a computer programming language and is credited with popularizing the term "debugging" for fixing computer glitches. https://en.wikipedia.org/wiki/Grace_Hopper
"hopper",
// Frances Hugle, she was an American scientist, engineer, and inventor who contributed to the understanding of semiconductors, integrated circuitry, and the unique electrical principles of microscopic materials. https://en.wikipedia.org/wiki/Frances_Hugle
"hugle",
// Hypatia - Greek Alexandrine Neoplatonist philosopher in Egypt who was one of the earliest mothers of mathematics - https://en.wikipedia.org/wiki/Hypatia
"hypatia",
// Yeong-Sil Jang was a Korean scientist and astronomer during the Joseon Dynasty; he invented the first metal printing press and water gauge. https://en.wikipedia.org/wiki/Jang_Yeong-sil
"jang",
// Betty Jennings - one of the original programmers of the ENIAC. https://en.wikipedia.org/wiki/ENIAC - https://en.wikipedia.org/wiki/Jean_Bartik
"jennings",
// Mary Lou Jepsen, was the founder and chief technology officer of One Laptop Per Child (OLPC), and the founder of Pixel Qi. https://en.wikipedia.org/wiki/Mary_Lou_Jepsen
"jepsen",
// Katherine Coleman Goble Johnson - American physicist and mathematician contributed to the NASA. https://en.wikipedia.org/wiki/Katherine_Johnson
"johnson",
// Irène Joliot-Curie - French scientist who was awarded the Nobel Prize for Chemistry in 1935. Daughter of Marie and Pierre Curie. https://en.wikipedia.org/wiki/Ir%C3%A8ne_Joliot-Curie
"joliot",
// Karen Spärck Jones came up with the concept of inverse document frequency, which is used in most search engines today. https://en.wikipedia.org/wiki/Karen_Sp%C3%A4rck_Jones
"jones",
// A. P. J. Abdul Kalam - is an Indian scientist aka Missile Man of India for his work on the development of ballistic missile and launch vehicle technology - https://en.wikipedia.org/wiki/A._P._J._Abdul_Kalam
"kalam",
// Susan Kare, created the icons and many of the interface elements for the original Apple Macintosh in the 1980s, and was an original employee of NeXT, working as the Creative Director. https://en.wikipedia.org/wiki/Susan_Kare
"kare",
// Mary Kenneth Keller, Sister Mary Kenneth Keller became the first American woman to earn a PhD in Computer Science in 1965. https://en.wikipedia.org/wiki/Mary_Kenneth_Keller
"keller",
// Har Gobind Khorana - Indian-American biochemist who shared the 1968 Nobel Prize for Physiology - https://en.wikipedia.org/wiki/Har_Gobind_Khorana
"khorana",
// Jack Kilby invented silicone integrated circuits and gave Silicon Valley its name. - https://en.wikipedia.org/wiki/Jack_Kilby
"kilby",
// Maria Kirch - German astronomer and first woman to discover a comet - https://en.wikipedia.org/wiki/Maria_Margarethe_Kirch
"kirch",
// Donald Knuth - American computer scientist, author of "The Art of Computer Programming" and creator of the TeX typesetting system. https://en.wikipedia.org/wiki/Donald_Knuth
"knuth",
// Sophie Kowalevski - Russian mathematician responsible for important original contributions to analysis, differential equations and mechanics - https://en.wikipedia.org/wiki/Sofia_Kovalevskaya
"kowalevski",
// Marie-Jeanne de Lalande - French astronomer, mathematician and cataloguer of stars - https://en.wikipedia.org/wiki/Marie-Jeanne_de_Lalande
"lalande",
// Hedy Lamarr - Actress and inventor. The principles of her work are now incorporated into modern Wi-Fi, CDMA and Bluetooth technology. https://en.wikipedia.org/wiki/Hedy_Lamarr
"lamarr",
// Leslie B. Lamport - American computer scientist. Lamport is best known for his seminal work in distributed systems and was the winner of the 2013 Turing Award. https://en.wikipedia.org/wiki/Leslie_Lamport
"lamport",
// Mary Leakey - British paleoanthropologist who discovered the first fossilized Proconsul skull - https://en.wikipedia.org/wiki/Mary_Leakey
"leakey",
// Henrietta Swan Leavitt - she was an American astronomer who discovered the relation between the luminosity and the period of Cepheid variable stars. https://en.wikipedia.org/wiki/Henrietta_Swan_Leavitt
"leavitt",
//Daniel Lewin - Mathematician, Akamai co-founder, soldier, 9/11 victim-- Developed optimization techniques for routing traffic on the internet. Died attempting to stop the 9-11 hijackers. https://en.wikipedia.org/wiki/Daniel_Lewin
"lewin",
// Ruth Lichterman - one of the original programmers of the ENIAC. https://en.wikipedia.org/wiki/ENIAC - https://en.wikipedia.org/wiki/Ruth_Teitelbaum
"lichterman",
// Barbara Liskov - co-developed the Liskov substitution principle. Liskov was also the winner of the Turing Prize in 2008. - https://en.wikipedia.org/wiki/Barbara_Liskov
"liskov",
// Ada Lovelace invented the first algorithm. https://en.wikipedia.org/wiki/Ada_Lovelace (thanks James Turnbull)
"lovelace",
// Auguste and Louis Lumière - the first filmmakers in history - https://en.wikipedia.org/wiki/Auguste_and_Louis_Lumi%C3%A8re
"lumiere",
// Mahavira - Ancient Indian mathematician during 9th century AD who discovered basic algebraic identities - https://en.wikipedia.org/wiki/Mah%C4%81v%C4%ABra_(mathematician)
"mahavira",
// Maria Mayer - American theoretical physicist and Nobel laureate in Physics for proposing the nuclear shell model of the atomic nucleus - https://en.wikipedia.org/wiki/Maria_Mayer
"mayer",
// John McCarthy invented LISP: https://en.wikipedia.org/wiki/John_McCarthy_(computer_scientist)
"mccarthy",
// Barbara McClintock - a distinguished American cytogeneticist, 1983 Nobel Laureate in Physiology or Medicine for discovering transposons. https://en.wikipedia.org/wiki/Barbara_McClintock
"mcclintock",
// Malcolm McLean invented the modern shipping container: https://en.wikipedia.org/wiki/Malcom_McLean
"mclean",
// Kay McNulty - one of the original programmers of the ENIAC. https://en.wikipedia.org/wiki/ENIAC - https://en.wikipedia.org/wiki/Kathleen_Antonelli
"mcnulty",
// Lise Meitner - Austrian/Swedish physicist who was involved in the discovery of nuclear fission. The element meitnerium is named after her - https://en.wikipedia.org/wiki/Lise_Meitner
"meitner",
// Carla Meninsky, was the game designer and programmer for Atari 2600 games Dodge 'Em and Warlords. https://en.wikipedia.org/wiki/Carla_Meninsky
"meninsky",
// Johanna Mestorf - German prehistoric archaeologist and first female museum director in Germany - https://en.wikipedia.org/wiki/Johanna_Mestorf
"mestorf",
// Marvin Minsky - Pioneer in Artificial Intelligence, co-founder of the MIT's AI Lab, won the Turing Award in 1969. https://en.wikipedia.org/wiki/Marvin_Minsky
"minsky",
// Maryam Mirzakhani - an Iranian mathematician and the first woman to win the Fields Medal. https://en.wikipedia.org/wiki/Maryam_Mirzakhani
"mirzakhani",
// Samuel Morse - contributed to the invention of a single-wire telegraph system based on European telegraphs and was a co-developer of the Morse code - https://en.wikipedia.org/wiki/Samuel_Morse
"morse",
// Ian Murdock - founder of the Debian project - https://en.wikipedia.org/wiki/Ian_Murdock
"murdock",
// John von Neumann - todays computer architectures are based on the von Neumann architecture. https://en.wikipedia.org/wiki/Von_Neumann_architecture
"neumann",
// Isaac Newton invented classic mechanics and modern optics. https://en.wikipedia.org/wiki/Isaac_Newton
"newton",
// Florence Nightingale, more prominently known as a nurse, was also the first female member of the Royal Statistical Society and a pioneer in statistical graphics https://en.wikipedia.org/wiki/Florence_Nightingale#Statistics_and_sanitary_reform
"nightingale",
// Alfred Nobel - a Swedish chemist, engineer, innovator, and armaments manufacturer (inventor of dynamite) - https://en.wikipedia.org/wiki/Alfred_Nobel
"nobel",
// Emmy Noether, German mathematician. Noether's Theorem is named after her. https://en.wikipedia.org/wiki/Emmy_Noether
"noether",
// Poppy Northcutt. Poppy Northcutt was the first woman to work as part of NASAs Mission Control. http://www.businessinsider.com/poppy-northcutt-helped-apollo-astronauts-2014-12?op=1
"northcutt",
// Robert Noyce invented silicone integrated circuits and gave Silicon Valley its name. - https://en.wikipedia.org/wiki/Robert_Noyce
"noyce",
// Panini - Ancient Indian linguist and grammarian from 4th century CE who worked on the world's first formal system - https://en.wikipedia.org/wiki/P%C4%81%E1%B9%87ini#Comparison_with_modern_formal_systems
"panini",
// Ambroise Pare invented modern surgery. https://en.wikipedia.org/wiki/Ambroise_Par%C3%A9
"pare",
// Louis Pasteur discovered vaccination, fermentation and pasteurization. https://en.wikipedia.org/wiki/Louis_Pasteur.
"pasteur",
// Cecilia Payne-Gaposchkin was an astronomer and astrophysicist who, in 1925, proposed in her Ph.D. thesis an explanation for the composition of stars in terms of the relative abundances of hydrogen and helium. https://en.wikipedia.org/wiki/Cecilia_Payne-Gaposchkin
"payne",
// Radia Perlman is a software designer and network engineer and most famous for her invention of the spanning-tree protocol (STP). https://en.wikipedia.org/wiki/Radia_Perlman
"perlman",
// Rob Pike was a key contributor to Unix, Plan 9, the X graphic system, utf-8, and the Go programming language. https://en.wikipedia.org/wiki/Rob_Pike
"pike",
// Henri Poincaré made fundamental contributions in several fields of mathematics. https://en.wikipedia.org/wiki/Henri_Poincar%C3%A9
"poincare",
// Laura Poitras is a director and producer whose work, made possible by open source crypto tools, advances the causes of truth and freedom of information by reporting disclosures by whistleblowers such as Edward Snowden. https://en.wikipedia.org/wiki/Laura_Poitras
"poitras",
// Claudius Ptolemy - a Greco-Egyptian writer of Alexandria, known as a mathematician, astronomer, geographer, astrologer, and poet of a single epigram in the Greek Anthology - https://en.wikipedia.org/wiki/Ptolemy
"ptolemy",
// C. V. Raman - Indian physicist who won the Nobel Prize in 1930 for proposing the Raman effect. - https://en.wikipedia.org/wiki/C._V._Raman
"raman",
// Srinivasa Ramanujan - Indian mathematician and autodidact who made extraordinary contributions to mathematical analysis, number theory, infinite series, and continued fractions. - https://en.wikipedia.org/wiki/Srinivasa_Ramanujan
"ramanujan",
// Sally Kristen Ride was an American physicist and astronaut. She was the first American woman in space, and the youngest American astronaut. https://en.wikipedia.org/wiki/Sally_Ride
"ride",
// Rita Levi-Montalcini - Won Nobel Prize in Physiology or Medicine jointly with colleague Stanley Cohen for the discovery of nerve growth factor (https://en.wikipedia.org/wiki/Rita_Levi-Montalcini)
"montalcini",
// Dennis Ritchie - co-creator of UNIX and the C programming language. - https://en.wikipedia.org/wiki/Dennis_Ritchie
"ritchie",
// Wilhelm Conrad Röntgen - German physicist who was awarded the first Nobel Prize in Physics in 1901 for the discovery of X-rays (Röntgen rays). https://en.wikipedia.org/wiki/Wilhelm_R%C3%B6ntgen
"roentgen",
// Rosalind Franklin - British biophysicist and X-ray crystallographer whose research was critical to the understanding of DNA - https://en.wikipedia.org/wiki/Rosalind_Franklin
"rosalind",
// Meghnad Saha - Indian astrophysicist best known for his development of the Saha equation, used to describe chemical and physical conditions in stars - https://en.wikipedia.org/wiki/Meghnad_Saha
"saha",
// Jean E. Sammet developed FORMAC, the first widely used computer language for symbolic manipulation of mathematical formulas. https://en.wikipedia.org/wiki/Jean_E._Sammet
"sammet",
// Carol Shaw - Originally an Atari employee, Carol Shaw is said to be the first female video game designer. https://en.wikipedia.org/wiki/Carol_Shaw_(video_game_designer)
"shaw",
// Dame Stephanie "Steve" Shirley - Founded a software company in 1962 employing women working from home. https://en.wikipedia.org/wiki/Steve_Shirley
"shirley",
// William Shockley co-invented the transistor - https://en.wikipedia.org/wiki/William_Shockley
"shockley",
// Françoise Barré-Sinoussi - French virologist and Nobel Prize Laureate in Physiology or Medicine; her work was fundamental in identifying HIV as the cause of AIDS. https://en.wikipedia.org/wiki/Fran%C3%A7oise_Barr%C3%A9-Sinoussi
"sinoussi",
// Betty Snyder - one of the original programmers of the ENIAC. https://en.wikipedia.org/wiki/ENIAC - https://en.wikipedia.org/wiki/Betty_Holberton
"snyder",
// Frances Spence - one of the original programmers of the ENIAC. https://en.wikipedia.org/wiki/ENIAC - https://en.wikipedia.org/wiki/Frances_Spence
"spence",
// Richard Matthew Stallman - the founder of the Free Software movement, the GNU project, the Free Software Foundation, and the League for Programming Freedom. He also invented the concept of copyleft to protect the ideals of this movement, and enshrined this concept in the widely-used GPL (General Public License) for software. https://en.wikiquote.org/wiki/Richard_Stallman
"stallman",
// Michael Stonebraker is a database research pioneer and architect of Ingres, Postgres, VoltDB and SciDB. Winner of 2014 ACM Turing Award. https://en.wikipedia.org/wiki/Michael_Stonebraker
"stonebraker",
// Janese Swanson (with others) developed the first of the Carmen Sandiego games. She went on to found Girl Tech. https://en.wikipedia.org/wiki/Janese_Swanson
"swanson",
// Aaron Swartz was influential in creating RSS, Markdown, Creative Commons, Reddit, and much of the internet as we know it today. He was devoted to freedom of information on the web. https://en.wikiquote.org/wiki/Aaron_Swartz
"swartz",
// Bertha Swirles was a theoretical physicist who made a number of contributions to early quantum theory. https://en.wikipedia.org/wiki/Bertha_Swirles
"swirles",
// Nikola Tesla invented the AC electric system and every gadget ever used by a James Bond villain. https://en.wikipedia.org/wiki/Nikola_Tesla
"tesla",
// Ken Thompson - co-creator of UNIX and the C programming language - https://en.wikipedia.org/wiki/Ken_Thompson
"thompson",
// Linus Torvalds invented Linux and Git. https://en.wikipedia.org/wiki/Linus_Torvalds
"torvalds",
// Alan Turing was a founding father of computer science. https://en.wikipedia.org/wiki/Alan_Turing.
"turing",
// Varahamihira - Ancient Indian mathematician who discovered trigonometric formulae during 505-587 CE - https://en.wikipedia.org/wiki/Var%C4%81hamihira#Contributions
"varahamihira",
// Sir Mokshagundam Visvesvaraya - is a notable Indian engineer. He is a recipient of the Indian Republic's highest honour, the Bharat Ratna, in 1955. On his birthday, 15 September is celebrated as Engineer's Day in India in his memory - https://en.wikipedia.org/wiki/Visvesvaraya
"visvesvaraya",
// Christiane Nüsslein-Volhard - German biologist, won Nobel Prize in Physiology or Medicine in 1995 for research on the genetic control of embryonic development. https://en.wikipedia.org/wiki/Christiane_N%C3%BCsslein-Volhard
"volhard",
// Marlyn Wescoff - one of the original programmers of the ENIAC. https://en.wikipedia.org/wiki/ENIAC - https://en.wikipedia.org/wiki/Marlyn_Meltzer
"wescoff",
// Andrew Wiles - Notable British mathematician who proved the enigmatic Fermat's Last Theorem - https://en.wikipedia.org/wiki/Andrew_Wiles
"wiles",
// Roberta Williams, did pioneering work in graphical adventure games for personal computers, particularly the King's Quest series. https://en.wikipedia.org/wiki/Roberta_Williams
"williams",
// Sophie Wilson designed the first Acorn Micro-Computer and the instruction set for ARM processors. https://en.wikipedia.org/wiki/Sophie_Wilson
"wilson",
// Jeannette Wing - co-developed the Liskov substitution principle. - https://en.wikipedia.org/wiki/Jeannette_Wing
"wing",
// Steve Wozniak invented the Apple I and Apple II. https://en.wikipedia.org/wiki/Steve_Wozniak
"wozniak",
// The Wright brothers, Orville and Wilbur - credited with inventing and building the world's first successful airplane and making the first controlled, powered and sustained heavier-than-air human flight - https://en.wikipedia.org/wiki/Wright_brothers
"wright",
// Rosalyn Sussman Yalow - Rosalyn Sussman Yalow was an American medical physicist, and a co-winner of the 1977 Nobel Prize in Physiology or Medicine for development of the radioimmunoassay technique. https://en.wikipedia.org/wiki/Rosalyn_Sussman_Yalow
"yalow",
// Ada Yonath - an Israeli crystallographer, the first woman from the Middle East to win a Nobel prize in the sciences. https://en.wikipedia.org/wiki/Ada_Yonath
"yonath",
}
)
// GetRandomName generates a random name from the list of adjectives and surnames in this package
// formatted as "adjective_surname". For example 'focused_turing'. If retry is non-zero, a random
// integer between 0 and 10 will be added to the end of the name, e.g `focused_turing3`
func GetRandomName(retry int) string {
rnd := random.Rand
begin:
name := fmt.Sprintf("%s_%s", left[rnd.Intn(len(left))], right[rnd.Intn(len(right))])
if name == "boring_wozniak" /* Steve Wozniak is not boring */ {
goto begin
}
if retry > 0 {
name = fmt.Sprintf("%s%d", name, rnd.Intn(10))
}
return name
}

71
vendor/github.com/docker/docker/pkg/random/random.go generated vendored Normal file
View File

@ -0,0 +1,71 @@
package random
import (
cryptorand "crypto/rand"
"io"
"math"
"math/big"
"math/rand"
"sync"
"time"
)
// Rand is a global *rand.Rand instance, which initialized with NewSource() source.
var Rand = rand.New(NewSource())
// Reader is a global, shared instance of a pseudorandom bytes generator.
// It doesn't consume entropy.
var Reader io.Reader = &reader{rnd: Rand}
// copypaste from standard math/rand
type lockedSource struct {
lk sync.Mutex
src rand.Source
}
func (r *lockedSource) Int63() (n int64) {
r.lk.Lock()
n = r.src.Int63()
r.lk.Unlock()
return
}
func (r *lockedSource) Seed(seed int64) {
r.lk.Lock()
r.src.Seed(seed)
r.lk.Unlock()
}
// NewSource returns math/rand.Source safe for concurrent use and initialized
// with current unix-nano timestamp
func NewSource() rand.Source {
var seed int64
if cryptoseed, err := cryptorand.Int(cryptorand.Reader, big.NewInt(math.MaxInt64)); err != nil {
// This should not happen, but worst-case fallback to time-based seed.
seed = time.Now().UnixNano()
} else {
seed = cryptoseed.Int64()
}
return &lockedSource{
src: rand.NewSource(seed),
}
}
type reader struct {
rnd *rand.Rand
}
func (r *reader) Read(b []byte) (int, error) {
i := 0
for {
val := r.rnd.Int63()
for val > 0 {
b[i] = byte(val)
i++
if i == len(b) {
return i, nil
}
val >>= 8
}
}
}

22
vendor/github.com/moul/gotty-client/LICENSE generated vendored Normal file
View File

@ -0,0 +1,22 @@
The MIT License (MIT)
Copyright (c) 2015 Manfred Touron
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

81
vendor/github.com/moul/gotty-client/Makefile generated vendored Normal file
View File

@ -0,0 +1,81 @@
# Project-specific variables
BINARIES ?= gotty-client
GOTTY_URL := http://localhost:8081/
VERSION := $(shell cat .goxc.json | jq -c .PackageVersion | sed 's/"//g')
CONVEY_PORT ?= 9042
# Common variables
SOURCES := $(shell find . -type f -name "*.go")
COMMANDS := $(shell go list ./... | grep -v /vendor/ | grep /cmd/)
PACKAGES := $(shell go list ./... | grep -v /vendor/ | grep -v /cmd/)
GOENV ?= GO15VENDOREXPERIMENT=1
GO ?= $(GOENV) go
GODEP ?= $(GOENV) godep
USER ?= $(shell whoami)
all: build
.PHONY: build
build: $(BINARIES)
.PHONY: install
install:
$(GO) install ./cmd/gotty-client
$(BINARIES): $(SOURCES)
$(GO) build -o $@ ./cmd/$@
.PHONY: test
test:
$(GO) get -t .
$(GO) test -v .
.PHONY: godep-save
godep-save:
$(GODEP) save $(PACKAGES) $(COMMANDS)
.PHONY: clean
clean:
rm -f $(BINARIES)
.PHONY: re
re: clean all
.PHONY: convey
convey:
$(GO) get github.com/smartystreets/goconvey
goconvey -cover -port=$(CONVEY_PORT) -workDir="$(realpath .)" -depth=1
.PHONY: cover
cover: profile.out
profile.out: $(SOURCES)
rm -f $@
$(GO) test -covermode=count -coverpkg=. -coverprofile=$@ .
.PHONY: docker-build
docker-build:
go get github.com/laher/goxc
rm -rf contrib/docker/linux_386
for binary in $(BINARIES); do \
goxc -bc="linux,386" -d . -pv contrib/docker -n $$binary xc; \
mv contrib/docker/linux_386/$$binary contrib/docker/entrypoint; \
docker build -t $(USER)/$$binary contrib/docker; \
docker run -it --rm $(USER)/$$binary || true; \
docker inspect --type=image --format="{{ .Id }}" moul/$$binary || true; \
echo "Now you can run 'docker push $(USER)/$$binary'"; \
done

201
vendor/github.com/moul/gotty-client/README.md generated vendored Normal file
View File

@ -0,0 +1,201 @@
# gotty-client
:wrench: Terminal client for [GoTTY](https://github.com/yudai/gotty).
![](https://raw.githubusercontent.com/moul/gotty-client/master/resources/gotty-client.png)
[![Build Status](https://travis-ci.org/moul/gotty-client.svg?branch=master)](https://travis-ci.org/moul/gotty-client)
[![GoDoc](https://godoc.org/github.com/moul/gotty-client?status.svg)](https://godoc.org/github.com/moul/gotty-client)
```ruby
┌─────────────────┐
┌──────▶│ /bin/bash │
│ └─────────────────┘
┌──────────────┐ ┌──────────┐
│ │ │ Gotty │
┌───────┐ ┌──▶│ Browser │───────┐ │ │
│ │ │ │ │ │ │ │
│ │ │ └──────────────┘ │ │ │ ┌─────────────────┐
│ Bob │───┤ websockets─▶│ │─▶│ emacs /var/www │
│ │ │ ╔═ ══ ══ ══ ══ ╗ │ │ │ └─────────────────┘
│ │ │ ║ ║ │ │ │
└───────┘ └──▶║ gotty-client ───────┘ │ │
║ │ │
╚═ ══ ══ ══ ══ ╝ └──────────┘
│ ┌─────────────────┐
└──────▶│ tmux attach │
└─────────────────┘
```
## Example
Server side ([GoTTY](https://github.com/yudai/gotty))
```console
$ gotty -p 9191 sh -c 'while true; do date; sleep 1; done'
2015/08/24 18:54:31 Server is starting with command: sh -c while true; do date; sleep 1; done
2015/08/24 18:54:31 URL: http://[::1]:9191/
2015/08/24 18:54:34 GET /ws
2015/08/24 18:54:34 New client connected: 127.0.0.1:61811
2015/08/24 18:54:34 Command is running for client 127.0.0.1:61811 with PID 64834
2015/08/24 18:54:39 Command exited for: 127.0.0.1:61811
2015/08/24 18:54:39 Connection closed: 127.0.0.1:61811
...
```
**Client side**
```console
$ gotty-client http://localhost:9191/
INFO[0000] New title: GoTTY - sh -c while true; do date; sleep 1; done (jean-michel-van-damme.local)
WARN[0000] Unhandled protocol message: json pref: 2{}
Mon Aug 24 18:54:34 CEST 2015
Mon Aug 24 18:54:35 CEST 2015
Mon Aug 24 18:54:36 CEST 2015
Mon Aug 24 18:54:37 CEST 2015
Mon Aug 24 18:54:38 CEST 2015
^C
```
## Usage
```console
$ gotty-client -h
NAME:
gotty-client - GoTTY client for your terminal
USAGE:
gotty-client [global options] command [command options] GOTTY_URL
VERSION:
1.3.0+
AUTHOR(S):
Manfred Touron <https://github.com/moul/gotty-client>
COMMANDS:
help, h Shows a list of commands or help for one command
GLOBAL OPTIONS:
--debug, -D Enable debug mode [$GOTTY_CLIENT_DEBUG]
--help, -h show help
--version, -v print the version
```
## Install
Install latest version using Golang (recommended)
```console
$ go get github.com/moul/gotty-client/cmd/gotty-client
```
---
Install latest version using Homebrew (Mac OS X)
```console
$ brew install https://raw.githubusercontent.com/moul/gotty-client/master/contrib/homebrew/gotty-client.rb --HEAD
```
or the latest released version
```console
$ brew install https://raw.githubusercontent.com/moul/gotty-client/master/contrib/homebrew/gotty-client.rb
```
## Changelog
### master (unreleased)
* No entry
[full commits list](https://github.com/moul/gotty-client/compare/v1.6.1...master)
### [v1.6.1](https://github.com/moul/gotty-client/releases/tag/v1.6.1) (2017-01-19)
* Do not exit on EOF ([#45](https://github.com/moul/gotty-client/pull/45)) ([@gurjeet](https://github.com/gurjeet))
[full commits list](https://github.com/moul/gotty-client/compare/v1.6.0...v1.6.1)
### [v1.6.0](https://github.com/moul/gotty-client/releases/tag/v1.6.0) (2016-05-23)
* Support of `--use-proxy-from-env` (Add Proxy support) ([#36](https://github.com/moul/gotty-client/pull/36)) ([@byung2](https://github.com/byung2))
* Add debug mode ([#18](https://github.com/moul/gotty-client/issues/18))
* Fix argument passing ([#16](https://github.com/moul/gotty-client/issues/16))
* Remove warnings + golang fixes and refactoring ([@QuentinPerez](https://github.com/QuentinPerez))
[full commits list](https://github.com/moul/gotty-client/compare/v1.5.0...v1.6.0)
### [v1.5.0](https://github.com/moul/gotty-client/releases/tag/v1.5.0) (2016-02-18)
* Add autocomplete support ([#19](https://github.com/moul/gotty-client/issues/19))
* Switch from `Party` to `Godep`
* Fix terminal data being interpreted as format string ([#34](https://github.com/moul/gotty-client/pull/34)) ([@mickael9](https://github.com/mickael9))
[full commits list](https://github.com/moul/gotty-client/compare/v1.4.0...v1.5.0)
### [v1.4.0](https://github.com/moul/gotty-client/releases/tag/v1.4.0) (2015-12-09)
* Remove solaris,plan9,nacl for `.goxc.json`
* Add an error if the go version is lower than 1.5
* Flexible parsing of the input URL
* Add tests
* Support of `--skip-tls-verify`
[full commits list](https://github.com/moul/gotty-client/compare/v1.3.0...v1.4.0)
### [v1.3.0](https://github.com/moul/gotty-client/releases/tag/v1.3.0) (2015-10-27)
* Fix `connected` state when using `Connect()` + `Loop()` methods
* Add `ExitLoop` which allow to exit from `Loop` function
[full commits list](https://github.com/moul/gotty-client/compare/v1.2.0...v1.3.0)
### [v1.2.0](https://github.com/moul/gotty-client/releases/tag/v1.2.0) (2015-10-23)
* Removed an annoying warning when exiting connection ([#22](https://github.com/moul/gotty-client/issues/22)) ([@QuentinPerez](https://github.com/QuentinPerez))
* Add the ability to configure alternative stdout ([#21](https://github.com/moul/gotty-client/issues/21)) ([@QuentinPerez](https://github.com/QuentinPerez))
* Refactored the goroutine system with select, improve speed and stability ([@QuentinPerez](https://github.com/QuentinPerez))
* Add debug mode (`--debug`/`-D`) ([#18](https://github.com/moul/gotty-client/issues/18))
* Improve error message when connecting by checking HTTP status code
* Fix arguments passing ([#16](https://github.com/moul/gotty-client/issues/16))
* Dropped support for golang<1.5
* Small fixes
[full commits list](https://github.com/moul/gotty-client/compare/v1.1.0...v1.2.0)
### [v1.1.0](https://github.com/moul/gotty-client/releases/tag/v1.1.0) (2015-10-10)
* Handling arguments + using mutexes (thanks to [@QuentinPerez](https://github.com/QuentinPerez))
* Add logo ([#9](https://github.com/moul/gotty-client/issues/9))
* Using codegansta/cli for CLI parsing ([#3](https://github.com/moul/gotty-client/issues/3))
* Fix panic when running on older GoTTY server ([#13](https://github.com/moul/gotty-client/issues/13))
* Add 'homebrew support' ([#1](https://github.com/moul/gotty-client/issues/1))
* Add Changelog ([#5](https://github.com/moul/gotty-client/issues/5))
* Add GOXC configuration to build binaries for multiple architectures ([#2](https://github.com/moul/gotty-client/issues/2))
[full commits list](https://github.com/moul/gotty-client/compare/v1.0.1...v1.1.0)
### [v1.0.1](https://github.com/moul/gotty-client/releases/tag/v1.0.1) (2015-09-27)
* Using party to manage dependencies
[full commits list](https://github.com/moul/gotty-client/compare/v1.0.0...v1.0.1)
### [v1.0.0](https://github.com/moul/gotty-client/releases/tag/v1.0.0) (2015-09-27)
Compatible with [GoTTY](https://github.com/yudai/gotty) version: [v0.0.10](https://github.com/yudai/gotty/releases/tag/v0.0.10)
#### Features
* Support **basic-auth**
* Support **terminal-(re)size**
* Support **write**
* Support **title**
* Support **custom URI**
[full commits list](https://github.com/moul/gotty-client/compare/cf0c1146c7ce20fe0bd65764c13253bc575cd43a...v1.0.0)
## License
MIT

34
vendor/github.com/moul/gotty-client/arch.go generated vendored Normal file
View File

@ -0,0 +1,34 @@
// +build !windows
package gottyclient
import (
"encoding/json"
"fmt"
"os"
"os/signal"
"syscall"
"unsafe"
)
func notifySignalSIGWINCH(c chan<- os.Signal) {
signal.Notify(c, syscall.SIGWINCH)
}
func resetSignalSIGWINCH() {
signal.Reset(syscall.SIGWINCH)
}
func syscallTIOCGWINSZ() ([]byte, error) {
ws := winsize{}
syscall.Syscall(syscall.SYS_IOCTL,
uintptr(0), uintptr(syscall.TIOCGWINSZ),
uintptr(unsafe.Pointer(&ws)))
b, err := json.Marshal(ws)
if err != nil {
return nil, fmt.Errorf("json.Marshal error: %v", err)
}
return b, err
}

16
vendor/github.com/moul/gotty-client/arch_windows.go generated vendored Normal file
View File

@ -0,0 +1,16 @@
package gottyclient
import (
"errors"
"os"
)
func notifySignalSIGWINCH(c chan<- os.Signal) {
}
func resetSignalSIGWINCH() {
}
func syscallTIOCGWINSZ() ([]byte, error) {
return nil, errors.New("SIGWINCH isn't supported on this ARCH")
}

37
vendor/github.com/moul/gotty-client/glide.lock generated vendored Normal file
View File

@ -0,0 +1,37 @@
hash: 5ba4ef945563e8e85097f2699126b1577f9c667fdbbcdd71604e553ab7dd2a03
updated: 2017-02-04T23:03:32.03375088+01:00
imports:
- name: github.com/codegangsta/cli
version: 2ae9042f5bcbaf15b01229f8395ba8e72e01bded
- name: github.com/creack/goselect
version: 40085cf5fd629ccd88dc328895f1f137d09a1de4
- name: github.com/gopherjs/gopherjs
version: db27c7c470d7404b6b201f82d6fd4821260bd13e
subpackages:
- js
- name: github.com/gorilla/websocket
version: 1f512fc3f05332ba7117626cdfb4e07474e58e60
- name: github.com/jtolds/gls
version: 8ddce2a84170772b95dd5d576c48d517b22cac63
- name: github.com/Sirupsen/logrus
version: cd7d1bbe41066b6c1f19780f895901052150a575
- name: github.com/smartystreets/assertions
version: 40711f7748186bbf9c99977cd89f21ce1a229447
subpackages:
- internal/go-render/render
- internal/oglematchers
- name: github.com/smartystreets/goconvey
version: d4c757aa9afd1e2fc1832aaab209b5794eb336e1
subpackages:
- convey
- convey/gotest
- convey/reporting
- name: golang.org/x/crypto
version: 5bcd134fee4dd1475da17714aac19c0aa0142e2f
subpackages:
- ssh/terminal
- name: golang.org/x/sys
version: d4feaf1a7e61e1d9e79e6c4e76c6349e9cab0a03
subpackages:
- unix
testImports: []

35
vendor/github.com/moul/gotty-client/glide.yaml generated vendored Normal file
View File

@ -0,0 +1,35 @@
package: github.com/moul/gotty-client
import:
- package: github.com/Sirupsen/logrus
version: cd7d1bbe41066b6c1f19780f895901052150a575
- package: github.com/codegangsta/cli
version: 2ae9042f5bcbaf15b01229f8395ba8e72e01bded
- package: github.com/creack/goselect
version: 40085cf5fd629ccd88dc328895f1f137d09a1de4
- package: github.com/gopherjs/gopherjs
version: db27c7c470d7404b6b201f82d6fd4821260bd13e
subpackages:
- js
- package: github.com/gorilla/websocket
version: 1f512fc3f05332ba7117626cdfb4e07474e58e60
- package: github.com/jtolds/gls
version: 8ddce2a84170772b95dd5d576c48d517b22cac63
- package: github.com/smartystreets/assertions
version: 40711f7748186bbf9c99977cd89f21ce1a229447
subpackages:
- internal/go-render/render
- internal/oglematchers
- package: github.com/smartystreets/goconvey
version: d4c757aa9afd1e2fc1832aaab209b5794eb336e1
subpackages:
- convey
- convey/gotest
- convey/reporting
- package: golang.org/x/crypto
version: 5bcd134fee4dd1475da17714aac19c0aa0142e2f
subpackages:
- ssh/terminal
- package: golang.org/x/sys
version: d4feaf1a7e61e1d9e79e6c4e76c6349e9cab0a03
subpackages:
- unix

469
vendor/github.com/moul/gotty-client/gotty-client.go generated vendored Normal file
View File

@ -0,0 +1,469 @@
package gottyclient
import (
"crypto/tls"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"os"
"regexp"
"strings"
"sync"
"time"
"github.com/Sirupsen/logrus"
"github.com/creack/goselect"
"github.com/gorilla/websocket"
"golang.org/x/crypto/ssh/terminal"
)
// GetAuthTokenURL transforms a GoTTY http URL to its AuthToken file URL
func GetAuthTokenURL(httpURL string) (*url.URL, *http.Header, error) {
header := http.Header{}
target, err := url.Parse(httpURL)
if err != nil {
return nil, nil, err
}
target.Path = strings.TrimLeft(target.Path+"auth_token.js", "/")
if target.User != nil {
header.Add("Authorization", "Basic "+base64.StdEncoding.EncodeToString([]byte(target.User.String())))
target.User = nil
}
return target, &header, nil
}
// GetURLQuery returns url.query
func GetURLQuery(rawurl string) (url.Values, error) {
target, err := url.Parse(rawurl)
if err != nil {
return nil, err
}
return target.Query(), nil
}
// GetWebsocketURL transforms a GoTTY http URL to its WebSocket URL
func GetWebsocketURL(httpURL string) (*url.URL, *http.Header, error) {
header := http.Header{}
target, err := url.Parse(httpURL)
if err != nil {
return nil, nil, err
}
if target.Scheme == "https" {
target.Scheme = "wss"
} else {
target.Scheme = "ws"
}
target.Path = strings.TrimLeft(target.Path+"ws", "/")
if target.User != nil {
header.Add("Authorization", "Basic "+base64.StdEncoding.EncodeToString([]byte(target.User.String())))
target.User = nil
}
return target, &header, nil
}
type Client struct {
Dialer *websocket.Dialer
Conn *websocket.Conn
URL string
WriteMutex *sync.Mutex
Output io.Writer
poison chan bool
SkipTLSVerify bool
UseProxyFromEnv bool
Connected bool
}
type querySingleType struct {
AuthToken string `json:"AuthToken"`
Arguments string `json:"Arguments"`
}
func (c *Client) write(data []byte) error {
c.WriteMutex.Lock()
defer c.WriteMutex.Unlock()
return c.Conn.WriteMessage(websocket.TextMessage, data)
}
// GetAuthToken retrieves an Auth Token from dynamic auth_token.js file
func (c *Client) GetAuthToken() (string, error) {
target, header, err := GetAuthTokenURL(c.URL)
if err != nil {
return "", err
}
logrus.Debugf("Fetching auth token auth-token: %q", target.String())
req, err := http.NewRequest("GET", target.String(), nil)
req.Header = *header
tr := &http.Transport{}
if c.SkipTLSVerify {
conf := &tls.Config{InsecureSkipVerify: true}
tr.TLSClientConfig = conf
}
if c.UseProxyFromEnv {
tr.Proxy = http.ProxyFromEnvironment
}
client := &http.Client{Transport: tr}
resp, err := client.Do(req)
if err != nil {
return "", err
}
switch resp.StatusCode {
case 200:
// Everything is OK
default:
return "", fmt.Errorf("unknown status code: %d (%s)", resp.StatusCode, http.StatusText(resp.StatusCode))
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", err
}
re := regexp.MustCompile("var gotty_auth_token = '(.*)'")
output := re.FindStringSubmatch(string(body))
if len(output) == 0 {
return "", fmt.Errorf("Cannot fetch GoTTY auth-token, please upgrade your GoTTY server.")
}
return output[1], nil
}
// Connect tries to dial a websocket server
func (c *Client) Connect() error {
// Retrieve AuthToken
authToken, err := c.GetAuthToken()
if err != nil {
return err
}
logrus.Debugf("Auth-token: %q", authToken)
// Open WebSocket connection
target, header, err := GetWebsocketURL(c.URL)
if err != nil {
return err
}
logrus.Debugf("Connecting to websocket: %q", target.String())
if c.SkipTLSVerify {
c.Dialer.TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
}
if c.UseProxyFromEnv {
c.Dialer.Proxy = http.ProxyFromEnvironment
}
conn, _, err := c.Dialer.Dial(target.String(), *header)
if err != nil {
return err
}
c.Conn = conn
c.Connected = true
// Pass arguments and auth-token
query, err := GetURLQuery(c.URL)
if err != nil {
return err
}
querySingle := querySingleType{
Arguments: "?" + query.Encode(),
AuthToken: authToken,
}
json, err := json.Marshal(querySingle)
if err != nil {
logrus.Errorf("Failed to parse init message %v", err)
return err
}
// Send Json
logrus.Debugf("Sending arguments and auth-token")
err = c.write(json)
if err != nil {
return err
}
go c.pingLoop()
return nil
}
func (c *Client) pingLoop() {
for {
logrus.Debugf("Sending ping")
c.write([]byte("1"))
time.Sleep(30 * time.Second)
}
}
// Close will nicely close the dialer
func (c *Client) Close() {
c.Conn.Close()
}
// ExitLoop will kill all goroutines launched by c.Loop()
// ExitLoop() -> wait Loop() -> Close()
func (c *Client) ExitLoop() {
fname := "ExitLoop"
openPoison(fname, c.poison)
}
// Loop will look indefinitely for new messages
func (c *Client) Loop() error {
if !c.Connected {
err := c.Connect()
if err != nil {
return err
}
}
wg := &sync.WaitGroup{}
wg.Add(1)
go c.termsizeLoop(wg)
wg.Add(1)
go c.readLoop(wg)
wg.Add(1)
go c.writeLoop(wg)
/* Wait for all of the above goroutines to finish */
wg.Wait()
logrus.Debug("Client.Loop() exiting")
return nil
}
type winsize struct {
Rows uint16 `json:"rows"`
Columns uint16 `json:"columns"`
// unused
x uint16
y uint16
}
type posionReason int
const (
committedSuicide = iota
killed
)
func openPoison(fname string, poison chan bool) posionReason {
logrus.Debug(fname + " suicide")
/*
* The close() may raise panic if multiple goroutines commit suicide at the
* same time. Prevent that panic from bubbling up.
*/
defer func() {
if r := recover(); r != nil {
logrus.Debug("Prevented panic() of simultaneous suicides", r)
}
}()
/* Signal others to die */
close(poison)
return committedSuicide
}
func die(fname string, poison chan bool) posionReason {
logrus.Debug(fname + " died")
wasOpen := <-poison
if wasOpen {
logrus.Error("ERROR: The channel was open when it wasn't suppoed to be")
}
return killed
}
func (c *Client) termsizeLoop(wg *sync.WaitGroup) posionReason {
defer wg.Done()
fname := "termsizeLoop"
ch := make(chan os.Signal, 1)
notifySignalSIGWINCH(ch)
defer resetSignalSIGWINCH()
for {
if b, err := syscallTIOCGWINSZ(); err != nil {
logrus.Warn(err)
} else {
if err = c.write(append([]byte("2"), b...)); err != nil {
logrus.Warnf("ws.WriteMessage failed: %v", err)
}
}
select {
case <-c.poison:
/* Somebody poisoned the well; die */
return die(fname, c.poison)
case <-ch:
}
}
}
type exposeFd interface {
Fd() uintptr
}
func (c *Client) writeLoop(wg *sync.WaitGroup) posionReason {
defer wg.Done()
fname := "writeLoop"
buff := make([]byte, 128)
oldState, err := terminal.MakeRaw(0)
if err == nil {
defer terminal.Restore(0, oldState)
}
rdfs := &goselect.FDSet{}
reader := io.Reader(os.Stdin)
for {
select {
case <-c.poison:
/* Somebody poisoned the well; die */
return die(fname, c.poison)
default:
}
rdfs.Zero()
rdfs.Set(reader.(exposeFd).Fd())
err := goselect.Select(1, rdfs, nil, nil, 50*time.Millisecond)
if err != nil {
return openPoison(fname, c.poison)
}
if rdfs.IsSet(reader.(exposeFd).Fd()) {
size, err := reader.Read(buff)
if err != nil {
if err == io.EOF {
// Send EOF to GoTTY
// Send 'Input' marker, as defined in GoTTY::client_context.go,
// followed by EOT (a translation of Ctrl-D for terminals)
err = c.write(append([]byte("0"), byte(4)))
if err != nil {
return openPoison(fname, c.poison)
}
continue
} else {
return openPoison(fname, c.poison)
}
}
if size <= 0 {
continue
}
data := buff[:size]
err = c.write(append([]byte("0"), data...))
if err != nil {
return openPoison(fname, c.poison)
}
}
}
}
func (c *Client) readLoop(wg *sync.WaitGroup) posionReason {
defer wg.Done()
fname := "readLoop"
type MessageNonBlocking struct {
Data []byte
Err error
}
msgChan := make(chan MessageNonBlocking)
for {
go func() {
_, data, err := c.Conn.ReadMessage()
msgChan <- MessageNonBlocking{Data: data, Err: err}
}()
select {
case <-c.poison:
/* Somebody poisoned the well; die */
return die(fname, c.poison)
case msg := <-msgChan:
if msg.Err != nil {
if _, ok := msg.Err.(*websocket.CloseError); !ok {
logrus.Warnf("c.Conn.ReadMessage: %v", msg.Err)
}
return openPoison(fname, c.poison)
}
if len(msg.Data) == 0 {
logrus.Warnf("An error has occured")
return openPoison(fname, c.poison)
}
switch msg.Data[0] {
case '0': // data
buf, err := base64.StdEncoding.DecodeString(string(msg.Data[1:]))
if err != nil {
logrus.Warnf("Invalid base64 content: %q", msg.Data[1:])
break
}
c.Output.Write(buf)
case '1': // pong
case '2': // new title
newTitle := string(msg.Data[1:])
fmt.Fprintf(c.Output, "\033]0;%s\007", newTitle)
case '3': // json prefs
logrus.Debugf("Unhandled protocol message: json pref: %s", string(msg.Data[1:]))
case '4': // autoreconnect
logrus.Debugf("Unhandled protocol message: autoreconnect: %s", string(msg.Data))
default:
logrus.Warnf("Unhandled protocol message: %s", string(msg.Data))
}
}
}
}
// SetOutput changes the output stream
func (c *Client) SetOutput(w io.Writer) {
c.Output = w
}
// ParseURL parses an URL which may be incomplete and tries to standardize it
func ParseURL(input string) (string, error) {
parsed, err := url.Parse(input)
if err != nil {
return "", err
}
switch parsed.Scheme {
case "http", "https":
// everything is ok
default:
return ParseURL(fmt.Sprintf("http://%s", input))
}
return parsed.String(), nil
}
// NewClient returns a GoTTY client object
func NewClient(inputURL string) (*Client, error) {
url, err := ParseURL(inputURL)
if err != nil {
return nil, err
}
return &Client{
Dialer: &websocket.Dialer{},
URL: url,
WriteMutex: &sync.Mutex{},
Output: os.Stdout,
poison: make(chan bool),
}, nil
}

View File

@ -0,0 +1,680 @@
// Copyright (C) 2015 Scaleway. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE.md file.
package api
import (
"errors"
"fmt"
"os"
"sort"
"strings"
"sync"
"time"
"github.com/Sirupsen/logrus"
log "github.com/Sirupsen/logrus"
"github.com/docker/docker/pkg/namesgenerator"
"github.com/dustin/go-humanize"
"github.com/moul/anonuuid"
"github.com/scaleway/scaleway-cli/pkg/utils"
)
// ScalewayResolvedIdentifier represents a list of matching identifier for a specifier pattern
type ScalewayResolvedIdentifier struct {
// Identifiers holds matching identifiers
Identifiers ScalewayResolverResults
// Needle is the criteria used to lookup identifiers
Needle string
}
// ScalewayImageInterface is an interface to multiple Scaleway items
type ScalewayImageInterface struct {
CreationDate time.Time
Identifier string
Name string
Tag string
VirtualSize uint64
Public bool
Type string
Organization string
Archs []string
Region []string
}
// ResolveGateway tries to resolve a server public ip address, else returns the input string, i.e. IPv4, hostname
func ResolveGateway(api *ScalewayAPI, gateway string) (string, error) {
if gateway == "" {
return "", nil
}
// Parses optional type prefix, i.e: "server:name" -> "name"
_, gateway = parseNeedle(gateway)
servers, err := api.ResolveServer(gateway)
if err != nil {
return "", err
}
if len(servers) == 0 {
return gateway, nil
}
if len(servers) > 1 {
return "", showResolverResults(gateway, servers)
}
// if len(servers) == 1 {
server, err := api.GetServer(servers[0].Identifier)
if err != nil {
return "", err
}
return server.PublicAddress.IP, nil
}
// CreateVolumeFromHumanSize creates a volume on the API with a human readable size
func CreateVolumeFromHumanSize(api *ScalewayAPI, size string) (*string, error) {
bytes, err := humanize.ParseBytes(size)
if err != nil {
return nil, err
}
var newVolume ScalewayVolumeDefinition
newVolume.Name = size
newVolume.Size = bytes
newVolume.Type = "l_ssd"
volumeID, err := api.PostVolume(newVolume)
if err != nil {
return nil, err
}
return &volumeID, nil
}
// fillIdentifierCache fills the cache by fetching from the API
func fillIdentifierCache(api *ScalewayAPI, identifierType int) {
log.Debugf("Filling the cache")
var wg sync.WaitGroup
wg.Add(5)
go func() {
if identifierType&(IdentifierUnknown|IdentifierServer) > 0 {
api.GetServers(true, 0)
}
wg.Done()
}()
go func() {
if identifierType&(IdentifierUnknown|IdentifierImage) > 0 {
api.GetImages()
}
wg.Done()
}()
go func() {
if identifierType&(IdentifierUnknown|IdentifierSnapshot) > 0 {
api.GetSnapshots()
}
wg.Done()
}()
go func() {
if identifierType&(IdentifierUnknown|IdentifierVolume) > 0 {
api.GetVolumes()
}
wg.Done()
}()
go func() {
if identifierType&(IdentifierUnknown|IdentifierBootscript) > 0 {
api.GetBootscripts()
}
wg.Done()
}()
wg.Wait()
}
// GetIdentifier returns a an identifier if the resolved needles only match one element, else, it exists the program
func GetIdentifier(api *ScalewayAPI, needle string) (*ScalewayResolverResult, error) {
idents, err := ResolveIdentifier(api, needle)
if err != nil {
return nil, err
}
if len(idents) == 1 {
return &idents[0], nil
}
if len(idents) == 0 {
return nil, fmt.Errorf("No such identifier: %s", needle)
}
sort.Sort(idents)
for _, identifier := range idents {
// FIXME: also print the name
fmt.Fprintf(os.Stderr, "- %s\n", identifier.Identifier)
}
return nil, fmt.Errorf("Too many candidates for %s (%d)", needle, len(idents))
}
// ResolveIdentifier resolves needle provided by the user
func ResolveIdentifier(api *ScalewayAPI, needle string) (ScalewayResolverResults, error) {
idents, err := api.Cache.LookUpIdentifiers(needle)
if err != nil {
return idents, err
}
if len(idents) > 0 {
return idents, nil
}
identifierType, _ := parseNeedle(needle)
fillIdentifierCache(api, identifierType)
return api.Cache.LookUpIdentifiers(needle)
}
// ResolveIdentifiers resolves needles provided by the user
func ResolveIdentifiers(api *ScalewayAPI, needles []string, out chan ScalewayResolvedIdentifier) {
// first attempt, only lookup from the cache
var unresolved []string
for _, needle := range needles {
idents, err := api.Cache.LookUpIdentifiers(needle)
if err != nil {
api.Logger.Fatalf("%s", err)
}
if len(idents) == 0 {
unresolved = append(unresolved, needle)
} else {
out <- ScalewayResolvedIdentifier{
Identifiers: idents,
Needle: needle,
}
}
}
// fill the cache by fetching from the API and resolve missing identifiers
if len(unresolved) > 0 {
// compute identifierType:
// if identifierType is the same for every unresolved needle,
// we use it directly, else, we choose IdentifierUnknown to
// fulfill every types of cache
identifierType, _ := parseNeedle(unresolved[0])
for _, needle := range unresolved {
newIdentifierType, _ := parseNeedle(needle)
if identifierType != newIdentifierType {
identifierType = IdentifierUnknown
break
}
}
// fill all the cache
fillIdentifierCache(api, identifierType)
// lookup again in the cache
for _, needle := range unresolved {
idents, err := api.Cache.LookUpIdentifiers(needle)
if err != nil {
api.Logger.Fatalf("%s", err)
}
out <- ScalewayResolvedIdentifier{
Identifiers: idents,
Needle: needle,
}
}
}
close(out)
}
// InspectIdentifierResult is returned by `InspectIdentifiers` and contains the inspected `Object` with its `Type`
type InspectIdentifierResult struct {
Type int
Object interface{}
}
// InspectIdentifiers inspects identifiers concurrently
func InspectIdentifiers(api *ScalewayAPI, ci chan ScalewayResolvedIdentifier, cj chan InspectIdentifierResult, arch string) {
var wg sync.WaitGroup
for {
idents, ok := <-ci
if !ok {
break
}
idents.Identifiers = FilterImagesByArch(idents.Identifiers, arch)
idents.Identifiers = FilterImagesByRegion(idents.Identifiers, api.Region)
if len(idents.Identifiers) != 1 {
if len(idents.Identifiers) == 0 {
log.Errorf("Unable to resolve identifier %s", idents.Needle)
} else {
logrus.Fatal(showResolverResults(idents.Needle, idents.Identifiers))
}
} else {
ident := idents.Identifiers[0]
wg.Add(1)
go func() {
var obj interface{}
var err error
switch ident.Type {
case IdentifierServer:
obj, err = api.GetServer(ident.Identifier)
case IdentifierImage:
obj, err = api.GetImage(ident.Identifier)
case IdentifierSnapshot:
obj, err = api.GetSnapshot(ident.Identifier)
case IdentifierVolume:
obj, err = api.GetVolume(ident.Identifier)
case IdentifierBootscript:
obj, err = api.GetBootscript(ident.Identifier)
}
if err == nil && obj != nil {
cj <- InspectIdentifierResult{
Type: ident.Type,
Object: obj,
}
}
wg.Done()
}()
}
}
wg.Wait()
close(cj)
}
// ConfigCreateServer represents the options sent to CreateServer and defining a server
type ConfigCreateServer struct {
ImageName string
Name string
Bootscript string
Env string
AdditionalVolumes string
IP string
CommercialType string
DynamicIPRequired bool
EnableIPV6 bool
}
// CreateServer creates a server using API based on typical server fields
func CreateServer(api *ScalewayAPI, c *ConfigCreateServer) (string, error) {
commercialType := os.Getenv("SCW_COMMERCIAL_TYPE")
if commercialType == "" {
commercialType = c.CommercialType
}
if len(commercialType) < 2 {
return "", errors.New("Invalid commercial type")
}
if c.Name == "" {
c.Name = strings.Replace(namesgenerator.GetRandomName(0), "_", "-", -1)
}
var server ScalewayServerDefinition
server.CommercialType = commercialType
server.Volumes = make(map[string]string)
server.DynamicIPRequired = &c.DynamicIPRequired
server.EnableIPV6 = c.EnableIPV6
if commercialType == "" {
return "", errors.New("You need to specify a commercial-type")
}
if c.IP != "" {
if anonuuid.IsUUID(c.IP) == nil {
server.PublicIP = c.IP
} else {
ips, err := api.GetIPS()
if err != nil {
return "", err
}
for _, ip := range ips.IPS {
if ip.Address == c.IP {
server.PublicIP = ip.ID
break
}
}
if server.PublicIP == "" {
return "", fmt.Errorf("IP address %v not found", c.IP)
}
}
}
server.Tags = []string{}
if c.Env != "" {
server.Tags = strings.Split(c.Env, " ")
}
switch c.CommercialType {
case "VC1M", "X64-4GB":
if c.AdditionalVolumes == "" {
c.AdditionalVolumes = "50G"
log.Debugf("This server needs a least 50G")
}
case "VC1L", "X64-8GB":
if c.AdditionalVolumes == "" {
c.AdditionalVolumes = "150G"
log.Debugf("This server needs a least 150G")
}
case "X64-60GB":
if c.AdditionalVolumes == "" {
c.AdditionalVolumes = "50G 150G 150G"
log.Debugf("This server needs a least 400G")
}
case "X64-120GB":
if c.AdditionalVolumes == "" {
c.AdditionalVolumes = "150G 150G 150G"
log.Debugf("This server needs a least 500G")
}
}
if c.AdditionalVolumes != "" {
volumes := strings.Split(c.AdditionalVolumes, " ")
for i := range volumes {
volumeID, err := CreateVolumeFromHumanSize(api, volumes[i])
if err != nil {
return "", err
}
volumeIDx := fmt.Sprintf("%d", i+1)
server.Volumes[volumeIDx] = *volumeID
}
}
arch := os.Getenv("SCW_TARGET_ARCH")
if arch == "" {
server.CommercialType = strings.ToUpper(server.CommercialType)
switch server.CommercialType[:2] {
case "C1":
arch = "arm"
case "C2", "VC", "X6":
arch = "x86_64"
default:
return "", fmt.Errorf("%s wrong commercial type", server.CommercialType)
}
}
imageIdentifier := &ScalewayImageIdentifier{
Arch: arch,
}
server.Name = c.Name
inheritingVolume := false
_, err := humanize.ParseBytes(c.ImageName)
if err == nil {
// Create a new root volume
volumeID, errCreateVol := CreateVolumeFromHumanSize(api, c.ImageName)
if errCreateVol != nil {
return "", errCreateVol
}
server.Volumes["0"] = *volumeID
} else {
// Use an existing image
inheritingVolume = true
if anonuuid.IsUUID(c.ImageName) == nil {
server.Image = &c.ImageName
} else {
imageIdentifier, err = api.GetImageID(c.ImageName, arch)
if err != nil {
return "", err
}
if imageIdentifier.Identifier != "" {
server.Image = &imageIdentifier.Identifier
} else {
snapshotID, errGetSnapID := api.GetSnapshotID(c.ImageName)
if errGetSnapID != nil {
return "", errGetSnapID
}
snapshot, errGetSnap := api.GetSnapshot(snapshotID)
if errGetSnap != nil {
return "", errGetSnap
}
if snapshot.BaseVolume.Identifier == "" {
return "", fmt.Errorf("snapshot %v does not have base volume", snapshot.Name)
}
server.Volumes["0"] = snapshot.BaseVolume.Identifier
}
}
}
if c.Bootscript != "" {
bootscript := ""
if anonuuid.IsUUID(c.Bootscript) == nil {
bootscript = c.Bootscript
} else {
var errGetBootScript error
bootscript, errGetBootScript = api.GetBootscriptID(c.Bootscript, imageIdentifier.Arch)
if errGetBootScript != nil {
return "", errGetBootScript
}
}
server.Bootscript = &bootscript
}
serverID, err := api.PostServer(server)
if err != nil {
return "", err
}
// For inherited volumes, we prefix the name with server hostname
if inheritingVolume {
createdServer, err := api.GetServer(serverID)
if err != nil {
return "", err
}
currentVolume := createdServer.Volumes["0"]
var volumePayload ScalewayVolumePutDefinition
newName := fmt.Sprintf("%s-%s", createdServer.Hostname, currentVolume.Name)
volumePayload.Name = &newName
volumePayload.CreationDate = &currentVolume.CreationDate
volumePayload.Organization = &currentVolume.Organization
volumePayload.Server.Identifier = &currentVolume.Server.Identifier
volumePayload.Server.Name = &currentVolume.Server.Name
volumePayload.Identifier = &currentVolume.Identifier
volumePayload.Size = &currentVolume.Size
volumePayload.ModificationDate = &currentVolume.ModificationDate
volumePayload.ExportURI = &currentVolume.ExportURI
volumePayload.VolumeType = &currentVolume.VolumeType
err = api.PutVolume(currentVolume.Identifier, volumePayload)
if err != nil {
return "", err
}
}
return serverID, nil
}
// WaitForServerState asks API in a loop until a server matches a wanted state
func WaitForServerState(api *ScalewayAPI, serverID string, targetState string) (*ScalewayServer, error) {
var server *ScalewayServer
var err error
var currentState string
for {
server, err = api.GetServer(serverID)
if err != nil {
return nil, err
}
if currentState != server.State {
log.Infof("Server changed state to '%s'", server.State)
currentState = server.State
}
if server.State == targetState {
break
}
time.Sleep(1 * time.Second)
}
return server, nil
}
// WaitForServerReady wait for a server state to be running, then wait for the SSH port to be available
func WaitForServerReady(api *ScalewayAPI, serverID, gateway string) (*ScalewayServer, error) {
promise := make(chan bool)
var server *ScalewayServer
var err error
var currentState string
go func() {
defer close(promise)
for {
server, err = api.GetServer(serverID)
if err != nil {
promise <- false
return
}
if currentState != server.State {
log.Infof("Server changed state to '%s'", server.State)
currentState = server.State
}
if server.State == "running" {
break
}
if server.State == "stopped" {
err = fmt.Errorf("The server has been stopped")
promise <- false
return
}
time.Sleep(1 * time.Second)
}
if gateway == "" {
dest := fmt.Sprintf("%s:22", server.PublicAddress.IP)
log.Debugf("Waiting for server SSH port %s", dest)
err = utils.WaitForTCPPortOpen(dest)
if err != nil {
promise <- false
return
}
} else {
dest := fmt.Sprintf("%s:22", gateway)
log.Debugf("Waiting for server SSH port %s", dest)
err = utils.WaitForTCPPortOpen(dest)
if err != nil {
promise <- false
return
}
log.Debugf("Check for SSH port through the gateway: %s", server.PrivateIP)
timeout := time.Tick(120 * time.Second)
for {
select {
case <-timeout:
err = fmt.Errorf("Timeout: unable to ping %s", server.PrivateIP)
goto OUT
default:
if utils.SSHExec("", server.PrivateIP, "root", 22, []string{
"nc",
"-z",
"-w",
"1",
server.PrivateIP,
"22",
}, false, gateway, false) == nil {
goto OUT
}
time.Sleep(2 * time.Second)
}
}
OUT:
if err != nil {
logrus.Info(err)
err = nil
}
}
promise <- true
}()
loop := 0
for {
select {
case done := <-promise:
utils.LogQuiet("\r \r")
if !done {
return nil, err
}
return server, nil
case <-time.After(time.Millisecond * 100):
utils.LogQuiet(fmt.Sprintf("\r%c\r", "-\\|/"[loop%4]))
loop = loop + 1
if loop == 5 {
loop = 0
}
}
}
}
// WaitForServerStopped wait for a server state to be stopped
func WaitForServerStopped(api *ScalewayAPI, serverID string) (*ScalewayServer, error) {
server, err := WaitForServerState(api, serverID, "stopped")
if err != nil {
return nil, err
}
return server, nil
}
// ByCreationDate sorts images by CreationDate field
type ByCreationDate []ScalewayImageInterface
func (a ByCreationDate) Len() int { return len(a) }
func (a ByCreationDate) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a ByCreationDate) Less(i, j int) bool { return a[j].CreationDate.Before(a[i].CreationDate) }
// StartServer start a server based on its needle, can optionaly block while server is booting
func StartServer(api *ScalewayAPI, needle string, wait bool) error {
server, err := api.GetServerID(needle)
if err != nil {
return err
}
if err = api.PostServerAction(server, "poweron"); err != nil {
return err
}
if wait {
_, err = WaitForServerReady(api, server, "")
if err != nil {
return fmt.Errorf("failed to wait for server %s to be ready, %v", needle, err)
}
}
return nil
}
// StartServerOnce wraps StartServer for golang channel
func StartServerOnce(api *ScalewayAPI, needle string, wait bool, successChan chan string, errChan chan error) {
err := StartServer(api, needle, wait)
if err != nil {
errChan <- err
return
}
successChan <- needle
}
// DeleteServerForce tries to delete a server using multiple ways
func (a *ScalewayAPI) DeleteServerForce(serverID string) error {
// FIXME: also delete attached volumes and ip address
// FIXME: call delete and stop -t in parallel to speed up process
err := a.DeleteServer(serverID)
if err == nil {
logrus.Infof("Server '%s' successfully deleted", serverID)
return nil
}
err = a.PostServerAction(serverID, "terminate")
if err == nil {
logrus.Infof("Server '%s' successfully terminated", serverID)
return nil
}
// FIXME: retry in a loop until timeout or Control+C
logrus.Errorf("Failed to delete server %s", serverID)
logrus.Errorf("Try to run 'scw rm -f %s' later", serverID)
return err
}
// GetSSHFingerprintFromServer returns an array which containts ssh-host-fingerprints
func (a *ScalewayAPI) GetSSHFingerprintFromServer(serverID string) []string {
ret := []string{}
if value, err := a.GetUserdata(serverID, "ssh-host-fingerprints", false); err == nil {
PublicKeys := strings.Split(string(*value), "\n")
for i := range PublicKeys {
if fingerprint, err := utils.SSHGetFingerprint([]byte(PublicKeys[i])); err == nil {
ret = append(ret, fingerprint)
}
}
}
return ret
}

View File

@ -4,7 +4,7 @@ import "fmt"
var (
// VERSION represents the semver version of the package
VERSION = "v1.11+dev"
VERSION = "v1.11.1+dev"
// GITCOMMIT represents the git commit hash of the package, it is configured at build time
GITCOMMIT string

View File

@ -0,0 +1,30 @@
// Copyright (C) 2015 Scaleway. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE.md file.
// Package utils contains logquiet
package utils
import (
"fmt"
"os"
)
// LogQuietStruct is a struct to store information about quiet state
type LogQuietStruct struct {
quiet bool
}
var instanceQuiet LogQuietStruct
// Quiet enable or disable quiet
func Quiet(option bool) {
instanceQuiet.quiet = option
}
// LogQuiet Displays info if quiet is activated
func LogQuiet(str string) {
if !instanceQuiet.quiet {
fmt.Fprintf(os.Stderr, "%s", str)
}
}

View File

@ -0,0 +1,253 @@
// Copyright (C) 2015 Scaleway. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE.md file.
// scw helpers
// Package utils contains helpers
package utils
import (
"crypto/md5"
"errors"
"fmt"
"io"
"net"
"os"
"os/exec"
"path"
"path/filepath"
"reflect"
"regexp"
"strings"
"time"
"golang.org/x/crypto/ssh"
"github.com/Sirupsen/logrus"
log "github.com/Sirupsen/logrus"
"github.com/mattn/go-isatty"
"github.com/moul/gotty-client"
"github.com/scaleway/scaleway-cli/pkg/sshcommand"
)
// SpawnRedirection is used to redirects the fluxes
type SpawnRedirection struct {
Stdin io.Reader
Stdout io.Writer
Stderr io.Writer
}
// SSHExec executes a command over SSH and redirects file-descriptors
func SSHExec(publicIPAddress, privateIPAddress, user string, port int, command []string, checkConnection bool, gateway string, enableSSHKeyForwarding bool) error {
gatewayUser := "root"
gatewayIPAddress := gateway
if strings.Contains(gateway, "@") {
parts := strings.Split(gatewayIPAddress, "@")
if len(parts) != 2 {
return fmt.Errorf("gateway: must be like root@IP")
}
gatewayUser = parts[0]
gatewayIPAddress = parts[1]
gateway = gatewayUser + "@" + gatewayIPAddress
}
if publicIPAddress == "" && gatewayIPAddress == "" {
return errors.New("server does not have public IP")
}
if privateIPAddress == "" && gatewayIPAddress != "" {
return errors.New("server does not have private IP")
}
if checkConnection {
useGateway := gatewayIPAddress != ""
if useGateway && !IsTCPPortOpen(fmt.Sprintf("%s:22", gatewayIPAddress)) {
return errors.New("gateway is not available, try again later")
}
if !useGateway && !IsTCPPortOpen(fmt.Sprintf("%s:%d", publicIPAddress, port)) {
return errors.New("server is not ready, try again later")
}
}
sshCommand := NewSSHExecCmd(publicIPAddress, privateIPAddress, user, port, isatty.IsTerminal(os.Stdin.Fd()), command, gateway, enableSSHKeyForwarding)
log.Debugf("Executing: %s", sshCommand)
spawn := exec.Command("ssh", sshCommand.Slice()[1:]...)
spawn.Stdout = os.Stdout
spawn.Stdin = os.Stdin
spawn.Stderr = os.Stderr
return spawn.Run()
}
// NewSSHExecCmd computes execve compatible arguments to run a command via ssh
func NewSSHExecCmd(publicIPAddress, privateIPAddress, user string, port int, allocateTTY bool, command []string, gatewayIPAddress string, enableSSHKeyForwarding bool) *sshcommand.Command {
quiet := os.Getenv("DEBUG") != "1"
secureExec := os.Getenv("SCW_SECURE_EXEC") == "1"
sshCommand := &sshcommand.Command{
AllocateTTY: allocateTTY,
Command: command,
Host: publicIPAddress,
Quiet: quiet,
SkipHostKeyChecking: !secureExec,
User: user,
NoEscapeCommand: true,
Port: port,
EnableSSHKeyForwarding: enableSSHKeyForwarding,
}
if gatewayIPAddress != "" {
sshCommand.Host = privateIPAddress
sshCommand.Gateway = &sshcommand.Command{
Host: gatewayIPAddress,
SkipHostKeyChecking: !secureExec,
AllocateTTY: allocateTTY,
Quiet: quiet,
User: user,
Port: port,
}
}
return sshCommand
}
// GeneratingAnSSHKey generates an SSH key
func GeneratingAnSSHKey(cfg SpawnRedirection, path string, name string) (string, error) {
args := []string{
"-t",
"rsa",
"-b",
"4096",
"-f",
filepath.Join(path, name),
"-N",
"",
"-C",
"",
}
log.Infof("Executing commands %v", args)
spawn := exec.Command("ssh-keygen", args...)
spawn.Stdout = cfg.Stdout
spawn.Stdin = cfg.Stdin
spawn.Stderr = cfg.Stderr
return args[5], spawn.Run()
}
// WaitForTCPPortOpen calls IsTCPPortOpen in a loop
func WaitForTCPPortOpen(dest string) error {
for {
if IsTCPPortOpen(dest) {
break
}
time.Sleep(1 * time.Second)
}
return nil
}
// IsTCPPortOpen returns true if a TCP communication with "host:port" can be initialized
func IsTCPPortOpen(dest string) bool {
conn, err := net.DialTimeout("tcp", dest, time.Duration(2000)*time.Millisecond)
if err == nil {
defer conn.Close()
}
return err == nil
}
// TruncIf ensures the input string does not exceed max size if cond is met
func TruncIf(str string, max int, cond bool) string {
if cond && len(str) > max {
return str[:max]
}
return str
}
// Wordify convert complex name to a single word without special shell characters
func Wordify(str string) string {
str = regexp.MustCompile(`[^a-zA-Z0-9-]`).ReplaceAllString(str, "_")
str = regexp.MustCompile(`__+`).ReplaceAllString(str, "_")
str = strings.Trim(str, "_")
return str
}
// PathToTARPathparts returns the two parts of a unix path
func PathToTARPathparts(fullPath string) (string, string) {
fullPath = strings.TrimRight(fullPath, "/")
return path.Dir(fullPath), path.Base(fullPath)
}
// RemoveDuplicates transforms an array into a unique array
func RemoveDuplicates(elements []string) []string {
encountered := map[string]bool{}
// Create a map of all unique elements.
for v := range elements {
encountered[elements[v]] = true
}
// Place all keys from the map into a slice.
result := []string{}
for key := range encountered {
result = append(result, key)
}
return result
}
// AttachToSerial tries to connect to server serial using 'gotty-client' and fallback with a help message
func AttachToSerial(serverID, apiToken, url string) (*gottyclient.Client, chan bool, error) {
gottyURL := os.Getenv("SCW_GOTTY_URL")
if gottyURL == "" {
gottyURL = url
}
URL := fmt.Sprintf("%s?arg=%s&arg=%s", gottyURL, apiToken, serverID)
logrus.Debug("Connection to ", URL)
gottycli, err := gottyclient.NewClient(URL)
if err != nil {
return nil, nil, err
}
if os.Getenv("SCW_TLSVERIFY") == "0" {
gottycli.SkipTLSVerify = true
}
gottycli.UseProxyFromEnv = true
if err = gottycli.Connect(); err != nil {
return nil, nil, err
}
done := make(chan bool)
fmt.Println("You are connected, type 'Ctrl+q' to quit.")
go func() {
gottycli.Loop()
gottycli.Close()
done <- true
}()
return gottycli, done, nil
}
func rfc4716hex(data []byte) string {
fingerprint := ""
for i := 0; i < len(data); i++ {
fingerprint = fmt.Sprintf("%s%0.2x", fingerprint, data[i])
if i != len(data)-1 {
fingerprint = fingerprint + ":"
}
}
return fingerprint
}
// SSHGetFingerprint returns the fingerprint of an SSH key
func SSHGetFingerprint(key []byte) (string, error) {
publicKey, comment, _, _, err := ssh.ParseAuthorizedKey(key)
if err != nil {
return "", err
}
switch reflect.TypeOf(publicKey).String() {
case "*ssh.rsaPublicKey", "*ssh.dsaPublicKey", "*ssh.ecdsaPublicKey":
md5sum := md5.Sum(publicKey.Marshal())
return publicKey.Type() + " " + rfc4716hex(md5sum[:]) + " " + comment, nil
default:
return "", errors.New("Can't handle this key")
}
}

39
vendor/vendor.json vendored
View File

@ -1316,6 +1316,18 @@
"revision": "50133d63723f8fa376e632a853739990a133be16",
"revisionTime": "2017-02-21T19:08:14Z"
},
{
"checksumSHA1": "fIcQAnRueVtFU2fqw+2ajJ8MfJo=",
"path": "github.com/docker/docker/pkg/namesgenerator",
"revision": "3470c8d7676ec7e16db2f2be32805c569ad9448e",
"revisionTime": "2017-02-24T14:35:27Z"
},
{
"checksumSHA1": "lThih54jzz9A4zHKEFb9SIV3Ed0=",
"path": "github.com/docker/docker/pkg/random",
"revision": "3470c8d7676ec7e16db2f2be32805c569ad9448e",
"revisionTime": "2017-02-24T14:35:27Z"
},
{
"checksumSHA1": "zkENTbOfU8YoxPfFwVAhTz516Dg=",
"path": "github.com/dustin/go-humanize",
@ -2433,6 +2445,12 @@
"revision": "609b752a95effbbef26d134ac18ed6f57e01b98e",
"revisionTime": "2016-02-22T16:21:17Z"
},
{
"checksumSHA1": "WcXDSYIAP73RAvy22iD57nE/peI=",
"path": "github.com/moul/gotty-client",
"revision": "99224eea3278d662fce9124bb2bf6c2bb39f5160",
"revisionTime": "2017-02-05T09:54:39Z"
},
{
"checksumSHA1": "/iig5lYSPCL3C8J7e4nTAevYNDE=",
"comment": "v0.2.0-8-g841842b",
@ -2669,21 +2687,28 @@
"revisionTime": "2016-09-27T10:08:44Z"
},
{
"checksumSHA1": "/hY/JUzzV5+IMAGkfTGI3VA4k9Y=",
"path": "github.com/scaleway/scaleway-cli/pkg/api",
"revision": "15e90c8d6bd96a674cfe6539f0dc0fa122a7412b",
"revisionTime": "2016-12-07T13:39:28Z"
"revision": "2938313569b7f6cee34fdaae2a23c0daa7de5f3c",
"revisionTime": "2017-02-07T21:56:28Z"
},
{
"checksumSHA1": "aU2+iXO1oHS4vBtAXXBgicA9YBY=",
"checksumSHA1": "puRmTVCmWrk+Qq6/yeHjNC3uvy0=",
"path": "github.com/scaleway/scaleway-cli/pkg/scwversion",
"revision": "88132ecdd39da62f7c73c5a8e1a383d7da5e0e09",
"revisionTime": "2016-10-27T15:40:24Z"
"revision": "2938313569b7f6cee34fdaae2a23c0daa7de5f3c",
"revisionTime": "2017-02-07T21:56:28Z"
},
{
"checksumSHA1": "kveaAmNlnvmIIuEkFcMlB+N7TqY=",
"path": "github.com/scaleway/scaleway-cli/pkg/sshcommand",
"revision": "15e90c8d6bd96a674cfe6539f0dc0fa122a7412b",
"revisionTime": "2016-12-07T13:39:28Z"
"revision": "2938313569b7f6cee34fdaae2a23c0daa7de5f3c",
"revisionTime": "2017-02-07T21:56:28Z"
},
{
"checksumSHA1": "xM3G5ct9YYYnVIL3XMRrcf41xVw=",
"path": "github.com/scaleway/scaleway-cli/pkg/utils",
"revision": "2938313569b7f6cee34fdaae2a23c0daa7de5f3c",
"revisionTime": "2017-02-07T21:56:28Z"
},
{
"checksumSHA1": "tEKRyau4iRjmq2iwJbduD9RhN5s=",